Skip to content

Instantly share code, notes, and snippets.

@orian
Forked from fideloper/crypt.py
Last active April 12, 2022 20:48
Show Gist options
  • Save orian/f803a879abf7edc73966df44d65c6680 to your computer and use it in GitHub Desktop.
Save orian/f803a879abf7edc73966df44d65c6680 to your computer and use it in GitHub Desktop.
Decrypt Laravel-encrypted value
# Python3 code below
import os
import base64
import json
from Crypto.Cipher import AES
from phpserialize import loads
import hashlib
import hmac
def decrypt(payload):
data = json.loads(base64.b64decode(payload))
key=os.environ['APP_KEY']
if not valid_mac(key, data):
return None
value = base64.b64decode(data['value'])
iv = base64.b64decode(data['iv'])
return unserialize(mcrypt_decrypt(value, iv, key))
def mcrypt_decrypt(value, iv, key):
AES.key_size=128
crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)
return crypt_object.decrypt(value)
def unserialize(serialized):
return loads(serialized)
def valid_mac(key, payload):
dig = hmac.new(key, digestmod=hashlib.sha256)
dig.update(data['iv'].encode('utf8'))
dig.update(data['value'].encode('utf8'))
dig = dig.hexdigest()
return dig==payload['mac']
@shamimulalam
Copy link

Traceback (most recent call last):
File "/var/www/html/adnsms/SMS-Shooting-Process/Helpers/crypt.py", line 40, in
decrypt(code)
File "/var/www/html/adnsms/SMS-Shooting-Process/Helpers/crypt.py", line 19, in decrypt
return mcrypt_decrypt(value, iv, key)
File "/var/www/html/adnsms/SMS-Shooting-Process/Helpers/crypt.py", line 24, in mcrypt_decrypt
crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)
File "/var/www/html/adnsms/SMS-Shooting-Process/venv/lib/python3.8/site-packages/Crypto/Cipher/AES.py", line 234, in new
return _create_cipher(sys.modules[name], key, mode, *args, **kwargs)
File "/var/www/html/adnsms/SMS-Shooting-Process/venv/lib/python3.8/site-packages/Crypto/Cipher/init.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "/var/www/html/adnsms/SMS-Shooting-Process/venv/lib/python3.8/site-packages/Crypto/Cipher/_mode_cbc.py", line 274, in _create_cbc_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "/var/www/html/adnsms/SMS-Shooting-Process/venv/lib/python3.8/site-packages/Crypto/Cipher/AES.py", line 92, in _create_base_cipher
if len(key) not in key_size:
TypeError: argument of type 'int' is not iterable

Hey Orian, I'm getting this error while trying to decrypt. Can you help me out please ?

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