一、openssl aead算法接口使用示例:
//gcc -g -lssl aead_test.c -lcrypto -L /usr/local/lib/
#include <string.h>
#include <openssl/evp.h>
#define IV_SIZE 8
#define KEY_SIZE 24
#define INPUT_SIZE 100
void print_hexdata(unsigned char *b, int len, char *title)
{
int i = 0, c = 0;
printf("===================================== %s =====================================\n", title);
for (; i<len; i++) {
printf("0x%02x ", b[i]);
c++;
if (!(c%16))
printf("\n");
}
printf("\n");
}
int gcm_encrypt(unsigned char *plaintext, int plaintext_len,
unsigned char *aad, int aad_len,
unsigned char *key,
unsigned char *iv, int iv_len,
unsigned char *ciphertext,
unsigned char *tag)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new()))
return -1;
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
return -1;
/*
* Set IV length if default 12 bytes (96 bits) is not appropriate
*/
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL))
return -1;
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
return -1;
/*
* Provide any AAD data. This can be called zero or more times as
* required
*/
if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
return -1;
printf("len:%d\n", len);
/*
* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
return -1;
ciphertext_len = len;
printf("len:%d\n", len);
/*
* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
return -1;
ciphertext_len += len;
printf("len:%d\n", len);
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
return -1;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
retur