Last active
January 8, 2020 08:22
-
-
Save everesio/10aaa873ecfc3f050533fb5576427dfa to your computer and use it in GitHub Desktop.
decrypt spring encrypted secrets in python 3
This file contains hidden or 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
import base64 | |
import os | |
from hashlib import pbkdf2_hmac | |
# package pycryptodome = "*" | |
from Crypto.Cipher import AES | |
from Crypto.Cipher import PKCS1_v1_5 | |
from Crypto.PublicKey import RSA | |
def unpad(s): | |
return s[:-ord(s[len(s) - 1:])] | |
def decrypt(data, private_key, salt): | |
length = int.from_bytes(data[0:2], byteorder="big") # 2 bytes | |
random = data[2:length + 2] # 256 bytes (iv length is 16) | |
# decrypt the session key with the private RSA key - java uses RSA/ECB/PKCS1Padding | |
cipher = PKCS1_v1_5.new(private_key) | |
iv = cipher.decrypt(ciphertext=random, sentinel='Error while decrypting') | |
password = iv.hex() | |
# PBKDF2WithHmacSHA1 iterationCount = 1024, keyLength = 256 | |
aes_secret_key = pbkdf2_hmac('sha1', password.encode("utf-8"), bytearray.fromhex(salt), 1024, 32) # 32 * 8 = 256 bits | |
cipherAes = AES.new(aes_secret_key, AES.MODE_CBC, iv) | |
aesEncrypted = cipherAes.decrypt(data[2 + len(random):]) | |
unpadded = unpad(aesEncrypted) | |
# remove prepended initialization vector - 16 bytes | |
encrypted_bytes = unpadded[len(iv):] | |
return encrypted_bytes.decode("utf-8") | |
def decrypt_value(value, private_key, salt='deadbeef'): | |
cipher_prefix = "{cipher}" | |
if not value.startswith(cipher_prefix): | |
return value | |
value = value[len(cipher_prefix):] | |
data = base64.b64decode(value.encode("UTF-8")) | |
return decrypt(data, private_key, salt) | |
# example call | |
if __name__ == '__main__': | |
# privateKey = RSA.importKey(os.getenv("ENCRYPT_KEY")) | |
f = open('private.pem', 'r') | |
privateKey = RSA.importKey(f.read()) | |
password = "{cipher}AQAHWdKzJnjC/+H..........jT+DC4H/kb"; | |
plainText = decrypt_value(password, privateKey) | |
print(plainText) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment