当前位置:   article > 正文

Java实现哈希加密(HmacSHA1、HmacMD5、HmacSHA256、HmacSHA512)

hmacsha512

示例代码

  1. import javax.crypto.Mac;
  2. import javax.crypto.SecretKey;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.nio.charset.StandardCharsets;
  5. import java.security.InvalidKeyException;
  6. import java.security.NoSuchAlgorithmException;
  7. public class HmacUtil {
  8. //加密算法
  9. public static final String HMAC_SHA1 = "HmacSHA1";
  10. public static final String HMAC_MD5 = "HmacMD5";
  11. public static final String HMAC_SHA256 = "HmacSHA256";
  12. public static final String HMAC_SHA512 = "HmacSHA512";
  13. /**
  14. * 实现Hmac系列的加密算法HmacSHA1、HmacMD5等
  15. *
  16. * @param input 需要加密的输入参数
  17. * @param key 密钥
  18. * @param algorithm 选择加密算法
  19. * @return 加密后的值
  20. **/
  21. public static String encrypt(String input, String key, String algorithm) {
  22. String cipher = "";
  23. try {
  24. byte[] data = key.getBytes(StandardCharsets.UTF_8);
  25. //根据给定的字节数组构造一个密钥,第二个参数指定一个密钥的算法名称,生成HmacSHA1专属密钥
  26. SecretKey secretKey = new SecretKeySpec(data, algorithm);
  27. //生成一个指定Mac算法的Mac对象
  28. Mac mac = Mac.getInstance(algorithm);
  29. //用给定密钥初始化Mac对象
  30. mac.init(secretKey);
  31. byte[] text = input.getBytes(StandardCharsets.UTF_8);
  32. byte[] encryptByte = mac.doFinal(text);
  33. cipher = bytesToHexStr(encryptByte);
  34. } catch (NoSuchAlgorithmException | InvalidKeyException e) {
  35. e.printStackTrace();
  36. }
  37. return cipher;
  38. }
  39. /**
  40. * byte数组转16进制字符串
  41. *
  42. * @param bytes byte数组
  43. * @return hex字符串
  44. */
  45. public static String bytesToHexStr(byte[] bytes) {
  46. StringBuilder hexStr = new StringBuilder();
  47. for (byte b : bytes) {
  48. String hex = Integer.toHexString(b & 0xFF);
  49. if (hex.length() == 1) {
  50. hex = '0' + hex;
  51. }
  52. hexStr.append(hex);
  53. }
  54. return hexStr.toString();
  55. }
  56. }
  57. 测试:
  58. public class Test {
  59. public static void main(String[] args) {
  60. String valMD5 = HmacUtil.encrypt("abc", "123456", HmacUtil.HMAC_MD5);
  61. System.out.println(valMD5);
  62. String valSha1 = HmacUtil.encrypt("abc", "123456", HmacUtil.HMAC_SHA1);
  63. System.out.println(valSha1);
  64. String valSha256 = HmacUtil.encrypt("abc", "123456", HmacUtil.HMAC_SHA256);
  65. System.out.println(valSha256);
  66. String valSha512 = HmacUtil.encrypt("abc", "123456", HmacUtil.HMAC_SHA512);
  67. System.out.println(valSha512);
  68. }
  69. }

在线生成工具:https://tool.oschina.net/encrypt?type=2

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/450000
推荐阅读
相关标签
  

闽ICP备14008679号