Skip to content

Instantly share code, notes, and snippets.

@Te-k
Created July 7, 2018 22:08
Show Gist options
  • Save Te-k/762f63ae2944f1d6b9146789fc7c7e70 to your computer and use it in GitHub Desktop.
Save Te-k/762f63ae2944f1d6b9146789fc7c7e70 to your computer and use it in GitHub Desktop.
Python script decrypting openssl encrypted files
from Crypto.Cipher import AES
import hashlib
def get_key_and_iv(password, salt, klen=32, ilen=16, msgdgst='md5'):
mdf = getattr(__import__('hashlib', fromlist=[msgdgst]), msgdgst)
password = password.encode('ascii','ignore') # convert to ASCII
try:
maxlen = klen + ilen
keyiv = mdf(password + salt).digest()
tmp = [keyiv]
while len(tmp) < maxlen:
tmp.append( mdf(tmp[-1] + password + salt).digest() )
keyiv += tmp[-1] # append the last byte
key = keyiv[:klen]
iv = keyiv[klen:klen+ilen]
return key, iv
except UnicodeDecodeError:
return None, None
if __name__ == '__main__':
INPUT = 'toto'
with open(INPUT, 'rb') as f:
cipher = f.read()
salt = cipher[8:16]
pwd = "toto"
key, iv = get_key_and_iv(pwd, salt, msgdgst="md5")
ciphertext = cipher[16:]
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_plaintext = cipher.decrypt(ciphertext)
padding_len = padded_plaintext[-1]
plaintext = padded_plaintext[:-padding_len]
print(plaintext.decode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment