Python AES 256 CBC 加密 - ValueError : Incorrect AES key length

标签 python encryption aes sha256

我想在 Python 3.8.5 上使用 AES 256 为我的明文编写加密,但是当我执行它时,我收到错误ValueError:不正确的 AES key 长度(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)

最佳答案

以下代码是使用随机盐派生 PBKDF2 key 的完整运行示例,后跟 AES 256 CBC 模式加密。该代码在我的 Python 3.8.2 在线编译器上运行,并使用加密库 pycryptodome 版本 3.9.9 来执行加密任务 ( https://www.pycryptodome.org )。

加密输出是分开的(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 = ciphertextBase64.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)

关于Python AES 256 CBC 加密 - ValueError : Incorrect AES key length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66097967/

相关文章:

c# - AesManaged.KeySize 属性的默认值是多少?

javascript - 使用 PHP mcrypt 加密后使用 Javascript CryptoJS 解密 AES

python - 验证字符串是否仅包含一系列数字 Python 2.7

iOS 和 RESTful 网络服务加密

java - CipherOutputStream 与 rsa 一起使用

mysql - 如何通过网络对密码进行哈希和加密?

python - 如何在 Pandas 数据框中删除唯一行?

python - 使用列表理解交换行和列

python - 有没有办法计算每个月列值从 A 到 B 所花费的天数?

java - 如何在 Java 中生成一次 key 并在 2 个不同的程序中使用该 key