代码
#include <cstring>
#include <memory>#include <openssl/aes.h>
#include <openssl/md5.h>namespace hsm{namespace mgmt{void get_md5_digest(const std::string &data,uint8_t result[16]){MD5_CTX md5_ctx{};MD5_Init(&md5_ctx);MD5_Update(&md5_ctx,data.c_str(),data.length());MD5_Final(result,&md5_ctx);}
/*** @brief generate a valid aes key from input password** @note AES only support keys with length 128/192/256bits* @note this implementation use md5 as a method to fix the password*/std::unique_ptr<AES_KEY> get_aes_key(const std::string &password,int flag){auto aes_key = std::make_unique<AES_KEY>();uint8_t data[16]{};get_md5_digest(password,data);if (flag == AES_ENCRYPT){AES_set_encrypt_key(data,sizeof(data)*8,aes_key.get());} else if (flag == AES_DECRYPT){AES_set_decrypt_key(data,sizeof(data)*8,aes_key.get());}return aes_key;}std::string aes_cbc_encrypt_to_string(const std::string &data,const std::string &password){unsigned char buffer[AES_BLOCK_SIZE] = {0};auto aes_key = get_aes_key(password,AES_ENCRYPT);std::string result(data.length(),'0');auto input_offset = reinterpret_cast<const uint8_t *>(data.c_str());auto output_offset = reinterpret_cast<uint8_t *>(&result[0]);//encrypt blocksfor (size_t i = 0;i < 16;i++){buffer[i] += 1;}AES_cbc_encrypt(input_offset,output_offset,data.length(),aes_key.get(),buffer,AES_ENCRYPT);return result;}std::string aes_cbc_decrypt_from_string(const std::string &enc_data,const std::string &password){unsigned char buffer[AES_BLOCK_SIZE] = {0};auto aes_key = get_aes_key(password,AES_DECRYPT);std::string result(enc_data.length(),'0');auto input_offset = reinterpret_cast<const uint8_t *>(enc_data.c_str());auto output_offset = reinterpret_cast<uint8_t *>(&result[0]);for (size_t i = 0;i < 16;i++){buffer[i] += 1;}AES_cbc_encrypt(input_offset,output_offset,enc_data.length(),aes_key.get(),buffer,AES_DECRYPT);return result;}}//namespace mgmt
}//namespace hsm
注意事项
- 在CBC中,每个明文块要先与前一个密文块进行异或后再加密,每个密文块都依赖于前面的所有明文块。
- 那么问题又来了:第一个明文块怎么办?这个时候就要用到IV了。因此上面代码for循环是为了给第一块明文初始化,使其数据保持一致
- 在CBC中,IV先与第一个明文块进行异或,得到第一个明文块,然后再进行后续的加密。详见下图:
参考链接
- Openssl Aes加解密使用示例
- AES加密(3):AES加密模式与填充
- OpenSSL中AES加密的用法
- OpenSSL参考文档
- openssl使用指南