无法从加密图像中检索原始图像在Python中使用PIL

问题描述 投票:0回答:1

我正在编写一个可以使用RSA算法加密和解密图像的脚本。我的公钥是(7,187),私钥是(23,187),现在加密的计算是正确的,就像图像矩阵中的条目一样,41加密值是46.但是当解密发生时没有给出适当的结果,例如它给出了136,而对于加密矩阵中46的每个条目,我得到的结果是解密矩阵中的136。我不知道为什么会这样。当我在python提示符(或shell)中进行相同的计算时,它给出了正确的答案。

在脚本中,我首先将RGB图像转换为灰度,然后将其转换为2d numpy数组,然后对于每个元素,我应用RSA算法(键)然后将其保存为图像。然后我在加密矩阵中应用解密密钥,然后问题正在发生。下面是代码:

from PIL import Image
import numpy as np
from pylab import * 
#encryption

img1 = (Image.open('image.jpeg').convert('L')) 
img1.show()

img = array((Image.open('image.jpeg').convert('L')))
a,b = img.shape #saving the no of rows and col in a tuple
print('\n\nOriginal image: ')
print(img)
print((a,b))
tup = a,b

for i in range (0, tup[0]):
    for j in range (0, tup[1]):
        img[i][j]= (pow(img[i][j],7)%187)


print('\n\nEncrypted image: ')
print(img)
imgOut = Image.fromarray(img)
imgOut.show()
imgOut.save('img.bmp')

#decryption

img2 = (Image.open('img.bmp'))
img2.show()
img3 = array(Image.open('img.bmp'))
print('\n\nEncrypted image: ')
print(img3)
a1,b1 = img3.shape
print((a1,b1))
tup1 = a1,b1

for i1 in range (0, tup1[0]):
    for j1 in range (0, tup1[1]):
        img3[i1][j1]= ((pow(img3[i1][j1], 23))%187) 
print('\n\nDecrypted image: ')
print(img3)
imgOut1 = Image.fromarray(img3)
imgOut1.show()
print(type(img))  

矩阵的值:

原始图片:

[[41 42 45 ... 47 41 33]

[41 43 45 ... 44 38 30]

[41 42 46 ... 41 36 30] ...

[43 43 44 ... 56 56 55]

[45 44 45 ... 55 55 54]

[46 46 46 ... 53 54 54]]

加密图片:

[[ 46 15 122 ... 174 46 33]

[ 46 87 122 ... 22 47 123]

[ 46 15 7 ... 46 9 123] ...

[ 87 87 22 ... 78 78 132]

[122 22 122 ... 132 132 164]

[ 7 7 7 ... 26 164 164]]

解密图片:

[[136 70 24 ... 178 136 164]

[136 111 24 ... 146 141 88]

[136 70 96 ... 136 100 88] ...

[111 111 146 ... 140 140 1]

[ 24 146 24 ... 1 1 81]

[ 96 96 96 ... 52 81 81]]

任何帮助将不胜感激。谢谢。

python image encryption python-imaging-library mod
1个回答
0
投票

我认为你会更好地使用pow()函数的第3个参数,它可以在内部为你做模数。

这是一个没有加载图像复杂性的小例子 - 想象它是从黑到白的灰度渐变。

# Make single row greyscale gradient from 0..255
img = [ x for x in range(256) ]

# Create encrypted version
enc = [ pow(x,7,187) for x in img ]

# Decrypt back to plaintext
dec = [ pow(x,23,187) for x in enc ]

它似乎从0..187解密回原始值,它出错了 - 可能是因为溢出?也许比我更聪明的人能够解释一下 - 如果你知道的话请为我添加评论!

© www.soinside.com 2019 - 2024. All rights reserved.