如果是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();