|
| 1 | +import base64 |
| 2 | +from Crypto.Cipher import AES |
| 3 | +from Crypto import Random |
| 4 | +from Crypto.Protocol.KDF import PBKDF2 |
| 5 | + |
| 6 | +BLOCK_SIZE = 16 |
| 7 | + |
| 8 | + |
| 9 | +def pad(s): |
| 10 | + return s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr( |
| 11 | + BLOCK_SIZE - len(s) % BLOCK_SIZE |
| 12 | + ) |
| 13 | + |
| 14 | + |
| 15 | +def unpad(s): |
| 16 | + return s[: -ord(s[len(s) - 1:])] |
| 17 | + |
| 18 | + |
| 19 | +def get_private_key(password): |
| 20 | + salt = b"this is a salt" |
| 21 | + kdf = PBKDF2(password, salt, 64, 1000) |
| 22 | + key = kdf[:32] |
| 23 | + return key |
| 24 | + |
| 25 | + |
| 26 | +def encrypt(raw, password): |
| 27 | + private_key = get_private_key(password) |
| 28 | + raw = pad(raw) |
| 29 | + iv = Random.new().read(AES.block_size) |
| 30 | + cipher = AES.new(private_key, AES.MODE_CBC, iv) |
| 31 | + cipher = iv + cipher.encrypt(raw.encode("utf-8")) |
| 32 | + return base64.b64encode(cipher) |
| 33 | + |
| 34 | + |
| 35 | +def decrypt(enc, password): |
| 36 | + private_key = get_private_key(password) |
| 37 | + enc = base64.b64decode(enc) |
| 38 | + iv = enc[:16] |
| 39 | + cipher = AES.new(private_key, AES.MODE_CBC, iv) |
| 40 | + return unpad(cipher.decrypt(enc[16:])) |
| 41 | + |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + password = input("Enter encryption password: ") |
| 45 | + # First let us encrypt secret message |
| 46 | + encrypted = encrypt("This is a secret message", password) |
| 47 | + print(encrypted) |
| 48 | + |
| 49 | + # Let us decrypt using our original password |
| 50 | + decrypted = decrypt(encrypted, password) |
| 51 | + print(bytes.decode(decrypted)) |
0 commit comments