windows -- openssl sha256加密和AES加密

如果是windows-vs工程需要导入库

第一步
在这里插入图片描述
第二步

在这里插入图片描述

第三步

在这里插入图片描述

SHA256加密
#include "openssl/sha.h"

std::string sha256(const std::string str)
{
    char buf[2];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    std::ostringstream oss;
    for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        // sprintf(buf, "%02x", hash[i]);
        oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(hash[i]);
    }
    return std::move(oss.str());
}
AES 加密
std::string in_str = "待加密数据";
std::string encryptkey = "加密密钥";
unsigned char ivec[AES_BLOCK_SIZE];

AES_KEY aeskey;
AES_set_encrypt_key((unsigned char*)encryptkey.c_str(), 128, &aeskey);

for (int i = 0; i < encrypt_chunk_size; i++)
{//必须要有
    ivec[i] = 0;
}
char* out_data = new char[encrypt_chunk_size + 1];
for (int start = 0; start < length;) {
    if (length - start < encrypt_chunk_size) {
        // printf("%s\r\n", in_str.substr(start, length - start).c_str());
        fout.write(in_str.substr(start, length - start).c_str(), (length - start));
        break;
    }
    // printf("%s\r\n", in_str.substr(start, encrypt_chunk_size).c_str());
    AES_encrypt((const unsigned char*)in_str.substr(start, encrypt_chunk_size).c_str()
        , (unsigned char*)out_data, &aeskey);
    AES_cbc_encrypt((unsigned char*)in_str.substr(start, encrypt_chunk_size).c_str()
        , (unsigned char*)out_data, encrypt_chunk_size, &aeskey, ivec, AES_ENCRYPT);
    fout.write(out_data, encrypt_chunk_size);
    start = start + encrypt_chunk_size;
}
RELESE_ARRAY(out_data);
fout.close();
AES 解密

从文件中读取数据,写入另外一个文件

std::string in_file = "待解密文件";
std::string out_file = "解密输出文件";
int encrypt_chunk_size = 16;
unsigned char ivec[AES_BLOCK_SIZE];

std::ifstream fin(in_file.c_str(), std::ios::binary);
std::ofstream fout(out_file, std::ios::binary);
std::string encryptkey = "加密的密钥";

AES_KEY aeskey;
AES_set_decrypt_key((unsigned char*)encryptkey.c_str(), 128, &aeskey);

char* in_data = new char[encrypt_chunk_size + 1];
char* out_data = new char[encrypt_chunk_size + 1];
while (!fin.eof()) {
    fin.read(in_data, encrypt_chunk_size);
    if (fin.gcount() < encrypt_chunk_size) {
        fout.write(in_data, fin.gcount());
    }
    else {
        AES_cbc_encrypt((unsigned char*)in_data, (unsigned char*)out_data, encrypt_chunk_size, &aeskey, ivec, AES_DECRYPT);
        // std::cout << "out_data:" << out_data << std::endl;
        fout.write(out_data, fin.gcount());
    }
}
RELESE_ARRAY(in_data);
RELESE_ARRAY(out_data);
fout.close();
fin.close();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值