aes-cbc-ebc的加密解密
from Cryptodome.Cipher import AES from binascii import a2b_base64, b2a_base64 import base64 ''' ECB没有偏移量 ''' KEY = '9' * 16 def pad(text): '''给text补\0''' mod = len(text.encode('utf8')) % 16 if mod: add = 16 - mod else: add = 0 text = text + '\0' * add return text.encode('utf8') def unpad(plain_text): return plain_text.decode('utf8').rstrip('\0') def encrypt(text): text = pad(text) # 补齐 mode = AES.MODE_ECB aes = AES.new(key=bytes(KEY, 'utf8'), mode=mode) cipher_text = aes.encrypt(text) return b2a_base64(cipher_text, newline=False) def decrypt(text): mode = AES.MODE_ECB aes = AES.new(key=KEY.encode('utf8'), mode=mode) plain_text = aes.decrypt(a2b_base64(text)) return unpad(plain_text) if __name__ == '__main__': e = encrypt('1' * 17) print(e) d = decrypt(e) print(d)
from Cryptodome.Cipher import AES from binascii import b2a_base64, a2b_base64 from hashlib import md5 from Cryptodome import Random import base64 ''' CBC ''' KEY = ('9' * 16).encode('utf8') IV = ('1' * 8).encode('utf8') MODE = AES.MODE_CBC def pad(text): '''给text补\0''' mod = len(text.encode('utf8')) % 16 if mod: add = 16 - mod else: add = 0 text = text + '\0' * add return text.encode('utf8') def pad1(bt): mod = len(bt) % 16 if mod: add = 16 - mod else: add = 0 text = bt + b'\0' * add return text def unpad(plain_text): return plain_text.decode('utf8').rstrip('\0') def bytes_to_key(data, salt, output=48): # extended from https://gist.github.com/gsakkis/4546068 assert len(salt) == 8, len(salt) data += salt key = md5(data).digest() final_key = key while len(final_key) < output: key = md5(key + data).digest() final_key += key return final_key[:output] def simple_encrype(text): aes = AES.new(key=KEY, mode=MODE, iv=IV) return b2a_base64(aes.encrypt(pad(text)), newline=False) def simple_decrypt(encrypted): aes = AES.new(key=KEY, mode=MODE, iv=IV) return unpad(aes.decrypt(a2b_base64(encrypted))) def encrype(text): salt = Random.new().read(8) # 随机生成8字节的盐 key_iv = bytes_to_key(KEY, salt, 32 + 16) key = key_iv[:32] iv = key_iv[32:] aes = AES.new(key=key, mode=MODE, iv=iv) return base64.b64encode(salt + aes.encrypt(pad(text))) # 注意前8位 def decrypt(encrypted): encrypted_data = base64.b64decode(encrypted) salt = encrypted_data[:8] key_iv = bytes_to_key(KEY, salt, 32 + 16) key = key_iv[:32] iv = key_iv[32:] aes = AES.new(key, MODE, iv) return unpad(aes.decrypt(encrypted_data[8:])) # 前8位是salt if __name__ == '__main__': e = encrype('Hello World') print(e) d = decrypt(e) print(d) # # bytes_to_key实例 # salt = Random.new().read(8) # # key_iv = bytes_to_key(KEY, salt) # key = key_iv[:32] # iv = key_iv[32:] # print(key_iv) # print(key) # print(iv)