我正在编写一个脚本,可以使用RSA算法对图像进行加密和解密。我的公钥是(7187),私钥是(23187),现在加密的计算是正确的,就像图像矩阵中的一个条目,41加密值是46。但是当解密发生时,它并没有给出适当的结果,就像对于46,它给出了136,对于加密矩阵中的每个条目,我得到的结果是解密矩阵中的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 43 44。。。56 56 55]
[45 44 45。。。55 55 54]
[46 46 46。。。54]]
加密图像:
[[46 15 122。。。174 46 33]
[46 87 122。。。22 47 123]
[46 15 7。。。46 9 123] ... 在
[87 87 87 22。。。78 78 132]
[122 22 122。。。132 132 164]
[7 7 7。。。26 164 164 164]]
解密图像:
[[136 70 24。。。178 136 164]
[136 111 24。。。146 141 88]
[136 70 96。。。136 100 88] ... 在
[111 111 111 146。。。140 140 1]
[24 146 24。。。1811年]
[96 96 96。。。52 81 81]]
如有任何帮助,将不胜感激。谢谢您。在
我认为您可以更好地使用
pow()
函数的第三个参数,该函数在内部为您计算模数。在这里有一个小例子,没有加载图像的复杂性-想象一下它是从黑色到白色的灰度渐变。在
它似乎从0..187解密回原始值,在那里出错-可能是因为溢出?也许比我聪明的人可以解释这一点-请为我添加评论,如果你知道!在
相关问题 更多 >
编程相关推荐