Search code examples
cencryptionopensslaes

OpenSSL Encryption AES 128bit CBC


When I run this program, AES_cbc_encrypt produces a different cipher during every loop. Is there a way to reset the state, so that the same cipher is produced during every loop?

void main() 
{
int i;
unsigned char iv[]  = "\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00\xA2\xB2\xC2\xD2\xE2\xF2";
unsigned char plaintxt[] = "\x25\x50\x44\x46\x2d\x31\x2e\x35\x0a\x25\xd0\xd4\xc5\xd8\x0a\x34";
unsigned char ciphertext[] = "\xd0\x6b\xf9\xd0\xda\xb8\xe8\xef\x88\x06\x60\xd2\xaf\x65\xaa\x82";
unsigned char cipher[128];
char key[] = "\x95\xfa\x20\x30\xe7\x3e\xd3\xf8\xda\x76\x1b\x4e\xb8\x05\xdf\xd7";


for(int j = 0; j < 10; j++) {

    AES_KEY aeskeyEnc;
    AES_set_encrypt_key(key, 128, &aeskeyEnc);
    AES_cbc_encrypt(plaintxt, cipher, 33, &aeskeyEnc, iv, AES_ENCRYPT);


    for (i = 0; i < KEYSIZE; i++) {     
        printf("%.2x", (unsigned char)cipher[i]);
    }
    printf("\n");
}   
}

Solution

  • nevermind, it seems it's because for some weird reason AES_cbc_encrypt function modifies the IV.

    for(int j = 0; j < 10; j++) {
    
        AES_KEY aeskeyEnc;
        unsigned char iv[]  = "\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00\xA2\xB2\xC2\xD2\xE2\xF2";
        AES_set_encrypt_key(key, 128, &aeskeyEnc);
        AES_cbc_encrypt(plaintxt, cipher, 33, &aeskeyEnc, iv, AES_ENCRYPT);
    
    
        for (i = 0; i < KEYSIZE; i++) {     
            printf("%.2x", (unsigned char)cipher[i]);
        }
        printf("\n");
    }