我在下面有一些代码。我的问题是我有一个奇怪的加密和解密字符数组结尾。
#include <iostream>
#include <openssl\evp.h>
#define AES_BLOCK_SIZE 16
static EVP_CIPHER_CTX Encrypt_Context, Decrypt_Context;
int aes_init(unsigned char *key_data, int key_data_len, unsigned char *salt, EVP_CIPHER_CTX *e_ctx,
EVP_CIPHER_CTX *d_ctx)
{
int i, nrounds = 1;
unsigned char key[16], iv[16];
i = EVP_BytesToKey(EVP_aes_128_cbc(), EVP_sha1(), salt, key_data, key_data_len, nrounds, key, iv);
if (i != 16) {
printf("Key size is %d bits - should be 128 bits\n", i);
return -1;
}
EVP_CIPHER_CTX_init(e_ctx);
EVP_EncryptInit_ex(e_ctx, EVP_aes_128_cbc(), NULL, key, iv);
EVP_CIPHER_CTX_init(d_ctx);
EVP_DecryptInit_ex(d_ctx, EVP_aes_128_cbc(), NULL, key, iv);
return 0;
}
unsigned char *aes_encrypt(EVP_CIPHER_CTX *e, unsigned char *plaintext, int *len)
{
int c_len = *len + AES_BLOCK_SIZE, f_len = 0;
unsigned char *ciphertext = (unsigned char *)malloc(c_len);
EVP_EncryptInit_ex(e, NULL, NULL, NULL, NULL);
EVP_EncryptUpdate(e, ciphertext, &c_len, plaintext, *len);
EVP_EncryptFinal_ex(e, ciphertext+c_len, &f_len);
*len = c_len + f_len;
return ciphertext;
}
unsigned char *aes_decrypt(EVP_CIPHER_CTX *e, unsigned char *ciphertext, int *len)
{
int p_len = *len, f_len = 0;
unsigned char *plaintext = (unsigned char*)malloc(p_len);
EVP_DecryptInit_ex(e, NULL, NULL, NULL, NULL);
EVP_DecryptUpdate(e, plaintext, &p_len, ciphertext, *len);
EVP_DecryptFinal_ex(e, plaintext+p_len, &f_len);
*len = p_len + f_len;
return plaintext;
}
void main()
{
unsigned char * data_to_encrypt = (unsigned char*)"aaaaaaaaabbbbbbbbbbbbbbccccccccc";
unsigned char *key_data = (unsigned char *)"aaaaaaaaaaaaaaaa";
int key_data_len = strlen((const char*) key_data);
char * ciphertext;
char * plaintext;
aes_init(key_data, 16, NULL, &Encrypt_Context, &Decrypt_Context);
int length = strlen((const char*) data_to_encrypt)-1;
printf("Clear text :%s\n", data_to_encrypt);
ciphertext = (char *)aes_encrypt(&Encrypt_Context, data_to_encrypt, &length);
printf("Crypted text :%s\n", ciphertext);
plaintext = (char *)aes_decrypt(&Decrypt_Context, (unsigned char*)ciphertext, &length);
printf("Decrypted text :%s\n", plaintext);
}
使用此代码,我进入控制台:
明文:aaaaaaaaabbbbbbbbbbbbcccccccccc 加密文本:°ЁТ☼#єз▬├^^,♦Ёфм:ЇъШ╙y╒КzukЩu@8¤════════════════════解密¤ aaaaaaaabbbbbbbbbbbbbbcccccccc☺¤¤¤¤</p>
什么是加密文本末尾的═══════════════¤¤¤¤和解密末尾的☺¤¤¤¤?我的代码有什么问题?
谢谢!