2014-06-15 205 views
2

美好的一天,紳士!我正在嘗試使用帶有256位密鑰的aes ctr來加密和解密字符串。下面我發佈了代碼。我錯過了什麼,但我無法弄清楚什麼。由解密產生的Checktext與明文不同。提前致謝!AES 256 CTR加密/解密使用Visual Studio和Openssl

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); 
    } 
+0

這是什麼問題更換

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

? – SLaks

+0

@SLaks對不起。由解密產生的Checktext與明文不同。 –

+0

[OpenSSL上的AES CTR 256加密操作模式]的可能重複(http://stackoverflow.com/questions/3141860/aes-ctr-256-encryption-mode-of-operation-on-openssl) – jww

回答

4

解密時,與

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

事實上,它工作。從我讀過的內容看來,AES_set_decrypt_key僅適用於某些模式。 (它爲aes cbc工作)。非常感謝! –

+0

很高興幫助:) – ChiaraHsieh