Created
March 30, 2023 18:13
-
-
Save daemswibowo/074ab7cf634a74bd6b0886edad9f6c00 to your computer and use it in GitHub Desktop.
Python laravel encryption
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
from Crypto import Random | |
from Crypto.Cipher import AES | |
import base64 | |
import json | |
from phpserialize import unserialize, dumps | |
import hmac | |
import hashlib | |
class LaravelEncryption: | |
def __init__(self, key): | |
# self.key = key | |
AES.block_size = 16 | |
self.key = base64.b64decode(key) | |
def decrypt(self, text): | |
decoded_text = base64.b64decode(text) | |
decoded_text = json.loads(decoded_text) | |
iv = base64.b64decode(decoded_text['iv']) | |
crypt_object = AES.new(key=self.key, mode=AES.MODE_CBC, IV=iv) | |
decoded = base64.b64decode(decoded_text['value']) | |
decrypted = crypt_object.decrypt(decoded) | |
return unserialize(decrypted).decode('UTF-8') | |
def encrypt(self, text): | |
iv = Random.new().read(AES.block_size) | |
text = dumps(text) | |
padding = 16 - len(text) % 16 | |
text += bytes(chr(padding) * padding, 'utf-8') | |
cipher = AES.new(self.key, mode=AES.MODE_CBC, IV=iv) | |
value = base64.b64encode(cipher.encrypt(text)) | |
iv = base64.b64encode(iv) | |
mac = hmac.new(self.key, iv + value, hashlib.sha256).hexdigest() | |
dic = {'iv': iv.decode(), 'value': value.decode(), 'mac': mac} | |
return base64.b64encode(bytes(json.dumps(dic), 'utf-8')).decode('UTF-8') |
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
from app.utils.laravel_encryption import LaravelEncryption | |
key = b'QhGi88ju4rsBrtLRRalWvTvMoux7/7AnkvJZ49y9Q3M=' | |
message = '{"message":"hello world"}' | |
def test_should_decrypt_from_laravel(): | |
# arrange | |
encrypted = 'eyJpdiI6IitnRUVva2tNckhwdHMzeFlVOWl5TlE9PSIsInZhbHVlIjoiSURHb1VhY0ZRZVZIdm1ZRTJ1TDhXZC9rMGVqUVY5MnRpN3BoSHc4UzZsZVJnUFpyZVRidDE0UEtJMXFxOWxpNiIsIm1hYyI6ImViMDM5ZDE4NTg3MWNiYmZlYzM0NjNiYmZjNTVkMTQ4N2M2ODdjYTU2ZDgxOGYwNTM0MDllNDQzYmI3ZWIyNmEifQ==' | |
# action | |
result = LaravelEncryption(key).decrypt(encrypted) | |
# assert | |
assert message == result | |
def test_should_encrypt_from_laravel(): | |
# action | |
result = LaravelEncryption(key).encrypt(message) | |
result = LaravelEncryption(key).decrypt(result) | |
# assert | |
assert result == message |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment