利用openssl中AES进行加解密

利用openssl中AES进行加解密

#include <string>
#include <iostream>
#include <assert.h>
#include <openssl/aes.h>

using namespace std;

string EncryptAES(const string& strKey, const string& strData)
{
    AES_KEY aes_key;
    if (AES_set_encrypt_key((const unsigned char*)strKey.c_str(), strKey.length() * 8, &aes_key) < 0)
    {
        assert(false);
        return "";
    }
    string strRet;
    string strDataBak = strData;
    unsigned int data_length = strDataBak.length();
    int padding = 0;
    if (strDataBak.length() % AES_BLOCK_SIZE > 0)
    {
        padding = AES_BLOCK_SIZE - strDataBak.length() % AES_BLOCK_SIZE;
    }
    data_length += padding;
    while (padding > 0)
    {
        strDataBak += '\0';
        padding--;
    }
    for (unsigned int i = 0; i < data_length / AES_BLOCK_SIZE; i++)
    {
        string strBlock = strDataBak.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);
        unsigned char out[AES_BLOCK_SIZE];
        ::memset(out, 0, AES_BLOCK_SIZE);
        AES_encrypt((const unsigned char*)strBlock.c_str(), out, &aes_key);
        strRet += string((const char*)out, AES_BLOCK_SIZE);
    }
    return strRet;
}


string DecryptAES(const string& strKey, const string& strDecryptedData)
{
    AES_KEY aes_key;
    if (AES_set_decrypt_key((const unsigned char*)strKey.c_str(), strKey.length() * 8, &aes_key) < 0)
    {
        assert(false);
        return "";
    }
    std::string strRet;
    for (unsigned int i = 0; i < strDecryptedData.length() / AES_BLOCK_SIZE; i++)
    {
        std::string strBlock = strDecryptedData.substr(i*AES_BLOCK_SIZE, AES_BLOCK_SIZE);
        unsigned char out[AES_BLOCK_SIZE];
        ::memset(out, 0, AES_BLOCK_SIZE);
        AES_decrypt((const unsigned char*)strBlock.c_str(), out, &aes_key);
        strRet += std::string((const char*)out, AES_BLOCK_SIZE);
    }
    string::size_type pos = strRet.find_last_not_of('\0');
    if (pos != string::npos)
    {
        strRet = strRet.substr(0, pos + 1);
    }
    return strRet;
}

int main(int argc, char *argv[])
{
    string strOriginData = "original_data";
    string strKey = "encrypted_123456";
    string strEncryptedData = EncryptAES(strKey, strOriginData);
    string strDecryptedData = DecryptAES(strKey, strEncryptedData);

    if (strOriginData == strDecryptedData)
    {
        cout << "Encrypt And Decrypt Successful!" << endl;
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值