hmacsha256是对称算法吗_HMACSHA256加密

package com.lh.micro.datasource.util;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

public class HMACSHA256 {

/**

* 将加密后的字节数组转换成字符串

*

* @param b 字节数组

* @return 字符串

*/

public static String byteArrayToHexString(byte[] b) {

StringBuilder hs = new StringBuilder();

String stmp;

for (int n = 0; b!=null && n < b.length; n++) {

stmp = Integer.toHexString(b[n] & 0XFF);

if (stmp.length() == 1)

hs.append('0');

hs.append(stmp);

}

return hs.toString().toLowerCase();

}

/**

* sha256_HMAC加密

* @param message 消息

* @param secret 秘钥

* @return 加密后字符串

*/

public static String sha256_HMAC(String message, String secret) {

String hash = "";

try {

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");

SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");

sha256_HMAC.init(secret_key);

byte[] bytes = sha256_HMAC.doFinal(message.getBytes());

hash = byteArrayToHexString(bytes);

} catch (Exception e) {

System.out.println("Error HmacSHA256 ===========" + e.getMessage());

}

return hash;

}

}

  • 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、付费专栏及课程。

余额充值