PyCryptoDome为AES加密生成OpenSSL PBKDF2密钥

2024-06-08 21:53:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用PyCryptoDome AES-256-ECB模式加密文件,将密钥和密码写入文件,然后使用OpenSSL解密 Python密码和密钥加密如下所示:

import random
import string
from pathlib import Path
import sys
from Crypto.Cipher import AES

from Crypto.Protocol.KDF import PBKDF2
from Crypto.Util.Padding import pad


secret = "123"
random_aes_key_length = 32
aes_key_file_path = "key.key"
encrypted_message_file_path = "message.out"
dir_path = Path(__file__).resolve().parent
random_aes_password = "".join(
        random.SystemRandom().choice(string.hexdigits) for _ in range(random_aes_key_length))
aes_key = PBKDF2(random_aes_password, b'', dkLen=32)
aes_obj = AES.new(aes_key, AES.MODE_ECB)
encrypted_message = aes_obj.encrypt(pad(secret.encode(), AES.block_size))

with open(dir_path / aes_key_file_path, 'w', encoding="utf-8") as aes_key_file:
    aes_key_file.write(random_aes_password)

with open(dir_path / encrypted_message_file_path, 'wb') as encrypted_message_file:
    encrypted_message_file.write(encrypted_message)

然后我想用OpenSSL解码encrypted_message_file

{cd2}

但我不知道我的秘密,只是一些随机数据: {���"R,�b�<�-�

  1. 在给定随机生成的加密密码的情况下,如何使用python以兼容的方式加密OpenSSL来解密数据字符串?在
  2. 特别是我在python中生成PBKDF2键的方法 与OpenSSL方法相同/兼容?在

Tags: pathkeyfromimport密码messagedirrandom