当前位置:   article > 正文

python使用Crypto库实现加密解密_python crypto

python crypto

一:crypto库安装

pycrypto,pycryptodome是crypto第三方库,pycrypto已经停止更新三年了,所以不建议安装这个库;pycryptodome是pycrypto的延伸版本,用法和pycrypto 是一模一样的;所以只需要安装pycryptodome就可以了

pip install pycryptodome

二:python使用crypto

1:crypto的加密解密组件des.py

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from Crypto.Cipher import DES
  4. from binascii import b2a_hex, a2b_hex
  5. class MyDESCrypt: #自己实现的DES加密类
  6. def __init__(self, key = ''):
  7. #密钥长度必须为64位,也就是8个字节
  8. if key is not '':
  9. self.key = key.encode('utf-8')
  10. else:
  11. self.key = '12345678'.encode('utf-8')
  12. self.mode = DES.MODE_CBC
  13. # 加密函数,如果text不足16位就用空格补足为16位,
  14. # 如果大于16当时不是16的倍数,那就补足为16的倍数。
  15. def encrypt(self,text):
  16. try:
  17. text = text.encode('utf-8')
  18. cryptor = DES.new(self.key, self.mode, self.key)
  19. # 这里密钥key 长度必须为16(DES-128),
  20. # 24(DES-192),或者32 (DES-256)Bytes 长度
  21. # 目前DES-128 足够目前使用
  22. length = 16 #lenth可以设置为8的倍数
  23. count = len(text)
  24. if count < length:
  25. add = (length - count)
  26. # \0 backspace
  27. # text = text + ('\0' * add)
  28. text = text + ('\0' * add).encode('utf-8')
  29. elif count > length:
  30. add = (length - (count % length))
  31. # text = text + ('\0' * add)
  32. text = text + ('\0' * add).encode('utf-8')
  33. self.ciphertext = cryptor.encrypt(text)
  34. # 因为DES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
  35. # 所以这里统一把加密后的字符串转化为16进制字符串
  36. return b2a_hex(self.ciphertext)
  37. except:
  38. return ""
  39. # 解密后,去掉补足的空格用strip() 去掉
  40. def decrypt(self, text):
  41. try:
  42. cryptor = DES.new(self.key, self.mode, self.key)
  43. plain_text = cryptor.decrypt(a2b_hex(text))
  44. # return plain_text.rstrip('\0')
  45. return bytes.decode(plain_text).rstrip('\0')
  46. except:
  47. return ""

2:crypto组件使用

  1. from . import des
  2. msg = "password is 961223"
  3. key = "12345678" #key值可传可不传
  4. des1 = des.MyDESCrypt()
  5. #加密
  6. cipherTxt = des1.encrypt(msg) #返回值为bytes型
  7. print(cipherTxt)
  8. #解密
  9. decTxt = des1.decrypt(cipherTxt); #返回值为str型
  10. print(decTxt)

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/835039
推荐阅读
相关标签
  

闽ICP备14008679号