java 用Java生成HMAC MD5 / SHA1 / SHA256等

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 用Java生成HMAC MD5 / SHA1 / SHA256等相关的知识,希望对你有一定的参考价值。

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HMAC {

  public static void main(String[] args) throws Exception {
    System.out.println(hmacDigest("The quick brown fox jumps over the lazy dog", "key", "HmacSHA1"));
  }

  public static String hmacDigest(String msg, String keyString, String algo) {
    String digest = null;
    try {
      SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
      Mac mac = Mac.getInstance(algo);
      mac.init(key);

      byte[] bytes = mac.doFinal(msg.getBytes("ASCII"));

      StringBuffer hash = new StringBuffer();
      for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
          hash.append('0');
        }
        hash.append(hex);
      }
      digest = hash.toString();
    } catch (UnsupportedEncodingException e) {
    } catch (InvalidKeyException e) {
    } catch (NoSuchAlgorithmException e) {
    }
    return digest;
  }
}

以上是关于java 用Java生成HMAC MD5 / SHA1 / SHA256等的主要内容,如果未能解决你的问题,请参考以下文章

Java加密算法---HMAC

nodeJS之crypto模块md5和Hmac加密

基本的java加密算法MD5等等

HMAC加密的消息摘要码

Python学习笔记__12.6章 hmac

hmac md5