sha1加密 C語言例子(使用OpenSSL庫)
阿新 • • 發佈:2019-01-10
包含標頭檔案:#include <openssl/sha.h>
#define SHA_DIGEST_LENGTH 20
sample1:
sample2:#include <stdio.h> #include <string.h> #include <openssl/sha.h> 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; }
#include <stdio.h> #include <string.h> #include <openssl/sha.h> 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