print('安裝密碼學套件pycryptodome,使用AES256加密圖檔opencv處理')
!pip install pycryptodome
from Crypto.Cipher import AES
import cv2
import numpy as np
from google.colab import files
from google.colab.patches import cv2_imshow
x=files.upload()
for f in x.keys():
s=f
print(s)
"""因AES的block_size=128/8=16(bytes),圖檔也要根據(w,h)
pad使得修改後的w, h為4的倍數
"""
def pad(im):
global h,w
h2=(h+3)//4*4
w2=(w+3)//4*4
print('改圖使其(w,h)為4的倍數',(w2,h2))
im2 = np.zeros((h2, w2, 3), dtype=np.uint8)
im2[0:h, 0:w, 0:3]=im
h,w=(h2, w2)
im=im2
return im
"""不是整個圖檔加密,而是針對圖檔內容每個pixel加密,如果h, w非4倍數,就要pad
"""
im=cv2.imread(s)
sz=im.shape
print(sz)
h, w, _=sz
if h%4!=0 or w%4!=0:
im=pad(im)
cv2_imshow(im)
"""把圖檔內容轉成1D array"""
ss=h*w*3
data=im.reshape(ss, order='C')
data
"""轉成bytes"""
m=data.tobytes('C')
m
"""輸入passphrase透過hash產生密鑰secret key與iv"""
import getpass
p = getpass.getpass('輸入passphrase:')
import hashlib
x=hashlib.sha256()
x.update(p.encode())
key=x.digest()
print("sha256長度256 bits產生key:\n",key.hex())
x=hashlib.md5()
x.update(p.encode())
iv=x.digest()
print("md5長度128 bits產生iv:\n",iv.hex())
"""ECB或是CBC
"""
aes = AES.new(key, AES.MODE_CBC, iv)
#aes =AES.new(key, AES.MODE_ECB)
"""加密"""
cc=aes.encrypt(m)
"""將bytes資料秀圖並存成'cipher.png'"""
def bytes_image(b):
im0=np.frombuffer(b, dtype=np.uint8)
im=im0.reshape(h, w, 3)
cv2_imshow(im)
cv2.imwrite('cipher.png', im)
bytes_image(cc)
files.download('cipher.png')
沒有留言:
張貼留言