Java: hash & HMAC

 

复制代码
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Ruzz{
  public static void main(String[] args) throws NoSuchAlgorithmException{
    System.out.println(sha256("ruzz"));
  }

  public static String sha256(String data){
    if(data == null)
      throw new NullPointerException("data is null");

    try{
      MessageDigest messageDigest = MessageDigest.getInstance("sha256");
      byte[] bytes = messageDigest.digest(data.getBytes(StandardCharsets.UTF_8));
      StringBuilder result = new StringBuilder();
      for(byte aByte : bytes){
        String hexString = Integer.toHexString(aByte & 0xFF);
        if(hexString.length() == 1)
          hexString = hexString + '0';
        result.append(hexString);
      }
      return result.toString();
    }catch(NoSuchAlgorithmException e){
      e.printStackTrace();
    }
    return null;
  }

}
复制代码

 

 

复制代码
package io.wig;


import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Ruzz{
  public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException{
    String str="fozy";
    byte[] key = "cozy".getBytes(StandardCharsets.UTF_8);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacMD5");
    Mac mac = Mac.getInstance("HmacMD5");
    mac.init(secretKeySpec);
    mac.update(str.getBytes(StandardCharsets.UTF_8));
    byte[] bytes = mac.doFinal();

    String s = new BigInteger(1, bytes).toString(16);
    System.out.println("s = " + s);
    //
    // String s1 = new BigInteger(bytes).toString(16);
    // System.out.println("s1 = " + s1);

    StringBuilder stringBuilder = new StringBuilder();
    for(byte aByte : bytes){
      String string = Integer.toHexString(aByte & 0xFF);
      if(string.length()==1)
        string='0'+string;
      stringBuilder.append(string);
    }
    System.out.println("stringBuilder = " + stringBuilder);
    HMac hMac = new HMac(HmacAlgorithm.HmacMD5, key);
    System.out.println(hMac.digestHex(str));

  }
}
复制代码

 

 

 

posted @   ascertain  阅读(248)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-04-21 Source Code Pro ( Windows)
2021-04-21 python时间处理
2021-04-21 java jenkins
2021-04-21 promise async await
点击右上角即可分享
微信分享提示