hashUtil.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #encoding:utf8
  2. import base64
  3. from Crypto.Cipher import AES
  4. from Crypto import Random
  5. import pandas as pd
  6. class AESCipher:
  7. def __init__(self):
  8. '''
  9. CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)
  10. '''
  11. self.key = self.check_key(base64.b64decode('zDXjL5mx5HeUgmsg7HyKLg==') )
  12. # 数据块的大小 16位
  13. self.BS = 32
  14. # CBC模式 相对安全 因为有偏移向量 iv 也是16位字节的
  15. self.mode = AES.MODE_ECB
  16. # 填充函数 因为AES加密是一段一段加密的 每段都是BS位字节,不够的话是需要自己填充的
  17. self.pad = lambda s: s + (self.BS - len(s.encode()) % self.BS)*chr(self.BS - len(s.encode()) % self.BS)
  18. # 将填充的数据剔除
  19. self.unpad = lambda s: s[:-ord(s[len(s) - 1:])]
  20. def check_key(self, key):
  21. '''
  22. 检测key的长度是否为16,24或者32bytes的长度
  23. '''
  24. try:
  25. if isinstance(key, bytes):
  26. assert len(key) in [16, 24, 32]
  27. return key
  28. elif isinstance(key, str):
  29. assert len(key.encode()) in [16, 24, 32]
  30. return key.encode()
  31. else:
  32. raise Exception('密钥必须为str或bytes,不能为%s'%type(key))
  33. except AssertionError:
  34. print('输入的长度不正确')
  35. def check_data(self, data):
  36. '''
  37. 检测加密的数据类型
  38. '''
  39. if isinstance(data, int):
  40. data = str(data)
  41. elif isinstance(data, bytes):
  42. data = data.decode()
  43. elif isinstance(data, str):
  44. pass
  45. else:
  46. raise Exception('加密的数据必须为str或bytes,不能为%s'%type(data))
  47. return data
  48. def text2hex(self,_str):
  49. list_hex = []
  50. if isinstance(_str,str):
  51. _str1 = _str.encode()
  52. elif isinstance(_str,bytes):
  53. _str1 = _str
  54. for _hex in map(hex,_str1):
  55. _i = int(_hex[2:],16)
  56. while(True):
  57. a = _i&0xFF
  58. list_hex.append(hex(a)[2:].rjust(2,"0"))
  59. _i = _i >>8
  60. if _i==0:
  61. break
  62. return "".join(list_hex)
  63. def encrypt(self, raw):
  64. raw = self.check_data(raw)
  65. raw = self.pad(raw).encode()
  66. # 随机获取iv
  67. iv = Random.new().read(AES.block_size)
  68. # 定义初始化
  69. cipher = AES.new(self.key, self.mode)
  70. # 此处是将密文和iv一起 base64 解密的时候就可以根据这个iv来解密
  71. return self.text2hex(cipher.encrypt(raw))
  72. return base64.b64encode(cipher.encrypt(raw)).decode()
  73. def decrypt(self, enc):
  74. # 先将密文进行base64解码
  75. enc = base64.b64decode(enc)
  76. # 取出iv值
  77. iv = enc[:self.BS]
  78. # 初始化自定义
  79. cipher = AES.new(self.key, self.mode, iv)
  80. # 返回utf8格式的数据
  81. return self.unpad(cipher.decrypt(enc[self.BS:])).decode()
  82. aesCipher = AESCipher()