微智科技网
您的当前位置:首页Cipher:字符串加解密

Cipher:字符串加解密

来源:微智科技网
Cipher:字符串加解密

1 from Crypto.Cipher import AES

2 from binascii import b2a_hex, a2b_hex 3 4 \"\"\"

5 pip install pycryptodome 6 \"\"\" 7 8

9 class Cipher(object):

10 MODE = AES.MODE_CBC

11 DEFAULT_KEY = b\"024ea5b1f070da\"12

13 def __init__(self, key: bytes = b\"024ea5b1f070da\"):14 \"\"\"key: 16位, 24位, 32位\"\"\"15 self.DEFAULT_KEY = key16

17 @classmethod

18 def encrypt(cls, text: str):

19 \"\"\"这⾥密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.⽬前AES-128⾜够⽤\"\"\"20 cipher = AES.new(cls.DEFAULT_KEY, cls.MODE, cls.DEFAULT_KEY)21 length = 16

22 count = len(text)

23 add = length - (count % length)24 text += '\\0' * add

25 return b2a_hex(cipher.encrypt(text.encode())).decode()26

27 @classmethod

28 def decrypt(cls, text: str):

29 cipher = AES.new(cls.DEFAULT_KEY, cls.MODE, cls.DEFAULT_KEY)30 plain_text = cipher.decrypt(a2b_hex(text))31 return plain_text.rstrip(b'\\0').decode()32 33

34 if __name__ == '__main__':35 cipher = Cipher()

36 text = cipher.encrypt('hello')37 print(text)

38 print(cipher.decrypt('f9cca2bb60e577874271c538c6c06161'))

因篇幅问题不能全部显示,请点此查看更多更全内容