Skip to content

Instantly share code, notes, and snippets.

@samuelchen
Last active January 14, 2019 05:20
Show Gist options
  • Select an option

  • Save samuelchen/433107e4437c711a0f9d53e0e24434d7 to your computer and use it in GitHub Desktop.

Select an option

Save samuelchen/433107e4437c711a0f9d53e0e24434d7 to your computer and use it in GitHub Desktop.
BASE4, MD5, SHA1, SHA256, AES, RSA encoding and encryption sample and benchmark in python
#!/user/env python
# by Samuel <[email protected]>
import json
import base64
import hashlib
import datetime
from Crypto.Cipher import AES, PKCS1_v1_5
from Crypto.PublicKey import RSA, DSA
from Crypto import Random
from Crypto.Util.Padding import pad, unpad
def base64_encode(data):
b = data.encode('utf-8')
r = base64.b64encode(b)
return r
def base64_decode(data):
r = base64.b64decode(data)
r = r.decode('utf-8')
return r
def md5_encode(data):
b = data.encode('utf-8')
dg = hashlib.md5(b)
r = dg.hexdigest()
return r
def md5_decode(data):
return '<Irrversible. MD5 is one way algorithm.>'
def sha1_encode(data):
b = data.encode('utf-8')
dg = hashlib.sha1(b)
r = dg.hexdigest()
return r
def sha1_decode(data):
return '<Irrversible. SHA1 is one way algorithm.>'
def sha256_encode(data):
b = data.encode('utf-8')
dg = hashlib.sha256(b)
r = dg.hexdigest()
return r
def sha256_decode(data):
return '<Irrversible. SHA256 is one way algorithm.>'
def rsa_generate_keys():
random_generator = Random.new().read
rsa = RSA.generate(1024, random_generator)
private_pem = rsa.exportKey()
with open('private.pem', 'wb') as f:
f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('public.pem', 'wb') as f:
f.write(public_pem)
def rsa_encode(data, public_key):
b = data.encode(encoding="utf-8")
# print('Public key: %s' % public_key)
key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(key)
r = cipher.encrypt(b)
return r
def rsa_decode(data, private_key):
b = data
# print('Private key: %s' % private_key)
key = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(key)
r = cipher.decrypt(b, b'ERROR')
r = r.decode('utf-8')
return r
def aes_generate_key(len=32):
key = AES.get_random_bytes(len)
# key = base64.b64encode(key)
with open('aes_key.txt', 'wb') as f:
f.write(key)
def aes_encode(data, key):
b = data.encode('utf-8')
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(b, AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
r = json.dumps({'iv': iv, 'ct': ct})
return r
def aes_decode(data, key):
b = json.loads(data)
iv = base64.b64decode(b['iv'])
ct = base64.b64decode(b['ct'])
cipher = AES.new(key, AES.MODE_CBC, iv)
ct_bytes = unpad(cipher.decrypt(ct), AES.block_size)
r = ct_bytes.decode('utf-8')
return r
if __name__ == '__main__':
data = 'Hello world!'
print('\n----- BASE64 -----')
print('origin string : %s' % data)
encoded = base64_encode(data)
print('encoded data : %s' % encoded)
s = base64_decode(encoded)
print('decoded string: %s' % s)
print('\n----- MD5 -----')
print('origin string : %s' % data)
encoded = md5_encode(data)
print('encoded data : %s' % encoded)
decoded = md5_decode(encoded)
print('decoded data : %s' % decoded)
print('\n----- SHA1 -----')
print('origin string : %s' % data)
encoded = sha1_encode(data)
print('encoded data : %s' % encoded)
decoded = sha1_decode(encoded)
print('decoded data : %s' % decoded)
print('\n----- SHA256 -----')
print('origin string : %s' % data)
encoded = sha256_encode(data)
print('encoded data : %s' % encoded)
decoded = sha256_decode(encoded)
print('decoded data : %s' % decoded)
print('\n----- RSA -----')
rsa_generate_keys()
public_key = ''
private_key = ''
with open('public.pem', 'r') as f:
public_key = f.read()
with open('private.pem', 'r') as f:
private_key = f.read()
print('origin string : %s' % data)
encoded = rsa_encode(data, public_key)
print('encoded data : %s' % encoded)
s = rsa_decode(encoded, private_key)
print('decoded string: %s' % s)
print('\n----- AES -----')
aes_generate_key()
key = ''
with open('aes_key.txt', 'rb') as f:
key = f.read()
print('origin string : %s' % data)
encoded = aes_encode(data, key)
print('encoded data : %s' % encoded)
decoded = aes_decode(encoded, key)
print('decoded string: %s' % s)
test_data = (
"""Amazon’s Echo voice assistants have gone from expensive parlor trick of a gadget to the perfect stocking stuffer, so you probably weren’t surprised to see one of these smart home speakers wrapped up with your name on it. Well, maybe be a little surprised.
The Echo is a perfect first step or addition to a smart home, and taking advantage of some of its lesser-known features could take you from smart home skeptic to convert faster than you think.
Stop saying “Alexa”
Thankfully if you have a friend or family member with a name that sounds anything like “Alexa,” you can change the “wake word” that activates your new voice assistant. Download the Alexa app to your smartphone, then navigate to the Devices tab. Select “Echo and Alexa,” pick your Echo device, then select “Wake Word.” You can pick from Alexa, Echo, Computer, and Amazon. While it’s an admittedly limited selection of options, you’ll be happy to be rid of any false positives, and will feel like a Star Trek character each time you say “Computer!”
Get your Echo to read to you
Linking your Echo device to your Amazon account does more than personalize your experience. It links your Echo to the content you’ve already got from the company. So when you’re trying to wind down for the evening, your Echo can read you a story from your library of Audible content. You can also set sleep timers, so your book ends as you drift off to la-la land.
Get familiar with Alexa Skills
Voice assistants can tell you the weather, turn on your lights, and alert you to an upcoming appointment. But with the help of third-party developers, your Echo device can get a lot more interesting and entertaining when paired with the right Alexa Skills.
Alexa Skills are essentially apps you can enable on your Echo, and include offerings like trivia games, meditation timers, and news reports from major outlets. You can get started by asking your Echo device to “help me get started with skills.” Use Skills to learn a new word each day, play a round of Jeopardy!, or even find your phone when you misplace it.
Give everyone a voice
It’s your gift, but everyone in your home can benefit from your new Echo by giving each person their own personalized experience. You can ask your Echo to “learn my voice,” then go through a few minutes of repeating what your Echo says.
Teaching the Echo your voice means you can send and receive messages privately, skip over previously heard news stories, and bypass the shopping voice code needed for voice purchases. If you’re a member of an Amazon Household, you’ll also be able to link your services to the Echo device in question."""
).split()
test_data = test_data
data_item_num = len(test_data)
print('\n----- BASE64 %s words -----' % data_item_num)
t = datetime.datetime.utcnow()
for data in test_data:
encoded = base64_encode(data)
decoded = base64_decode(encoded)
assert data == decoded
t = datetime.datetime.utcnow() - t
print(t.total_seconds() * 1000, 'ms')
print('\n----- AES %s words -----' % data_item_num)
with open('aes_key.txt', 'rb') as f:
key = f.read()
t = datetime.datetime.utcnow()
for data in test_data:
encoded = aes_encode(data, key)
decoded = aes_decode(encoded, key)
assert data == decoded
t = datetime.datetime.utcnow() - t
print(t.total_seconds() * 1000, 'ms')
print('\n----- RSA %s words -----' % data_item_num)
aes_generate_key()
key = ''
with open('aes_key.txt', 'rb') as f:
key = f.read()
t = datetime.datetime.utcnow()
for data in test_data:
encoded = rsa_encode(data, public_key)
decoded = rsa_decode(encoded, private_key)
assert data == decoded
t = datetime.datetime.utcnow() - t
print(t.total_seconds() * 1000, 'ms')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment