日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

hmac-sha1加密算法C源码示例

發布時間:2023/11/27 生活经验 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hmac-sha1加密算法C源码示例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HMAC: Hash-based Message Authentication Code,即基于Hash的消息鑒別碼 

在各大開放平臺大行其道的互聯網開發潮流中,調用各平臺的API接口過程中,無一例外都會用到計算簽名值(sig值)。而在各種計算簽名的方法中,經常被采用的就是HMAC-SHA1,現對HMAC-SHA1做一個簡單的介紹:

HMAC,散列消息鑒別碼,基于密鑰的Hash算法認證協議。

實現原理為:

利用已經公開的Hash函數和私有的密鑰,來生成固定長度的消息鑒別碼;

SHA1、MD5等Hash算法是比較常用的不可逆Hash簽名計算方法;

BASE64,將任意序列的8字節字符轉換為人眼無法直接識別的符號編碼的一種方法;

相關依賴庫是openssl,安裝方法如下:apt-get install openssl ? //Ubuntu 14.04yum -y install openssl-devel ? ?//centos?

下面提供兩個源碼示例:

例子一:

//gcc -g hmac_sha1_demo3.c -o hmac_sha1_demo3 -lcrypto -std=c99#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>int main()
{// The key to hashchar key[] = "012345678";// The data that we're going to hash using HMACchar data[] = "hello world";unsigned char digest[EVP_MAX_MD_SIZE] = {'\0'};unsigned int digest_len = 0;// Using sha1 hash engine here.// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etcHMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), digest, &digest_len);printf("%s, len %u\n", digest, digest_len);// Be careful of the length of string with the choosen hash engine. SHA1 produces a 20-byte hash value which rendered as 40 characters.// Change the length accordingly with your choosen hash enginechar mdString[41] = {'\0'};for(int i = 0; i < 20; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("HMAC digest: %s\n", mdString);return 0;
}

例子二:

//gcc -g hmac_sha1_demo2.c -o hmac_sha1_demo2 -lcrypto --std=c99#include <stdio.h>
#include <string.h>
#include <openssl/hmac.h>int main() {// The secret key for hashingconst char key[] = "012345678";// The data that we're going to hashchar data[] = "hello world";// Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters.// Change the length accordingly with your choosen hash engine.unsigned char* result;unsigned int len = 20;result = (unsigned char*)malloc(sizeof(char) * len);HMAC_CTX ctx;HMAC_CTX_init(&ctx);// Using sha1 hash engine here.// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etcHMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));HMAC_Final(&ctx, result, &len);HMAC_CTX_cleanup(&ctx);printf("HMAC digest: ");for (int i = 0; i != len; i++)printf("%02x", (unsigned int)result[i]);printf("\n");free(result);return 0;
}
運行截圖:


參考文獻:

[1].http://www.askyb.com/cpp/openssl-hmac-hasing-example-in-cpp/?

總結

以上是生活随笔為你收集整理的hmac-sha1加密算法C源码示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。