def test_encrypt_decrypt_without_assoc(self): # generate keyring self.set_password('system', 'user', 'password') config = self.get_config() # generate and save password without assoc data encrypted = self.keyring.encrypt('password'.encode('utf-8')) password_base64 = '\n' + encodebytes(encrypted).decode() config.set('system', 'user', password_base64) self.save_config(config) assert self.keyring.get_password('system', 'user') == 'password'
def encrypt(self, password, assoc=None): salt = os.urandom(16) cipher = self._create_cipher(self.keyring_key, salt) if assoc is not None: cipher.update(assoc) data, mac = cipher.encrypt_and_digest(password) # Serialize salt, encrypted password, mac and nonce in a portable format data = dict(salt=salt, data=data, mac=mac, nonce=cipher.nonce) for key in data: # spare a few bytes: throw away newline from base64 encoding data[key] = encodebytes(data[key]).decode()[:-1] return json.dumps(data).encode()
def encrypt(self, password, assoc=None): # encrypt password, ignore associated data from Crypto.Random import get_random_bytes salt = get_random_bytes(self.block_size) from Crypto.Cipher import AES IV = get_random_bytes(AES.block_size) cipher = self._create_cipher(self.keyring_key, salt, IV) password_encrypted = cipher.encrypt(self.pw_prefix + password) # Serialize the salt, IV, and encrypted password in a secure format data = dict(salt=salt, IV=IV, password_encrypted=password_encrypted) for key in data: # spare a few bytes: throw away newline from base64 encoding data[key] = encodebytes(data[key]).decode()[:-1] return json.dumps(data).encode()