Skip to content

Instantly share code, notes, and snippets.

@nbah22
Last active November 3, 2019 02:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nbah22/1fd7da3deb5b416a0524 to your computer and use it in GitHub Desktop.
Save nbah22/1fd7da3deb5b416a0524 to your computer and use it in GitHub Desktop.
Laravel-compatible encryption and decryption in python
import os
import json
import hashlib
import hmac
import base64
from Crypto.Cipher import AES
from phpserialize import loads, dumps
def mcrypt_decrypt(value, iv):
global key
AES.key_size = 128
crypt_object = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
return crypt_object.decrypt(value)
def mcrypt_encrypt(value, iv):
global key
AES.key_size = 128
crypt_object = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
return crypt_object.encrypt(value)
def decrypt(bstring):
global key
dic = json.loads(base64.b64decode(bstring).decode())
mac = dic['mac']
value = bytes(dic['value'], 'utf-8')
iv = bytes(dic['iv'], 'utf-8')
if mac == hmac.new(key, iv+value, hashlib.sha256).hexdigest():
return loads(mcrypt_decrypt(base64.b64decode(value), base64.b64decode(iv))).decode()
return ''
def encrypt(string):
global key
iv = os.urandom(16)
string = dumps(string)
padding = 16 - len(string) % 16
string += bytes(chr(padding) * padding, 'utf-8')
value = base64.b64encode(mcrypt_encrypt(string, iv))
iv = base64.b64encode(iv)
mac = hmac.new(key, iv+value, hashlib.sha256).hexdigest()
dic = {'iv': iv.decode(), 'value': value.decode(), 'mac': mac}
return base64.b64encode(bytes(json.dumps(dic), 'utf-8'))
key = b'1234567890abcdef'
print(decrypt(encrypt('something')) == 'something')
@nbah22
Copy link
Author

nbah22 commented Nov 8, 2015

Created with help of https://gist.github.com/fideloper/c4806c504e46e8cdb00a
You will need to pip3 install pycrypto phpserialize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment