Example #1
0
    def _decrypt_cryptography(cls, b_salt, b_ciphertext, b_password,
                              key_length):
        bs = algorithms.AES.block_size // 8
        b_key, b_iv = cls._aes_derive_key_and_iv(b_password, b_salt,
                                                 key_length, bs)
        cipher = C_Cipher(algorithms.AES(b_key), modes.CBC(b_iv),
                          CRYPTOGRAPHY_BACKEND).decryptor()
        unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

        try:
            b_plaintext = unpadder.update(
                cipher.update(b_ciphertext) +
                cipher.finalize()) + unpadder.finalize()
        except ValueError:
            # In VaultAES, ValueError: invalid padding bytes can mean bad
            # password was given
            raise AnsibleError("Decryption failed")

        # split out sha and verify decryption
        b_split_data = b_plaintext.split(b"\n", 1)
        b_this_sha = b_split_data[0]
        b_plaintext = b_split_data[1]
        b_test_sha = to_bytes(sha256(b_plaintext).hexdigest())

        if b_this_sha != b_test_sha:
            raise AnsibleError("Decryption failed")

        return b_plaintext