Created
September 13, 2019 11:17
-
-
Save bryanculver/d785117ea54af496b60bae2d7b00d439 to your computer and use it in GitHub Desktop.
A Python Implementation of Node's createCipher Encrypt/Decrypt Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
DO NOT USE THIS IN PRODUCTION! PLEASE USE createCipheriv IN NODE! | |
OK... If you got this far you're probably like me and got stuck needing to find a way do mimic Node's createCipher. | |
Seriously though, please don't use this... | |
See: https://nodejs.org/docs/latest-v10.x/api/crypto.html#crypto_crypto_createcipher_algorithm_password_options | |
""" | |
from Crypto import Random | |
from Crypto.Cipher import AES | |
from hashlib import md5 | |
BS = 16 | |
def EVP_BytesToKey(password, salt, key_len, iv_len): | |
dtot = md5(password + salt).digest() | |
d = [ dtot ] | |
while len(dtot)<(iv_len+key_len): | |
d.append( md5(d[-1] + password + salt).digest() ) | |
dtot += d[-1] | |
return dtot[:key_len], dtot[key_len:key_len+iv_len] | |
def pad(data): | |
padding = BS - len(data) % BS | |
return data + padding * chr(padding) | |
def unpad(data): | |
return data[0:-data[-1]] | |
def decrypt(hex_data, password): | |
key,iv = EVP_BytesToKey(password, b'', 32,16) | |
data = bytes.fromhex(hex_data) | |
aes = AES.new(key, AES.MODE_CBC, iv) | |
return unpad(aes.decrypt(data)).decode("utf-8") | |
def encrypt(data, password): | |
key,iv = EVP_BytesToKey(password, b'', 32,16) | |
aes = AES.new(key, AES.MODE_CBC, iv) | |
return aes.encrypt(pad(data)).hex() | |
encrypted = encrypt('This is something I want encrypted', b'password1234') | |
print(encrypted) | |
decrypted = decrypt(encrypted, b'password1234') | |
print(decrypted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment