29 lines
768 B
Python
29 lines
768 B
Python
from Crypto.Cipher import AES
|
|
from Crypto.Random import get_random_bytes
|
|
from Crypto.Hash import SHA256
|
|
|
|
class Encryptor:
|
|
|
|
def __init__(self,key):
|
|
self.key = key
|
|
|
|
@staticmethod
|
|
def derive_key(password):
|
|
return SHA256(password).digest()
|
|
|
|
def encrypt(self,data):
|
|
encryptor = AES.new(self.key, AES.MODE_GCM)
|
|
(ciphertext, tag) = encryptor.encrypt_and_digest(data)
|
|
nonce = encryptor.nonce
|
|
return (ciphertext,tag)
|
|
|
|
def decrypt(self,data):
|
|
encryptor = AES.new(self.key, AES.MODE_CBC)
|
|
return encryptor.decrypt(data)
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
enc = Encryptor(Encryptor.derive_key("abc123"))
|
|
ciphertext = enc.encrypt("Hello world")
|
|
print enc.decrypt(ciphertext) == "Hello world" |