herrDeng網內搜尋

自訂搜尋

Ads

2022年5月27日 星期五

AES python實作圖檔加密


  1. print('安裝密碼學套件pycryptodome,使用AES256加密圖檔opencv處理')
  2. !pip install pycryptodome
  3. from Crypto.Cipher import AES
  4.  
  1. import cv2
  2. import numpy as np
  3. from google.colab import files
  4. from google.colab.patches import cv2_imshow
  5. x=files.upload()
  6. for f in x.keys():
  7. s=f
  8. print(s)
  9. """因AES的block_size=128/8=16(bytes),圖檔也要根據(w,h)
  10. pad使得修改後的w, h為4的倍數
  11. """
  12. def pad(im):
  13. global h,w
  14. h2=(h+3)//4*4
  15. w2=(w+3)//4*4
  16. print('改圖使其(w,h)為4的倍數',(w2,h2))
  17. im2 = np.zeros((h2, w2, 3), dtype=np.uint8)
  18. im2[0:h, 0:w, 0:3]=im
  19. h,w=(h2, w2)
  20. im=im2
  21. return im
  22. """不是整個圖檔加密,而是針對圖檔內容每個pixel加密,如果h, w非4倍數,就要pad
  23. """
  24. im=cv2.imread(s)
  25. sz=im.shape
  26. print(sz)
  27. h, w, _=sz
  28. if h%4!=0 or w%4!=0:
  29. im=pad(im)
  30. cv2_imshow(im)
  31. """把圖檔內容轉成1D array"""
  32. ss=h*w*3
  33. data=im.reshape(ss, order='C')
  34. data
  35. """轉成bytes"""
  36. m=data.tobytes('C')
  37. m
  38. """輸入passphrase透過hash產生密鑰secret key與iv"""
  39. import getpass
  40. p = getpass.getpass('輸入passphrase:')
  41. import hashlib
  42. x=hashlib.sha256()
  43. x.update(p.encode())
  44. key=x.digest()
  45. print("sha256長度256 bits產生key:\n",key.hex())
  46. x=hashlib.md5()
  47. x.update(p.encode())
  48. iv=x.digest()
  49. print("md5長度128 bits產生iv:\n",iv.hex())
  50. """ECB或是CBC
  51. """
  52. aes = AES.new(key, AES.MODE_CBC, iv)
  53. #aes =AES.new(key, AES.MODE_ECB)
  54. """加密"""
  55. cc=aes.encrypt(m)
  56. """將bytes資料秀圖並存成'cipher.png'"""
  57. def bytes_image(b):
  58. im0=np.frombuffer(b, dtype=np.uint8)
  59. im=im0.reshape(h, w, 3)
  60. cv2_imshow(im)
  61. cv2.imwrite('cipher.png', im)
  62. bytes_image(cc)
  63. files.download('cipher.png')

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章