Python3 AES密钥长度不正确(256字节)
我想编写一个脚本,对文本文件(key.k3y)的内容进行加密。当我执行它时,我得到一个错误:AES密钥长度不正确(256字节)。显然,这不应该对AES无效。这是我的密码:Python3 AES密钥长度不正确(256字节),python,encryption,aes,pycryptodome,Python,Encryption,Aes,Pycryptodome,我想编写一个脚本,对文本文件(key.k3y)的内容进行加密。当我执行它时,我得到一个错误:AES密钥长度不正确(256字节)。显然,这不应该对AES无效。这是我的密码: import base64 import pycryptodome from Crypto.Cipher import AES from Crypto.Util.Padding import pad from cryptography.fernet import Fernet from cryptography.hazmat.
import base64
import pycryptodome
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# Set a password and encode it (to Byte type)
password_provided = "NHW!He2-vxxYWF7va23LzjnqFTyvP#dAPGHChXmmSY4YYzJ*HDX_HzRZ-7M8c*2t" #64chars
password = password_provided.encode()
print(len(password))
# Set the hashing parameters for the pw hashing
salt = b'\x08\xfc\xe4e\x89\xc2\xa8\xfe\xe2UsS\xbb#\xbe\x8d\xec\x9b\xb1\xf9\x9d]\xa6D?\xc7\x89\x1b\xdf\xb7\xa3\x19m\x13\xca"i\xbbd\x07b\x8al\x80@xm>Coa\xcc\x88X\xc7@\x99\xd5\xf8\xcf\x86\x04\xbf9'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA512(),
length=192,
salt=salt,
iterations=100000,
backend=default_backend()
)
# Hash and encode the key with SHA512 and base64
key = base64.urlsafe_b64encode(kdf.derive(password))
print("The key (hashed pw) is: ")
print(len(key))
# Get the message or, as in this case, the content of the file key.k3y
messagefile = open('key.k3y', 'rb')
data = messagefile.read()
messagefile.close()
# Encrypting the message with AES, mode CBC
cipher = AES.new(key, AES.MODE_CBC)
encdata = cipher.encrypt(pad(data, AES.block_size))
print(encdata)
key=base64.urlsafe_b64encode(kdf.derivate(password))
应该是key=kdf.derivate(password)
。如果要通过文本媒体传输密钥或仅打印密钥,则应对其进行编码。另外,length=192,
应该是length=32,
如果需要256位密钥,AES密钥可以是128、192或256位。长度为256字节的密钥确实无效