使用openssl完成aes-cbc模式的数据加解密,输入和输出都是字符串的形式

本文介绍了一种使用AES算法进行数据加密和解密的方法,并提供了基于CBC模式的实现代码。使用MD5生成固定长度的密钥,通过CBC模式进行数据的加密与解密。

代码

#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,siz
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值