Last active
February 26, 2023 21:14
-
-
Save jgdev/6de6496c03fe8243211c84abc004cdb2 to your computer and use it in GitHub Desktop.
python encode/decode aes256 example
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
# pip3 uninstall pycrypto | |
# pip3 install pycryptodome | |
from Crypto.Cipher import AES | |
import base64 | |
BLOCK_SIZE = 16 | |
def pad(data): | |
pad = BLOCK_SIZE - len(data) % BLOCK_SIZE | |
return data + pad * chr(pad) | |
def unpad(padded): | |
pad = ord(chr(padded[-1])) | |
return padded[:-pad] | |
def _encrypt(data, password): | |
key, iv = get_key_iv(password) | |
data = pad(data) | |
aes = AES.new(key, AES.MODE_CBC, iv[:16]) | |
encrypted = aes.encrypt(data) | |
return base64.urlsafe_b64encode(encrypted) | |
def _decrypt(data, key, iv): | |
data = base64.b64decode(data) | |
key = base64.b64decode(key) | |
iv = base64.b64decode(iv) | |
aes = AES.new(key, AES.MODE_CBC, iv[:16]) | |
return unpad(aes.decrypt(data)) | |
# node -e 'console.log(crypto.randomBytes(32).toString("base64"))' | |
key = "IC7gTKZB6Ozb20mdRAHCFzJl2XsaU7nq3XFJoQqoGk0=" # secret environment variable | |
# node -e 'console.log(crypto.randomBytes(16).toString("base64"))' | |
iv = "KdLAu6oKOoffRURx9u0Ulw==" # already stored in the database | |
encoded_username = "Lx8aSNQeBACvbrNjycVyVg==" # already stored in the database | |
encoded_password = "4qxTadTDeQ2pzhSl83MicA==" # already stored in the database | |
decoded_username = _decrypt(encoded_username, key, iv).decode('utf8') | |
decoded_password = _decrypt(encoded_password, key, iv).decode('utf8') | |
print(decoded_username, decoded_password) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment