在线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×tamp=$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]);