-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptic.py
44 lines (37 loc) · 1.62 KB
/
cryptic.py
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
# Copyright (c) 2020 Vishnu J. Seesahai
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
import base64
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
def encrypt_seed(password, seed, filename):
encrypted_data = encrypt(password, seed)
with open(filename, "w") as file:
file.write(encrypted_data)
def encrypt(key, source, encode=True):
key = SHA256.new(key).digest() # use SHA-256 over our key to get a proper-sized AES key
IV = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, IV)
padding = AES.block_size - len(source) % AES.block_size # calculate needed padding
source += bytes([padding]) * padding
data = IV + encryptor.encrypt(source)
return base64.b64encode(data).decode("latin-1") if encode else data
def decrypt_seed(password, filename):
# Decrypt
with open(filename, "r") as file:
# read the encrypted data
encrypted_data = file.read()
decrypted = decrypt(password, encrypted_data)
return decrypted
def decrypt(key, source, decode=True):
if decode:
source = base64.b64decode(source.encode("latin-1"))
key = SHA256.new(key).digest() # use SHA-256 over our key to get a proper-sized AES key
IV = source[:AES.block_size] # extract the IV from the beginning
decryptor = AES.new(key, AES.MODE_CBC, IV)
data = decryptor.decrypt(source[AES.block_size:])
padding = data[-1]
if data[-padding:] != bytes([padding]) * padding:
raise ValueError("Invalid padding...")
return data[:-padding] # remove the padding