RSA加密SHA256校验和后解密报错:密文长度不正确
问题:RSA加密SHA256校验和解密时出现长度错误
错误信息
File "C:\Users\code\Encrypt.py", line 29, in decrypt_data return decipher.decrypt(data, None).decode() File "C:\Users\code\lib\site-packages\Crypto\Cipher\PKCS1_v1_5.py", line 174, in decrypt raise ValueError("Ciphertext with incorrect length (not %d bytes)" % k) ValueError: Ciphertext with incorrect length (not 384 bytes)
问题代码
import hashlib import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5 def compute_sha256(file_name): hash_sha256 = hashlib.sha256() with open(file_name, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest() def encrypt_data(data): with open("C:\\Users\\code\\key.pub", "rb") as k: key = RSA.importKey(k.read()) cipher = Cipher_PKCS1_v1_5.new(key) return cipher.encrypt(data.encode()) def decrypt_data(data): with open("C:\\Users\\code\\id_rsa", "rb") as k: key = RSA.importKey(k.read()) decipher = Cipher_PKCS1_v1_5.new(key) return decipher.decrypt(data, None).decode() message = compute_sha256("C:\\Users\\code\\test.rpm") encrypted = encrypt_data(message) decrypted = decrypt_data(message)
问题分析
- 核心错误:解密参数传错
调用decrypt_data时传入的是原始的message(SHA256十六进制字符串),而非加密后生成的encrypted二进制数据。你的RSA密钥是3072位(对应384字节),RSA解密要求输入必须是对应密钥长度的加密二进制数据,原始字符串长度远小于该值,因此触发长度错误。 - 额外问题:二进制数据处理
RSA加密返回的二进制字节流直接存储或打印易出现乱码、数据损坏,建议用Base64编码转为可打印字符串,解密时再解码回二进制。
修正后的代码
import hashlib import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5 def compute_sha256(file_name): hash_sha256 = hashlib.sha256() with open(file_name, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest() def encrypt_data(data): with open("C:\\Users\\code\\key.pub", "rb") as k: key = RSA.importKey(k.read()) cipher = Cipher_PKCS1_v1_5.new(key) # 加密后用Base64编码,避免二进制数据损坏 encrypted_bytes = cipher.encrypt(data.encode()) return base64.b64encode(encrypted_bytes).decode() def decrypt_data(data): with open("C:\\Users\\code\\id_rsa", "rb") as k: key = RSA.importKey(k.read()) decipher = Cipher_PKCS1_v1_5.new(key) # 先Base64解码回二进制 encrypted_bytes = base64.b64decode(data) return decipher.decrypt(encrypted_bytes, None).decode() message = compute_sha256("C:\\Users\\code\\test.rpm") encrypted = encrypt_data(message) decrypted = decrypt_data(encrypted) # 传入加密后的数据 print(f"原始SHA256: {message}") print(f"解密后SHA256: {decrypted}")
说明
- 修正了解密参数,传入加密后的
encrypted数据而非原始字符串; - 增加Base64编解码处理,确保加密数据可安全传输、存储;
- 运行后会输出原始与解密后的SHA256校验和,验证一致性。
内容的提问来源于stack exchange,提问作者Rafa S
相关产品推荐
相关产品推荐

