Skip to content

Instantly share code, notes, and snippets.

@bluetechy
Forked from nbah22/laravel_encryption.py
Created August 16, 2018 06:35
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bluetechy/5580fab27510906711a2775f3c4f5ce3 to your computer and use it in GitHub Desktop.
Save bluetechy/5580fab27510906711a2775f3c4f5ce3 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')
@lillois59
Copy link

File "laravel_encryption.py", line 28, in decrypt
value = bytes(dic['value'], 'utf-8')
TypeError: str() takes at most 1 argument (2 given)

can you help me to solve it please

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