C# 加密算法HmacSHA256

 

     //加密算法HmacSHA256  
        private static string HmacSHA256(string secret, string signKey)
        {
            string signRet = string.Empty;
            using (HMACSHA256 mac = new HMACSHA256(Encoding.UTF8.GetBytes(signKey)))
            {
                byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(secret));
                signRet = Convert.ToBase64String(hash);
                //signRet = ToHexString(hash); ;
            }
            return signRet;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HmacSha256是一种基于SHA-256(Secure Hash Algorithm 256-bit)算法的消息鉴别码算法。在C语言中,可以使用OpenSSL库来实现HmacSha256加密算法。 首先,我们需要包含OpenSSL库的头文件和链接静态库文件。在C代码中,可以使用以下指令进行包含: #include <openssl/hmac.h> ``` gcc -o example example.c -lcrypto ``` 接下来,我们可以定义一个函数来实现HmacSha256加密算法: ``` #include <stdio.h> #include <string.h> #include <openssl/hmac.h> void hmac_sha256(const unsigned char *key, int key_len, const unsigned char *data, int data_len, unsigned char *digest) { HMAC_CTX *hmac_ctx; unsigned int sha256_len; hmac_ctx = HMAC_CTX_new(); HMAC_Init_ex(hmac_ctx, key, key_len, EVP_sha256(), NULL); HMAC_Update(hmac_ctx, data, data_len); HMAC_Final(hmac_ctx, digest, &sha256_len); HMAC_CTX_free(hmac_ctx); } int main() { unsigned char key[] = "secret_key"; unsigned char data[] = "message"; int key_len = strlen(key); int data_len = strlen(data); unsigned char digest[EVP_MAX_MD_SIZE]; hmac_sha256(key, key_len, data, data_len, digest); printf("HMAC-SHA256 digest: "); for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { printf("%02x", digest[i]); } printf("\n"); return 0; } ``` 在main函数中,我们使用一个密钥key和一个消息data来进行HmacSha256加密,结果存储在digest数组中。输出结果是一个64字节的摘要。 编译并运行这段代码,将会输出HMAC-SHA256摘要结果。 这就是在C语言中实现HmacSha256加密算法的简单示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值