关于OPENSSL的EVP函数的使用

本文公开了如何调用OPENSSL对字符串进行加密和解密,同时展示了对加密数据进行BASE64编码的代码。详细给出了加密和解密函数的实现,以及BASE64编码和解码的代码,并表示代码已经过测试可行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4月份没什么做,就是做了OPENSSL的 加密和解密的应用,现在公开一下如何调用OPENSSL对字符串进行加密和解密,当中也学会了对加密数据进行BASE64编码,现在公开一下代码,在这感谢GITHUB里的好心人

 

//加密例子

int encryptdate(string plaindatas, string & encryptedatas)
{



const unsigned char iv[8] = { '1', '2', '3', '4, '5', '6', '7', '8' };

const unsigned char key[8] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

const unsigned char * in = reinterpret_cast<const unsigned char *> (plaindatas.c_str());

 

int written = 0, temp;
unsigned char * outbuf = new unsigned char[plaindatas.length()+1];
int in_len = plaindatas.length();

EVP_CIPHER_CTX *ctx;
if (!(ctx = EVP_CIPHER_CTX_new()))
{
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_CIPHER_CTX_new failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
return -1;
}

if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_cbc(), NULL, key, iv))
{
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_EncryptInit_ex failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}


EVP_CIPHER_CTX_set_padding(ctx, EVP_PADDING_PKCS7);

if (1 != EVP_EncryptUpdate(ctx, outbuf, &temp, in, in_len))
{
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_EncryptUpdate failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}

written = temp;

if (1 != EVP_EncryptFinal_ex(ctx, outbuf + temp, &temp))
{
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_EncryptFinal_ex failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}

written += temp;

//EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_CTX_cleanup(ctx);

encryptedatas = base64_encode(outbuf, written);
return 0;
}

 

 

//解密


int decryptdate(string encryptdatas, string & decryptdatas)
{


const unsigned char iv[8] =  { '1', '2', '3', '4, '5', '6', '7', '8' };

const unsigned char key[8] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

 

string decordstr = my_base64_decode(encryptdatas);

EVP_CIPHER_CTX * ctx;

int len=0;

int plaintext_len=0;

int ciphertext_len = decordstr.length();
unsigned char * ciphertext = new unsigned char[ciphertext_len]; //这个size 要大于 str.size();
memcpy(ciphertext, &decordstr[0], decordstr.size());

 

unsigned char * plaintext = new unsigned char[ciphertext_len];


/* Create and initialise the context */
if (!(ctx = EVP_CIPHER_CTX_new())) {
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_CIPHER_CTX_new failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);

// EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}

/* Initialise the decryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_cbc(), NULL, key, iv)){
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_DecryptInit_ex failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)){
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_DecryptUpdate failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
plaintext_len = len;

/* Finalise the decryption. Further plaintext bytes may be written at
* this stage.
*/
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)){
string errstr = ERR_error_string(ERR_get_error(), NULL);
errstr = "ERROR: EVP_DecryptFinal_ex failed. OpenSSL error:" + errstr;
write_text_to_log_file(errstr);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}

plaintext_len += len;

plaintext[plaintext_len] = 0;

decryptdatas = (reinterpret_cast<char const *>(plaintext));

/* Clean up */
EVP_CIPHER_CTX_cleanup(ctx);

 


return 0;
}

 

 而base64的代码如下,我测试过可行

 

//编码

#include <iostream>

static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";


static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];

while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;

for (i = 0; (i <4); i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}

if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';

char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];

while ((i++ < 3))
ret += '=';

}

return ret;

}

 

//base64解码

 

#include <cassert>
#include <limits>
#include <stdexcept>
#include <cctype>

static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static const char reverse_table[128] = {
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64,
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64,
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64
};

 

::std::string my_base64_decode(const ::std::string &ascdata)
{
using ::std::string;
string retval;
const string::const_iterator last = ascdata.end();
int bits_collected = 0;
unsigned int accumulator = 0;

for (string::const_iterator i = ascdata.begin(); i != last; ++i) {
const int c = *i;
if (::std::isspace(c) || c == '=') {
// Skip whitespace and padding. Be liberal in what you accept.
continue;
}
if ((c > 127) || (c < 0) || (reverse_table[c] > 63)) {
throw ::std::invalid_argument("This contains characters not legal in a base64 encoded string.");
}
accumulator = (accumulator << 6) | reverse_table[c];
bits_collected += 6;
if (bits_collected >= 8) {
bits_collected -= 8;
retval += static_cast<char>((accumulator >> bits_collected) & 0xffu);
}
}
return retval;
}

转载于:https://www.cnblogs.com/redmondfan/p/10944078.html

0、此例程调试环境 运行uname -a的结果如下: Linux freescale 3.0.35-2666-gbdde708-g6f31253 #1 SMP PREEMPT Thu Nov 30 15:45:33 CST 2017 armv7l GNU/Linux 简称2017 armv7l GNU/Linux 1、openssl 直接处理AES的API 在openssl/aes.h定义。是基本的AES库函数接口,可以直接调用,但是那个接口是没有填充的。而如果要与Java通信,必须要有填充模式。所以看第2条。 2、利用openssl EVP接口 在openssl/evp.h中定义。在这个接口中提供的AES是默认是pkcs5padding方式填充方案。 3、注意openssl新老版本的区别 看如下这段 One of the primary differences between master (OpenSSL 1.1.0) and the 1.0.2 version is that many types have been made opaque, i.e. applications are no longer allowed to look inside the internals of the structures. The biggest impact on applications is that: 1)You cannot instantiate these structures directly on the stack. So instead of: EVP_CIPHER_CTX ctx; you must instead do: EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); .... EVP_CIPHER_CTX_free(ctx); 2)You must only use the provided accessor functions to access the internals of the structure. 4、注意加密的内容是数据不限制是否为字符串 openssl接口加密的是数据,不限制是否为字符串,我看到有些人在加密时使用strlen(),来获取要加密的长度,如果是对字符串加密的话没有问题,如果不是字符串的话,用它获取的长度是到第一个0处,因为这个函数获取的是字符串长度,字符串是以零为终止的。 5、在调用EVP_EncryptFinal_ex时不要画蛇添足 正常加解密处理过程,引用网友的代码如下,经测试正确。 int kk_encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) { EVP_CIPHER_CTX *ctx; int len; int ciphertext_len; ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv); //EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); EVP_EncryptUpdate(ctx, ciphertext, &len;, plaintext, plaintext_len); ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len;); ciphertext_len += len; EVP_CIPHER_CTX_free(ctx); return ciphertext_len; } int kk_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) { EVP_CIPHER_CTX *ctx; int len; int plaintext_len; ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv); //EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); EVP_DecryptUpdate(ctx, plaintext, &len;, ciphertext, ciphertext_len); plaintext_len = len; EVP_DecryptFinal_ex(ctx, plaintext + len, &len;); plaintext_len += len; EVP_CIPHER_CTX_free(ctx); return plaintext_len; } 我看到有人提供的代码在加密长度正好是16字节的整数倍时特意不去调用EVP_EncryptFinal_ex,这实在是画蛇添足啊,不论什么情况下,最后一定要调用EVP_EncryptFinal_ex一次,然后结束加密过程。 6、Base64陷阱 如果用到了base64,要注意如下: 1)base64算法是将3个字节变成4个可显示字符。所以在如果数据长度不是3字节对齐时,会补0凑齐。 2)在解密时先要解base64,再解AES。在解base64后,要减掉补上的0。算法就去查看base64后的字符串尾处有几个=号,最多是2个,如果正好要加密的数据是3的倍数,不需要补0,那么base64后的数据尾处就没有=,如果补了1个0,就有一个=号。 算法如下: int encode_str_size = EVP_EncodeBlock(base64, en, el); int length = EVP_DecodeBlock(base64_out, base64, encode_str_size ); //EVP_DecodeBlock内部同样调用EVP_DecodeInit + EVP_DecodeUpdate + Evp_DecodeFinal实现,但是并未处理尾部的'='字符,因此结果字符串长度总是为3的倍数 while(base64[--encode_str_size] == '=') length--; 算法网友提供,测试正确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值