【发布时间】:2017-11-03 19:51:47
【问题描述】:
我正在使用 RSA 加密图像并使用 Pillow 逐字节读取它。我正在加密每个 128 字节。但是当我尝试将其解密时,生成的图像与原始图像不同。 这是我的代码:
from Crypto.PublicKey import RSA
from PIL import Image
def genearteRSAKeys(keyLength):
private = RSA.generate(keyLength)
public = private.publickey()
privateKey = private.exportKey()
publicKey = public.exportKey()
return privateKey, publicKey
def rsaEncrypt(pubKey, data):
publicKey = RSA.importKey(pubKey)
encryptData = publicKey.encrypt(data, "")
return encryptData
def rsaDecrypt(pivKey, data):
privateKey = RSA.importKey(pivKey)
decryptData = privateKey.decrypt(data)
return decryptData
im = Image.open("photo.jpg")
w, h = im.size
data = im.tobytes()
privateKey, publicKey = genearteRSAKeys(1024)
step = 128
block_cipher = []
for i in range(0, len(data), step):
encrypted = rsaEncrypt(publicKey, data[i:i+step])
block_cipher.append(''.join(encrypted))
data_cipher = ''.join(block_cipher)
img = Image.frombytes("RGB", (w, h), data_cipher)
img.save("photo2.jpg")
image = Image.open("photo2.jpg")
data_encrypt = image.tobytes()
block_plant =[]
for j in range(0, len(data_encrypt), step):
decrypted = rsaDecrypt(privateKey, data_encrypt[j:j+step])
block_plant.append(''.join(decrypted))
data_plant = ''.join(block_plant)
image2 = Image.frombytes("RGB", (w,h), data_plant)
image2.show()
为什么这段代码不起作用?
【问题讨论】:
-
谁能解释一下为什么这个问题被否决了这么多?没看懂
-
@BPL 因为你没有对预期的行为给出很多解释,看起来你只是希望我们更正你的代码,而不是试图自己做。请注意,我说的是“它看起来像”。
-
你能把图片链接(加密/解密之前,之后)吗?
-
RSA 不支持批量加密,因此库不支持加密大于密钥长度允许的消息。使用为批量加密设计的对称算法,如 AES。如果您确实需要来自 RSA 的两个密钥,您可以使用 Hybrid Encryption 获取
标签: python image encryption rsa pillow