[英]Cannot retrieve Original image from Encrypted image In Python using PIL
我正在編寫一個可以使用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]]
任何幫助將不勝感激。 謝謝。
我認為你會更好地使用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解密回原始值,它出錯了 - 可能是因為溢出? 也許比我更聰明的人能夠解釋一下 - 如果你知道的話請為我添加評論!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.