[openssl-users] Implement CBC decryption using EVP_aes_128_ecb()

Pavan Maddamsetti pavan.maddamsetti at gmail.com
Mon May 30 00:59:06 UTC 2016


Hello all,

I am attempting to solve Cryptopals Challenge 10 (
http://cryptopals.com/sets/2/challenges/10) using OpenSSL. Here's my code:

-----

#include <openssl/evp.h>
#include <openssl/bio.h>

enum {
BLKSIZ = 16
};

int
main(void)
{
unsigned char in[BLKSIZ], out[BLKSIZ], vec[BLKSIZ],
key[] = "YELLOW SUBMARINE";
int i, j;
EVP_CIPHER_CTX ctx;
BIO *bio, *b64, *bio_out;

EVP_CIPHER_CTX_init(&ctx);
EVP_CIPHER_CTX_set_padding(&ctx, BLKSIZ);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_ecb(), NULL, key, NULL);

b64 = BIO_new(BIO_f_base64());
bio = BIO_new_fp(stdin, BIO_NOCLOSE);
bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);
BIO_push(b64, bio);

for (i = 0; i < BLKSIZ; i++)
vec[i] = '\x00';
while ((i = BIO_read(b64, in, BLKSIZ)) > 0) {
EVP_DecryptUpdate(&ctx, out, &j, in, i);
for (i = 0; i < j; i++) {
printf("\nin[%d]:  %02x\nout[%d]: %02x\nvec[%d]: %02x\n", i, in[i], i,
out[i], i, vec[i]);
out[i] ^= vec[i];
vec[i] = in[i];
}
BIO_write(bio_out, out, j);
}
EVP_DecryptFinal_ex(&ctx, out, &j);
for (i = 0; i < j; i++)
out[i] ^= vec[i];
BIO_write(bio_out, out, j);
BIO_flush(bio_out);

return 0;
}

-----

If I change the cipher type to EVP_aes_128_cbc() and remove the XOR,
decryption seems to work correctly. However, as written what happens is
that starting from the second block, each decrypted byte is the same as the
corresponding ciphertext byte from the previous block. So when I XOR the
two, I get a null byte. This means only the first 16 characters print out
correctly followed by lots of '\0'.

Can someone clue me in as to what is going on here? Would appreciate the
help.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mta.openssl.org/pipermail/openssl-users/attachments/20160529/ced3e917/attachment.html>


More information about the openssl-users mailing list