Openssl中的sha1和sha256教程

sha说明

sha1库是一种哈希算法,用以生成结果为160bit的数据摘要,即20个字节。
sha256结果为256bit,即32个字节。

摘要的意思是,抽象为任意大小的数据为固定长度数据,结果是由于全部原始数据经过计算得出,逆推则无法计算除准确结果。
摘要的特性:

  • 单向性
  • 映射收敛性
  • 不可篡改性
  • 标准可验证性

由于以上特性,sha哈希被广泛用于软件工程中。例如git软件版本管理工具,就是使用sha1算法计算文件和切片的指纹值。Bitcoin,使用sha256作为数据验证依据。

openssl sha库使用方法:

/*
main.cc
*/
#include <openssl/sha.h>
#include <iostream>
#include <string>

using namespace std;

bool call1(void)
{
        string str="0123456789abcdefghijklmn";

        unsigned char result[32];
        SHA256( (const unsigned char *)str.c_str(), str.length(),  result);

        for (int i = 0; i < 32; i++) {
                printf("%02x ", result[i]);
        }
        cout << endl;	
		return true;
}

bool call2(void)
{
		SHA_CTX ctx;
        string str="0123456789abcdefghijklmn";
		unsigned char result[20];
        
        SHA1_Init(&ctx);
        do {
        	//如果是文件,此处读取文件数据,再使用sha1循环迭代,得到的就是整个文件的sah1值。
        	SHA1_Update(&ctx, str.c_str(), str.length());
        } while (0);
        SHA1_Final(&(result[0]), &ctx);
   
        for (int i = 0; i < 20; i++) {
                //cout << hex << i;
                printf("%02x ", result[i]);
        }
        cout << endl;	
		return true;
}

int main(int argc, char **argv)
{
	call1();
	call2();
	
	return 0;
}
/*
makefile
*/
all:
	g++ main.cc -lcrypto -std=c++11
clean:
	rm -f a.out

测试结果:

[centos@2 ~]$ make
[centos@2 ~]$ ./a.out 
d5 ea 2a a9 22 3a c1 fa 43 cc ec 70 b3 09 62 69 0f cf c6 68 68 57 f9 9a 0c 4b 29 63 cf 8b ee 4b
22 81 9a c0 5a 52 a8 53 8e 3d a2 13 87 dd e1 5d 4e b9 88 53 
[centos@2 ~]$
发布了61 篇原创文章 · 获赞 63 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jacky128256/article/details/102481584