OpenSSL:EVP
lastmod 2019-12-24created 2019-12-242 edits
AES example
Every encryption library goes through init, update, and final steps.
- init: sets encryption-related information. (encryption method, key length, password, etc.)
- update: splits the data into blocks and performs encryption with the configured encryption method.
- final: if the size of the input plain text is not a multiple of the block size, extra data bytes remain at the end of the data; these bytes are padded to make a block of processable size, and then encryption is performed.
This function converts the input plain text into cipher text using the decryption key.
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
/* AES Encrypt Process */
int encrypt_block(unsigned char* cipherText, unsigned char* plainText, unsigned int plainTextLen, unsigned char* key)
{
EVP_CIPHER_CTX ctx;
int addLen=0, orgLen=0;
unsigned long err=0;
ERR_load_crypto_strings();
EVP_CIPHER_CTX_init(&ctx);
if (EVP_EncryptInit(&ctx, EVP_aes_128_ecb(), key, NULL) != 1) {
err = ERR_get_error();
printf("ERR: EVP_EncryptInit() - %s\n", ERR_error_string (err, NULL));
return -1;
}
if (EVP_EncryptUpdate(&ctx, cipherText, &orgLen, plainText, plainTextLen) != 1) {
err = ERR_get_error();
printf("ERR: EVP_EncryptUpdate() - %s\n", ERR_error_string (err, NULL));
return -1;
}
if (EVP_EncryptFinal(&ctx, cipherText+orgLen, &addLen) != 1) {
err = ERR_get_error();
printf("ERR: EVP_EncryptFinal() - %s\n", ERR_error_string (err, NULL));
return -1;
}
EVP_CIPHER_CTX_cleanup(&ctx);
ERR_free_strings();
return addLen + orgLen;
}
Before using the EVP library, you must first set up a context. The context structure records encryption-related information. EVP_CIPHER_CTX_init() performs initialization, and EVP_CIPHER_CTX_cleanup() releases it.
Block cipher algorithms use modes such as ECB and CBC; this function uses ECB mode.
Below is a function that decrypts AES-encrypted cipher text into plain text.
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
/* AES Decrypt Process */
int decrypt_block(unsigned char* plainText, unsigned char* cipherText, unsigned int cipherTextLen, unsigned char* key)
{
EVP_CIPHER_CTX ctx;
unsigned long err=0;
int toLen=0, outLen=0;
int ret=0;
ERR_load_crypto_strings();
EVP_CIPHER_CTX_init(&ctx);
if (EVP_DecryptInit(&ctx, EVP_aes_128_ecb(), key, NULL) != 1) {
err = ERR_get_error();
printf("ERR: EVP_DecryptInit() - %s\n", ERR_error_string (err, NULL));
return -1;
}
if (EVP_DecryptUpdate(&ctx, plainText, &toLen, cipherText, cipherTextLen) != 1) {
err = ERR_get_error();
printf("ERR: EVP_DecryptUpdate() - %s\n", ERR_error_string (err, NULL));
return -1;
}
if (EVP_DecryptFinal(&ctx, &plainText[cipherTextLen], &outLen) != 1) {
err = ERR_get_error();
printf("ERR: EVP_DecryptFinal() - %s\n", ERR_error_string (err, NULL));
return -1;
}
EVP_CIPHER_CTX_cleanup(&ctx);
ERR_free_strings();
return toLen+outLen;
}