sha1加密 C语言例子(使用OpenSSL库)

包含头文件:#include

#define SHA_DIGEST_LENGTH 20

sample1:

#include 
#include 
#include 

int main()
{

unsigned char digest[SHA_DIGEST_LENGTH];
char string[] = "hello world";

SHA1((unsigned char*)&string, strlen(string), (unsigned char*)&digest);

char mdString[SHA_DIGEST_LENGTH*2+1];

for(int i = 0; i < SHA_DIGEST_LENGTH; i++)

sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

printf("SHA1 digest: %s\n", mdString);

return 0;

}
sample2:

#include 
#include 
#include 

int main() {

unsigned char digest[SHA_DIGEST_LENGTH];
const char* string = "hello world";

SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, string, strlen(string));
SHA1_Final(digest, &ctx);

char mdString[SHA_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA_DIGEST_LENGTH; i++)

sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);

printf("SHA1 digest: %s\n", mdString);

return 0;

}

       编译链接执行后的结果为:

例子1:

~$ gcc sha1_sample1.cpp -o sample1 -lcrypto
~$ ./sample1
SHA1 digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

例子2:

~$ gcc sha1_sample2.cpp -o sample2 -lcrypto
~$ ./sample2
SHA1 digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

了解更多openssl加密方法请阅读《openssl 多种方法加密例子》。


转自:http://www.ivpeng.com/pblog/sha1-c.html



你可能感兴趣的:(C学习笔记)