I was able to find the decrypt function with a few researches, and now I am trying to write laravel encrypt function using python.
I can decrypt using it:
class decrypter:
def __init__(cls, key):
cls.key = key
def decrypt(cls, text):
decoded_text = json.loads(base64.b64decode(text))
iv = base64.b64decode(decoded_text['iv'])
crypt_object = AES.new(key=cls.key, mode=AES.MODE_CBC, IV=iv)
decoded = base64.b64decode(decoded_text['value'])
decrypted = crypt_object.decrypt(decoded)
return unpad(decrypted, 16).decode('utf-8')
def decrypt_string(str):
try:
key = b"xxxx xxxxxx x xxxx xxxxx"
key = base64.b64decode(key)
msg = str
obj = decrypter(key)
decrypted = obj.decrypt(msg)
return decrypted
except Exception as e:
logla.logla(e, "decrypt_string")
print(e)
But I couldn't find a source for the encrypt method. There is a source I could find, but I couldn't run it.
CodePudding user response:
For encryption, proceed in the opposite direction:
- Create an IV
- Pad plaintext
- Save IV and ciphertext to JSON
- Encode JSON with Base64
class encrypter:
def __init__(cls, key):
cls.key = key
def encrypt(cls, text):
iv = get_random_bytes(16)
msg = pad(text, 16)
crypt_object = AES.new(key=cls.key, mode=AES.MODE_CBC, IV=iv)
encrypted = crypt_object.encrypt(msg)
json_string = json.dumps({'iv': base64.b64encode(iv).decode(), 'value': base64.b64encode(encrypted).decode()})
return base64.b64encode(json_string.encode())
def encrypt_string(str):
try:
key = b'xxxx xxxxxx x xxxx xxxxx'
key = base64.b64decode(key)
msg = str
obj = encrypter(key)
encrypted = obj.encrypt(msg)
return encrypted
except Exception as e:
print(e)
import statements:
import json
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
and test case:
str = b'This is a test plaintext'
encrypted = encrypt_string(str)
decrypted = decrypt_string(encrypted)
print(encrypted)
print(decrypted)