使用 HMAC-SHA1 算法

在线HMAC计算器:

https://1024tools.com/hmac

http://tool.oschina.net/encrypt?type=2

shell:

    # 随机字符串5位
    rand=$(date +%s%N | sha1sum | head -c 5)
    echo "rand    :     $rand"
    # 准备签名字符串
    signStr="deviceID=$deviceID&rand=$rand&timestamp=$timestamp&userKey=$userKey"
    echo "signStr    :    $signStr"
    # 签名
    sign=$(echo -n $signStr | openssl sha1 -hmac $secret | awk '{print $2}')
    echo "sign    :     $sign"
    # 拼接签名字符串
    queryStr="$signStr&sign=$sign"
    echo "queryStr:    $queryStr"

c代码1:

 #include <openssl/sha.h>
 unsigned char *SHA1(const unsigned char *d, unsigned long n,unsigned char *md)
-------------------------------------------------------------------------------
    unsigned char sign[EVP_MAX_MD_SIZE] = {'\0'};  
    unsigned int sign_len = 0;  
    char mdString[41] = {'\0'}; 
    int i;
    HMAC(EVP_sha1(), secret, strlen(secret), (const unsigned char *)signStr, strlen(signStr), sign, &sign_len);
    //转成16进制
    for(i = 0; i < 20; i++)    
        sprintf(&mdString[i*2], "%02x", (unsigned int)sign[i]);      
    printf("strlen(%d),HMAC sign: %s\n", strlen(mdString), mdString);  

或者:

c代码2:

 int SHA1_Init(SHA_CTX *c);
 int SHA1_Update(SHA_CTX *c, const void *data, unsigned long len);
 int SHA1_Final(unsigned char *md, SHA_CTX *c);
 --------------------------------------------------------------------------------

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, etc  

  HMAC_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]);  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值