openssl库的简单使用和介绍与哈希算法

什么是密钥 ?

密钥根据加密密钥和解密密钥是否相同而分为两种类型:
对称的和非对称的

对称的密钥:加密、解密都是用这个密钥

非对称密钥:该密钥是成对出现的,由 公钥和私钥 两部分组成的,本文将要介绍的 RSA 密钥属于非对称密钥
简单的说, 使用私钥加密的对象,使用公钥可以将其进行解密
反之,        使用公钥加密的对象,使用私钥可以将其进行解密
私钥只有生成密钥对的用户才能拥有

1. 哈希

特点:

  • 不可逆
  • 抗碰撞性强
    • 不同的数据拥有不同的哈希值, 相同的数据哈希值是相同的
  • 原始数据有细微的变化, 哈希值的变化是非常大的
  • 通过哈希函数将原始数据进行运算, 得到的哈希值长度是固定的
  • 原始的哈希值是一个定长的二进制字符串

哈希算法:

  • md5
    • 散列值: 16byte
  • sha1
    • 散列值: 20byte
  • sha224
    • 散列值: 28byte
  • sha256
    • 散列值: 32byte
  • sha384
    • 散列值: 48byte
  • sha512
    • 散列值: 64byte

以上说的散列值长度是二进制数据长度, 一般散列值使用 16 进制格式的数字串表示的, 看到的字符串长度是原来的2倍长.

使用的动态库: libcrypto.so

测试代码

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>


void getMD5(const char* str, char* result)
{
	MD5_CTX ctx;
	// 初始化
	MD5_Init(&ctx);
	// 添加数据
	MD5_Update(&ctx, str, strlen(str));
	// 计算结果
	unsigned char md[16] = { 0 };
	MD5_Final(md, &ctx);
	for (int i = 0; i < 16; ++i)
	{
		sprintf(&result[i * 2], "%02x", md[i]);
	}
}

int main()
{	
	char result[33] = { 0 };
	getMD5("hello, md5", result);
	printf("md5 value: %s\n", result);	
	system("pause");
	return 0;
}

测试代码二

#include <iostream>
#include <openssl/sha.h>
#include <string.h>
#include <stdio.h>

using namespace std;

void shalTest()
{
    // 1. 初始化
    SHA_CTX ctx;
    SHA1_Init(&ctx);
    // 2. 添加数据
    SHA1_Update(&ctx,"hello",strlen("hello"));
    SHA1_Update(&ctx,"world",strlen("world"));
    // 3. 哈希计算
    unsigned char* md = new unsigned char[SHA_DIGEST_LENGTH];
    char* res = new char[SHA_DIGEST_LENGTH*2+1];
    SHA1_Final(md,&ctx);
    for (int i=0;i<SHA_DIGEST_LENGTH;++i)                                                             
    {   
     sprintf(&res[i*2],"%02x",md[i]);
    }   
    cout<< "SHA1: "<<res<<endl;

}

int main()
{
    shalTest();
    return 0;
}

posted on 2021-05-26 11:42  lodger47  阅读(451)  评论(0)    收藏  举报

导航