· 7 years ago · May 25, 2018, 03:04 AM
1"""
2python3 encoding notes
3"""
4
5################################################################################
6
7# python 2
8
9>>> import md5
10>>> secret_key = md5.new("rppowellemail@gmail.com").hexdigest()
11
12# python 3
13
14>>> import hashlib
15>>> secret_key = hashlib.md5("rppowellemail@gmail.com".encode()).hexdigest()
16>>> secret_key = hashlib.md5("rppowellemail@gmail.com".encode("ascii")).hexdigest()
17>>> secret_key = hashlib.md5("rppowellemail@gmail.com".encode("utf-8")).hexdigest()
18
19################################################################################
20
21>>> import uuid
22
23>>> u = uuid.UUID(secret_key)
24>>> str(u)
25
26################################################################################
27
28import base64
29
30>>> base64.b64encode("This is a test".encode()).decode()
31'VGhpcyBpcyBhIHRlc3Q='
32
33>>> base64.b64encode("This is a test".encode("ascii"))
34b'VGhpcyBpcyBhIHRlc3Q='
35>>> base64.b64encode("This is a test".encode("utf-8"))
36b'VGhpcyBpcyBhIHRlc3Q='
37
38>>> base64.b64decode(
39... base64.b64encode("This is a test".encode())
40... ).decode()
41'This is a test'
42
43################################################################################
44
45# pip install Jasypt2Python
46
47>>> from j2p.JASYPT import Decryptor
48
49>>> decryptor = Decryptor(jasypt_password)
50>>> plaintext = decryptor.decrypt(some_encrypted_text)
51
52################################################################################
53
54# pip install pycrypto
55
56>>> from Crypto.Cipher import AES
57>>> encryptor = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
58>>> message = "The answer is no" # len(message) == 16
59>>> ciphertext = encryptor.encrypt(message)
60>>> decryptor = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
61>>> decryptor.decrypt(ciphertext).decode()
62'The answer is no'
63
64>>> from Crypto.Cipher import AES
65>>> encryptor = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
66>>> message = "This is a test."
67>>> ciphertext = encryptor.encrypt(message)
68>>> decryptor = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
69>>> decryptor.decrypt(ciphertext).decode()
70'This is a test.'
71
72################################################################################
73
74>>> jsondata = {'key':'value', 'numberarray':[1,2,3]}
75>>> jsondata
76{'key': 'value', 'numberarray': [1, 2, 3]}
77
78>>> jsonstring = json.dumps(jsondata)
79>>> jsonstring
80'{"key": "value", "numberarray": [1, 2, 3]}'
81
82>>> escapedjsonstring = json.dumps(jsonstring)
83>>> escapedjsonstring
84'"{\\"key\\": \\"value\\", \\"numberarray\\": [1, 2, 3]}"'
85
86>>> json.loads(escapedjsonstring)
87'{"key": "value", "numberarray": [1, 2, 3]}'
88
89>>> json.loads(json.loads(escapedjsonstring))
90{'key': 'value', 'numberarray': [1, 2, 3]}