我正在尝试使用AES_ctr128_encrypt进行加密和解密。编写了一个示例程序来执行相同的操作。 只有前16个字节已正确解密,其余未正确解密。 我假设这是一个API使用问题。非常感谢您提供有关纠正程序的帮助
实际程序:
#include <openssl/aes.h>
#include <openssl/md5.h>
#include <openssl/rand.h>
#include <openssl/hmac.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <openssl/modes.h>
struct ctr_state
{
unsigned char ivec[AES_BLOCK_SIZE];
unsigned int num;
unsigned char ecount[AES_BLOCK_SIZE];
};
AES_KEY key;
int bytes_read, bytes_written;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char outdata2[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE]; //16?
struct ctr_state state;
int init_ctr(struct ctr_state *state, const unsigned char iv[16])
{
state->num = 0;
memset(state->ecount, 0, 16); //16?
memset(state->ivec + 8, 0, 8);
memcpy(state->ivec, iv, 8); //16?
}
char * TextEncrypt(const char * text, int len)
{
AES_ctr128_encrypt((const unsigned char*)text, outdata, len, &key, state.ivec, state.ecount, &state.num);
printf("ecount : %u num : %u \n", state.ecount, state.num);
fflush(stdin);
return (char*)outdata;
}
char * TextDecrypt(const char* cypherText, int len)
{
AES_ctr128_encrypt((const unsigned char*)cypherText, outdata2, len, &key, state.ivec, state.ecount, &state.num);
printf("ecount : %d num : %d \n", state.ecount, state.num);
fflush(stdin);
return (char*)outdata;
}
int main()
{
//char text [] = "Text test to my program. trying to encrypt and decrypt using aes128";
char text [] = "Text test to my pr";
const char * chkey = "1234567812345678";
int len = strlen(text);
printf("text Length : %d \n", len);
printf("Clear Text : ");
for(int i=0; i<len; i++)
{
printf("%x ", text[i]);
}
printf("\n");
RAND_bytes(iv, AES_BLOCK_SIZE);
init_ctr(&state, iv);
AES_set_encrypt_key((const unsigned char*)chkey, 128, &key);
TextEncrypt(text, len);
printf("Encrypted Data : ");
for(int i=0; i<len; i++)
{
printf("%x ", outdata[i]);
}
printf("\n");
init_ctr(&state, iv);
TextDecrypt((const char*)outdata, len);
printf("Decrypted Data: ");
for(int i=0; i<len; i++)
{
printf("%x ", outdata2[i]);
}
printf("\n");
getc(stdin);
return 0;
}
程序输出:
[pchanda@pchanda-vmlnx test]$ g++ aes_crypto_test_old.c -lcrypto -o test
[pchanda@pchanda-vmlnx test]$ ./test
text Length : 18
Clear Text : 54 65 78 74 20 74 65 73 74 20 74 6f 20 6d 79 20 70 72
ecount : 6296564 num : 2
Encrypted Data : d2 e6 e fa b0 aa 5e 72 40 d4 24 59 dc ca f0 6d c6 f9
ecount : 6296564 num : 2
Decrypted Data: 54 65 78 74 20 74 65 73 74 20 74 6f 20 6d 79 20 e2 ee