HmacEncoder.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.uas.sso.util.encry;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.Mac;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.security.InvalidKeyException;
  7. import java.security.Key;
  8. import java.security.NoSuchAlgorithmException;
  9. /**
  10. * Hash-based message authentication code,利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出
  11. *
  12. * @author yingp
  13. *
  14. */
  15. public class HmacEncoder {
  16. private final String algorithm;
  17. public HmacEncoder(String algorithm) {
  18. this.algorithm = algorithm;
  19. }
  20. /**
  21. * 根据给定密钥生成算法创建密钥
  22. *
  23. * @param algorithm
  24. * 密钥算法
  25. * @return 密钥
  26. * @throws RuntimeException
  27. * 当 {@link NoSuchAlgorithmException} 发生时
  28. */
  29. public byte[] getKey() {
  30. // 初始化KeyGenerator
  31. KeyGenerator keyGenerator = null;
  32. try {
  33. keyGenerator = KeyGenerator.getInstance(algorithm);
  34. } catch (NoSuchAlgorithmException e) {
  35. throw new RuntimeException(e.getMessage());
  36. }
  37. // 产生密钥
  38. SecretKey secretKey = keyGenerator.generateKey();
  39. // 获得密钥
  40. return secretKey.getEncoded();
  41. }
  42. /**
  43. * 转换密钥
  44. *
  45. * @param key
  46. * 二进制密钥
  47. * @param algorithm
  48. * 密钥算法
  49. * @return 密钥
  50. */
  51. private static Key toKey(byte[] key, String algorithm) {
  52. // 生成密钥
  53. return new SecretKeySpec(key, algorithm);
  54. }
  55. /**
  56. * 使用指定消息摘要算法计算消息摘要
  57. *
  58. * @param data
  59. * 做消息摘要的数据
  60. * @param key
  61. * 密钥
  62. * @return 消息摘要(长度为16的字节数组)
  63. */
  64. public byte[] encode(byte[] data, Key key) {
  65. Mac mac = null;
  66. try {
  67. mac = Mac.getInstance(algorithm);
  68. mac.init(key);
  69. } catch (NoSuchAlgorithmException e) {
  70. e.printStackTrace();
  71. return new byte[0];
  72. } catch (InvalidKeyException e) {
  73. e.printStackTrace();
  74. return new byte[0];
  75. }
  76. return mac.doFinal(data);
  77. }
  78. /**
  79. * 使用指定消息摘要算法计算消息摘要
  80. *
  81. * @param data
  82. * 做消息摘要的数据
  83. * @param key
  84. * 密钥
  85. * @return 消息摘要(长度为16的字节数组)
  86. */
  87. public byte[] encode(byte[] data, byte[] key) {
  88. return encode(data, toKey(key, algorithm));
  89. }
  90. }