Decrypt OpenSSL aes-256-cbc with Crypto++

526 views
Skip to first unread message

asoko

unread,
Oct 22, 2011, 9:52:15 PM10/22/11
to Crypto++ Users
Hi,


I'm trying to decrypt OpenSSL encrypted files with Crypto++,
especially aes-256-cbc :

openssl enc -aes-256-cbc -nosalt -in "file.pdf" -out file.enc -pass
pass:test


I'm using CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption but need to
derive the key and the IV from the password.
The key starts as the MD5 of the password, but after that I'm lost.

Any help appreciated.

Thanks.

asoko

unread,
Oct 23, 2011, 7:26:05 AM10/23/11
to Crypto++ Users
I was able to advance a little bit using OpenSSL library :


#include <openssl/evp.h>

std::string pass_phrase,file_in, file_out;

unsigned char key_str[32];
unsigned char iv[16];
EVP_BytesToKey(EVP_aes_256_cbc(),
EVP_md5(),
NULL,
(unsigned char*)pass_phrase.c_str(),
pass_phrase.size(),
1,
key_str,
iv);

CryptoPP::SecByteBlock key(key_str,32);

CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption cfbDecryption(key,
key.m_size,
iv);

CryptoPP::FileSource f(file_in.c_str(),
true,
new CryptoPP::StreamTransformationFilter(cfbDecryption,
new CryptoPP::FileSink(file_out.c_str())));

So I guess need to translate EVP_BytesToKey into Crypto++ lingo.


int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
const unsigned char *salt, const unsigned char *data, int datal,
int count, unsigned char *key, unsigned char *iv)
{
EVP_MD_CTX c;
unsigned char md_buf[EVP_MAX_MD_SIZE];
int niv,nkey,addmd=0;
unsigned int mds=0,i;

nkey=type->key_len;
niv=type->iv_len;
OPENSSL_assert(nkey <= EVP_MAX_KEY_LENGTH);
OPENSSL_assert(niv <= EVP_MAX_IV_LENGTH);

if (data == NULL) return(nkey);

EVP_MD_CTX_init(&c);
for (;;)
{
if (!EVP_DigestInit_ex(&c,md, NULL))
return 0;
if (addmd++)
EVP_DigestUpdate(&c,&(md_buf[0]),mds);
EVP_DigestUpdate(&c,data,datal);
if (salt != NULL)
EVP_DigestUpdate(&c,salt,PKCS5_SALT_LEN);
EVP_DigestFinal_ex(&c,&(md_buf[0]),&mds);

for (i=1; i<(unsigned int)count; i++)
{
EVP_DigestInit_ex(&c,md, NULL);
EVP_DigestUpdate(&c,&(md_buf[0]),mds);
EVP_DigestFinal_ex(&c,&(md_buf[0]),&mds);
}
i=0;
if (nkey)
{
for (;;)
{
if (nkey == 0) break;
if (i == mds) break;
if (key != NULL)
*(key++)=md_buf[i];
nkey--;
i++;
}
}
if (niv && (i != mds))
{
for (;;)
{
if (niv == 0) break;
if (i == mds) break;
if (iv != NULL)
*(iv++)=md_buf[i];
niv--;
i++;
}
}
if ((nkey == 0) && (niv == 0)) break;
}
EVP_MD_CTX_cleanup(&c);
OPENSSL_cleanse(&(md_buf[0]),EVP_MAX_MD_SIZE);
return(type->key_len);
}

Troy

unread,
Sep 8, 2012, 5:34:39 AM9/8/12
to cryptop...@googlegroups.com
Did you end up finding a solution to this problem? I'm looking at needing the EVP_BytesToKey function as well, but really don't want to include an openssl dependency if I'm already using crypto++.
Reply all
Reply to author
Forward
0 new messages