C C++使用openssl进行摘要和加密解密(md5, sha256, des, rsa)_c++ openssl sha256

工程配置

windows

  1. 编译openssl库,得到头文件include和链接库lib和dll
  2. 配置包含头文件目录和库目录
  3. 工程中设置链接指定的lib:fenbieshlibssl.lib,libcrypto.lib
  4. 将对应的dll拷贝到exe执行目录:libcrypto-1_1.dll, libssl-1_1.dll

linux

  1. 编译openssl库,得到头文件include和链接库a和so
  2. 配置包含头文件目录和库目录
  3. 工程中设置链接指定的lib:libcrypto.a 后者libcrypto.so

代码

#include   
#include 
#include   
#include   
#include "openssl/md5.h"  
#include "openssl/sha.h"  
#include "openssl/des.h"  
#include "openssl/rsa.h"  
#include "openssl/pem.h"  

// ---- md5摘要哈希 ---- //  
void md5(const std::string &srcStr, std::string &encodedStr, std::string &encodedHexStr)
{
	// 调用md5哈希  
	unsigned char mdStr[33] = {0};
	MD5((const unsigned char *)srcStr.c_str(), srcStr.length(), mdStr);

	// 哈希后的字符串  
	encodedStr = std::string((const char *)mdStr);
	// 哈希后的十六进制串 32字节  
	char buf[65] = {0};
	char tmp[3] = {0};
	for (int i = 0; i < 32; i++)
	{
		sprintf(tmp, "%02x", mdStr[i]);
		strcat(buf, tmp);
	}
	buf[32] = '\0'; // 后面都是0,从32字节截断  
	encodedHexStr = std::string(buf);
}

// ---- sha256摘要哈希 ---- //  
void sha256(const std::string &srcStr, std::string &encodedStr, std::string &encodedHexStr)
{
	// 调用sha256哈希  
	unsigned char mdStr[33] = {0};
	SHA256((const unsigned char *)srcStr.c_str(), srcStr.length(), mdStr);

	// 哈希后的字符串  
	encodedStr = std::string((const char *)mdStr);
	// 哈希后的十六进制串 32字节  
	char buf[65] = {0};
	char tmp[3] = {0};
	for (int i = 0; i < 32; i++)
	{
		sprintf(tmp, "%02x", mdStr[i]);
		strcat(buf, tmp);
	}
	buf[32] = '\0'; // 后面都是0,从32字节截断  
	encodedHexStr = std::string(buf);
}

// ---- des对称加解密 ---- //  
// 加密 ecb模式  
std::string des_encrypt(const std::string &clearText, const std::string &key)
{
	std::string cipherText; // 密文  

	DES_cblock keyEncrypt;
	memset(keyEncrypt, 0, 8);

	// 构造补

你可能感兴趣的:(c语言,c++,开发语言)