EncryptUtil.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.ruoyi.common.utils;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Mac;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.io.UnsupportedEncodingException;
  6. import java.security.InvalidKeyException;
  7. import java.security.MessageDigest;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.SignatureException;
  10. public class EncryptUtil {
  11. /**
  12. * 加密数字签名(基于HMACSHA1算法)
  13. *
  14. * @param encryptText
  15. * @param encryptKey
  16. * @return
  17. * @throws SignatureException
  18. */
  19. public static String HmacSHA1Encrypt(String encryptText, String encryptKey) throws SignatureException {
  20. byte[] rawHmac = null;
  21. try {
  22. byte[] data = encryptKey.getBytes("UTF-8");
  23. SecretKeySpec secretKey = new SecretKeySpec(data, "HmacSHA1");
  24. Mac mac = Mac.getInstance("HmacSHA1");
  25. mac.init(secretKey);
  26. byte[] text = encryptText.getBytes("UTF-8");
  27. rawHmac = mac.doFinal(text);
  28. } catch (InvalidKeyException e) {
  29. throw new SignatureException("InvalidKeyException:" + e.getMessage());
  30. } catch (NoSuchAlgorithmException e) {
  31. throw new SignatureException("NoSuchAlgorithmException:" + e.getMessage());
  32. } catch (UnsupportedEncodingException e) {
  33. throw new SignatureException("UnsupportedEncodingException:" + e.getMessage());
  34. }
  35. String oauth = new String(Base64.encodeBase64(rawHmac));
  36. return oauth;
  37. }
  38. public final static String MD5(String pstr) {
  39. char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  40. try {
  41. byte[] btInput = pstr.getBytes();
  42. MessageDigest mdInst = MessageDigest.getInstance("MD5");
  43. mdInst.update(btInput);
  44. byte[] md = mdInst.digest();
  45. int j = md.length;
  46. char str[] = new char[j * 2];
  47. int k = 0;
  48. for (int i = 0; i < j; i++) { // i = 0
  49. byte byte0 = md[i]; // 95
  50. str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5
  51. str[k++] = md5String[byte0 & 0xf]; // F
  52. }
  53. return new String(str);
  54. } catch (Exception e) {
  55. return null;
  56. }
  57. }
  58. }