Decrypt OpenSSL AES-256-CBC ciphertext with PyCrypto

Test while reading EVP_BytesToKey () for OpenSSL 1.0.1g Python 2.6.6, PyCrypto 2.0.1

Ciphertext creation

First, create a ciphertext with the openssl command. Password is password

$#Base64 encoded for output to terminal
$ echo 'This is plain text !' | openssl aes-256-cbc -e -k password | openssl base64 -e
U2FsdGVkX1/Ab5WcN6HAN6ppt5YvoqTzD2VuQBbtmLIzAeTkYZFRUjtjwu/M5oMO

Decryption process

Decrypt with PyCryto's AES

import base64
from hashlib import md5
from Crypto.Cipher import AES

encoded = 'U2FsdGVkX1/Ab5WcN6HAN6ppt5YvoqTzD2VuQBbtmLIzAeTkYZFRUjtjwu/M5oMO'
encrypted = base64.b64decode(encoded)
print 'encrypted: '+ repr(encrypted)
## encrypted: 'Salted__\xc0o\x95\x9c7\xa1\xc07\xaai\xb7\x96/\xa2\xa4\xf3\x0fen@\x16\xed\x98\xb23\x01\xe4\xe4a\x91QR;c\xc2\xef\xcc\xe6\x83\x0e'

# Salted__8 bytes following salt
salt = encrypted[8:16]
print 'salt: '+ repr(salt)
## salt: '\xc0o\x95\x9c7\xa1\xc07'

secret = 'password'
#Simplified, but imitating OpenSSL's KDF
hash1 = md5(secret + salt)
hash2 = md5(hash1.digest() + secret + salt)
hash3 = md5(hash2.digest() + secret + salt)
key = hash1.digest() + hash2.digest()
iv = hash3.digest()
print 'key: '+ repr(key)
print 'iv: '+ repr(iv)
## key: "\x1e\xfdh\xb0_\x05\xe1\x83x\xa5\xfe\x1d8&E#<'\x9f\xaf\x0e\xcba\x12\\KX\x897X\x90\x0c"
## iv: '4-\\iNh-\xc7\x99\tg\xe2\xbb\xcd\x12\xf5'


cipher = AES.new(key, AES.MODE_CBC, iv)
##Decrypt data excluding salt
decrypted = cipher.decrypt(encrypted[16:])
print 'decrypted: '+ repr(decrypted)
print 'original: '+ repr(decrypted[0:-ord(decrypted[-1])])
## decrypted: 'This is plain text !\n\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b'
## original: 'This is plain text !\n'

References

Recommended Posts

Decrypt OpenSSL AES-256-CBC ciphertext with PyCrypto
Decrypt files encrypted with openssl from python with openssl