Python AES 256 CBC加密-值错误:AES密钥长度不正确

Python AES 256 CBC加密-值错误:AES密钥长度不正确,python,encryption,aes,sha256,Python,Encryption,Aes,Sha256,我想在Python 3.8.5上使用AES 256为我的明文编写加密,但是当我执行它时,我收到了错误ValueError:error-error-AES key length(64字节)我的代码中有什么错误吗 plaintext = "ABC123" secret_key = "6789045129812345" secret_iv = "4567891122315731" key = hashlib.sha256(str(s

我想在Python 3.8.5上使用AES 256为我的明文编写加密,但是当我执行它时,我收到了错误ValueError:error-error-AES key length(64字节)我的代码中有什么错误吗

plaintext = "ABC123"
secret_key = "6789045129812345"
secret_iv = "4567891122315731"
    
key = hashlib.sha256(str(secret_key).encode('utf-8')).hexdigest()
iv = hashlib.sha256(str(secret_iv).encode('utf-8')).hexdigest()
substring_iv = iv[:16]
cipher_config = AES.new(key.encode("utf-8"), AES.MODE_CBC, substring_iv.encode("utf-8"))
results = base64.b64encode(cipher_config)

print("results : "+results)

以下代码是使用随机salt进行PBKDF2密钥派生的完整运行示例,后跟AES 256 CBC模式加密。代码在我的联机编译器上运行,使用Python 3.8.2,并使用crypto库pycryptodome3.9.9版执行加密任务()

加密输出是分开的(salt、iv和密文),每个输出都采用Base64编码,因为代码在我的跨平台项目中使用

这是输出:

SO AES CBC 256 encryption with PBKDF2 key derivation
plaintext: The quick brown fox jumps over the lazy dog

* * * Encryption * * *
ciphertext: 2BUSFaOSh+HsFI0tYbuZEJxvjRfYxJxwP+4h8haaTgU=:1Ke2VbQouUGh/ninKt1RiQ==:Wno0ARfn3dCCGm/IGpIpuN9guoBsRrktL1RaIaFflQIRl9uOettvsH9AexcH/bvq
output is (Base64) salt : (Base64) iv : (Base64) ciphertext

* * * Decryption * * *
ciphertext (Base64): 2BUSFaOSh+HsFI0tYbuZEJxvjRfYxJxwP+4h8haaTgU=:1Ke2VbQouUGh/ninKt1RiQ==:Wno0ARfn3dCCGm/IGpIpuN9guoBsRrktL1RaIaFflQIRl9uOettvsH9AexcH/bvq
input is (Base64) salt : (Base64) iv : (Base64) ciphertext
plaintext:  The quick brown fox jumps over the lazy dog
请注意,代码没有异常处理,没有运行身份验证检查,仅用于教育目的:

from Crypto.Protocol.KDF import PBKDF2
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Hash import SHA256
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import base64

# uses https://www.pycryptodome.org version 3.9.9

def base64Encoding(input):
  dataBase64 = base64.b64encode(input)
  dataBase64P = dataBase64.decode("UTF-8")
  return dataBase64P

def base64Decoding(input):
    return base64.decodebytes(input.encode("ascii"))

def generateSalt32Byte():
  return get_random_bytes(32)

def aesCbcPbkdf2EncryptToBase64(password, plaintext):
  passwordBytes = password.encode("ascii")
  salt = generateSalt32Byte()
  PBKDF2_ITERATIONS = 15000
  encryptionKey = PBKDF2(passwordBytes, salt, 32, count=PBKDF2_ITERATIONS, hmac_hash_module=SHA256)
  cipher = AES.new(encryptionKey, AES.MODE_CBC)
  ciphertext = cipher.encrypt(pad(plaintext.encode("ascii"), AES.block_size))
  ivBase64 = base64Encoding(cipher.iv)
  saltBase64 = base64Encoding(salt)
  ciphertextBase64 = base64Encoding(ciphertext)
  return saltBase64 + ":" + ivBase64 + ":" + ciphertextBase64

def aesCbcPbkdf2DecryptFromBase64(password, ciphertextBase64): 
  passwordBytes = password.encode("ascii")
  data = ciphertextDecryptionBase64.split(":")
  salt = base64Decoding(data[0])
  iv = base64Decoding(data[1])
  ciphertext = base64Decoding(data[2])
  PBKDF2_ITERATIONS = 15000
  decryptionKey = PBKDF2(passwordBytes, salt, 32, count=PBKDF2_ITERATIONS, hmac_hash_module=SHA256)
  cipher = AES.new(decryptionKey, AES.MODE_CBC, iv)
  decryptedtext = unpad(cipher.decrypt(ciphertext), AES.block_size)
  decryptedtextP = decryptedtext.decode("UTF-8")
  return decryptedtextP

print("SO AES CBC 256 encryption with PBKDF2 key derivation")

plaintext = "The quick brown fox jumps over the lazy dog"
print("plaintext: " + plaintext)
password = "6789045129812345"

print("\n* * * Encryption * * *") 
ciphertextBase64 = aesCbcPbkdf2EncryptToBase64(password, plaintext)
print("ciphertext: " + ciphertextBase64)
print("output is (Base64) salt : (Base64) iv : (Base64) ciphertext")

print("\n* * * Decryption * * *") 
ciphertextDecryptionBase64 = ciphertextBase64

print("ciphertext (Base64): " + ciphertextDecryptionBase64)
print("input is (Base64) salt : (Base64) iv : (Base64) ciphertext")
decryptedtext = aesCbcPbkdf2DecryptFromBase64(password, ciphertextBase64)
print("plaintext:  " + decryptedtext)

十六进制摘要的长度是摘要的两倍。使用静态密钥和iv的安全警告是不安全的,您应该使用像PBKDF2这样的密码派生函数,并结合随机生成的Salt来获得可接受的安全级别,谢谢。@MichaelFehr好的,这只是一个简单的加密示例,在我的问题解决后,我将更改为随机生成的salt。但我仍然有这个错误。你知道吗?如果你用一个为派生密钥而创建的函数来派生密钥,你将得到一个正确长度的密钥,从而解决你的问题。现在,您试图使用sha256派生一个密钥,但得到的“密钥”大小不正确。代码中最引人注目的一点可能是,您没有在任何地方使用或加密明文,即encrypt()调用丢失。此外,缺少明文的填充。最后,键的长度不正确,请参见其他注释。PyCryptodome文档包含AES和大多数模式的易于理解的示例,例如。