1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import json from base64 import b64encode, b64decode from Crypto.Cipher import AES from Crypto.Random import get_random_bytes
class AesOcb: def __init__(self, key): self.bs = AES.block_size self.key = key self.mode = AES.MODE_OCB self.json_k = ['nonce', 'header', 'ciphertext', 'tag']
def encrypt(self, header, data): header = header cipher = AES.new(self.key, self.mode) cipher.update(header) ciphertext, tag = cipher.encrypt_and_digest(data) json_v = [b64encode(x).decode('utf-8') for x in [cipher.nonce, header, ciphertext, tag]] return json.dumps(dict(zip(self.json_k, json_v)))
def decrypt(self, json_input): try: b64 = json.loads(json_input) jv = {k: b64decode(b64[k]) for k in self.json_k} cipher = AES.new(self.key, self.mode, nonce=jv['nonce']) cipher.update(jv['header']) plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) return plaintext.decode('utf-8') except (ValueError, KeyError) as err: print(err) return None
if __name__ == "__main__": data = "需要加密的数据".encode('utf-8') key = get_random_bytes(16) header = b'header'
aes_cipher = AesOcb(key)
encrypt_reuslt = aes_cipher.encrypt(header, data) print("密文: ", encrypt_reuslt)
plaintext = aes_cipher.decrypt(encrypt_reuslt) print("原文: ", plaintext)
|