-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptlib.py
More file actions
71 lines (53 loc) · 1.75 KB
/
cryptlib.py
File metadata and controls
71 lines (53 loc) · 1.75 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Project: device_GUI
File: cryptlib.py
Date: 3/29/2019
https://stackoverflow.com/questions/2490334/simple-way-to-encode-a-string-according-to-a-password
http://www.pycrypto.org/ aka https://www.dlitz.net/software/pycrypto/
https://pypi.org/project/pycrypto/
https://paste.ubuntu.com/11024555/
PyCrypto is public domain
"""
# TODO unit tests
import struct
from typing import Union
from base64 import urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
def pad16(s: Union[str, bytes]) -> bytes:
if isinstance(s, str):
s = s.encode()
r: bytes = struct.pack('>I', len(s)) # save the length
r = r + s # append it
pad: str = '\x00' * ((16 - len(r) % 16) % 16) # pad with zeros
r = r + pad.encode()
return r # and r is now a multiple of 16 chars long
def unpad16(s: bytes) -> bytes:
n = struct.unpack('>I', s[:4])[0]
r: bytes = s[4:n + 4]
return r
class Crypt(object):
def __init__(self, password: str):
self.cipher = AES.new(pad16(password), AES.MODE_ECB)
def encrypt(self, s: str) -> bytes:
b: bytes = pad16(s)
return self.cipher.encrypt(b)
def decrypt(self, s) -> bytes:
t: bytes = self.cipher.decrypt(s)
r: bytes = unpad16(t)
return r
def encrypt(s: str, p: str) -> str:
c = Crypt(p)
b: bytes = c.encrypt(s)
r: str = urlsafe_b64encode(b).decode()
return r
def decrypt(s: str, p: str) -> str:
c = Crypt(p)
s2: bytes = urlsafe_b64decode(s)
r: str = c.decrypt(s2).decode()
return r
if __name__ == '__main__':
p: str = 'password'
t: str = 'my message'
x: str = encrypt(t, p)
y: str = decrypt(x, p)
print([x, y])