2

Good day, gentleman! I am trying to encrypt and decrypt a string using aes ctr with a 256-bit key. Below I posted the code. I'm missing something, but I can't figure out what. Checktext resulted from decryption is not the same as the plaintext. Thanks in advance!

struct ctr_state 
{ 
    unsigned char ivec[16]; 
    unsigned int num; 
    unsigned char ecount[16]; 
}; 

int init_ctr(struct ctr_state *state, const unsigned char iv[16])
{ 
    state->num = 0; 

    memset(state->ecount,0,16);
    memset(state->ivec + 8, 0, 8);   /* Copy IV into 'ivec' */ 
    memcpy(state->ivec, iv, 8); 

    return 0;
} 

struct ctr_state state;

void ctr_encrypt(const size_t encslength, AES_KEY key, int length) 
    {
        init_ctr(&state, iv);
        unsigned char my_data[16], output[16];

        AES_set_encrypt_key((unsigned char*)rkey, 256, &key);

        for (int i=1; i<encslength/16+1; i++)
        {
            memset(my_data,0,16);
            memcpy(my_data,plaintext+((i-1)*16),16);
            AES_ctr128_encrypt((unsigned char*)my_data, (unsigned char*)output, 16, &key, state.ivec, state.ecount, &state.num);
            memcpy(ciphertext+((i-1)*16),output,16);
        }

        hexdump(stdout, "ciphertext", (unsigned char*)ciphertext, length);
    }


    void ctr_decrypt(const size_t encslength, AES_KEY key, int length)
    {
        init_ctr(&state, iv);
        unsigned char my_data[16], output[16];

        AES_set_decrypt_key((unsigned char*)rkey, 256, &key);

        for (int i=1; i<encslength/16+1; i++)
        {
            memset(my_data,0,16);
            memcpy(my_data,ciphertext+((i-1)*16),16);
            AES_ctr128_encrypt((unsigned char*)my_data, (unsigned char*)output, 16, &key, state.ivec, state.ecount, &state.num);
            memcpy(checktext+((i-1)*16),output,16);
        }

        hexdump(stdout, "checktext", (unsigned char*)checktext, length);
    }
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
Tanatos Daniel
  • 558
  • 2
  • 9
  • 27
  • @SLaks Sorry. Checktext resulted from decryption is not the same as the plaintext. – Tanatos Daniel Jun 15 '14 at 13:48
  • possible duplicate of [AES CTR 256 Encryption Mode of operation on OpenSSL](http://stackoverflow.com/questions/3141860/aes-ctr-256-encryption-mode-of-operation-on-openssl) – jww Jun 15 '14 at 22:31

1 Answers1

4

During decryption, replace

AES_set_decrypt_key((unsigned char*)rkey, 256, &key);

with

AES_set_encrypt_key((unsigned char*)rkey, 256, &key);
Chiara Hsieh
  • 3,273
  • 23
  • 32
  • Indeed, it worked. From what I have read, it appears AES_set_decrypt_key only works with certain modes. (it worked for aes cbc). Lots of thanks! – Tanatos Daniel Jun 16 '14 at 22:28
  • I am also looking for AES 256 encrypt/decrypt with CTR mode using c#. Is it a good idea to use this or some new library came in dotnet ? please advice – user2463514 Aug 01 '19 at 00:10