QT+openssl 实现aes 的 ebc 加解密过程pkcs填充
以下是使用QT和openssl库实现AES的ECB加解密过程,以及PKCS填充的示例代码:
#include <QCoreApplication>
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
void aes_encrypt(const unsigned char *plaintext, int plaintext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *ciphertext, int *ciphertext_len)
{
EVP_CIPHER_CTX *ctx;
int len;
*ciphertext_len = 0;
if(!(ctx = EVP_CIPHER_CTX_new()))
return;
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv))
return;
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
return;
*ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
return;
*ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
}
void aes_decrypt(const unsigned char *ciphertext, int ciphertext_len,
const unsigned char *key, const unsigned char *iv,
unsigned char *plaintext, int *plaintext_len)
{
EVP_CIPHER_CTX *ctx;
int len;
*plaintext_len = 0;
if(!(ctx = EVP_CIPHER_CTX_new()))
return;
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv))
return;
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
return;
*plaintext_len = len;
if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
return;
*plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
}
void pkcs7_pad(const unsigned char *input, int input_len,
unsigned char *output, int *output_len)
{
int pad_len = AES_BLOCK_SIZE - (input_len % AES_BLOCK_SIZE);
*output_len = input_len + pad_len;
for(int i = 0; i < input_len; i++)
output[i] = input[i];
for(int i = input_len; i < *output_len; i++)
output[i] = pad_len;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const unsigned char *key = (const unsigned char *)"0123456789abcdef";
const unsigned char *iv = (const unsigned char *)"0123456789abcdef";
unsigned char plaintext[] = "Hello, world!";
int plaintext_len = strlen((char *)plaintext);
int ciphertext_len = 0;
unsigned char ciphertext[plaintext_len + AES_BLOCK_SIZE];
aes_encrypt(plaintext, plaintext_len, key, iv, ciphertext, &ciphertext_len);
printf("Ciphertext: ");
for(int i = 0; i < ciphertext_len; i++)
printf("%02x", ciphertext[i]);
printf("\n");
int decrypted_len = 0;
unsigned char decrypted[plaintext_len];
aes_decrypt(ciphertext, ciphertext_len, key, iv, decrypted, &decrypted_len);
printf("Plaintext: %s\n", decrypted);
unsigned char padded_plaintext[AES_BLOCK_SIZE * (plaintext_len / AES_BLOCK_SIZE + 1)];
int padded_plaintext_len = 0;
pkcs7_pad(plaintext, plaintext_len, padded_plaintext, &padded_plaintext_len);
printf("Padded plaintext: ");
for(int i = 0; i < padded_plaintext_len; i++)
printf("%02x", padded_plaintext[i]);
printf("\n");
return a.exec();
}
在这个示例代码中,我们使用了OpenSSL库提供的EVP API来实现AES的ECB加解密。我们还实现了PKCS#7填充,以确保输入数据的长度是AES块大小的整数倍。
在这个示例代码中,我们使用了128位AES密钥和IV。请注意,这些是示例值,您应该使用真正的随机密钥和IV来保护您的数据。
以上就是使用QT和openssl库实现AES的ECB加解密过程,以及PKCS#7填充的示例代码
原文地址: https://www.cveoy.top/t/topic/eokV 著作权归作者所有。请勿转载和采集!