CryptUtil.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.malk.rjk.util;
  2. import com.google.common.base.CharMatcher;
  3. import com.google.common.io.BaseEncoding;
  4. import org.apache.commons.codec.binary.Base64;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.spec.IvParameterSpec;
  7. import javax.crypto.spec.SecretKeySpec;
  8. import java.nio.charset.StandardCharsets;
  9. import java.util.Arrays;
  10. public class CryptUtil {
  11. protected byte[] aesKey;
  12. public CryptUtil(String encodingAesKey) {
  13. this.aesKey = BaseEncoding.base64().decode(CharMatcher.whitespace().removeFrom(encodingAesKey));
  14. }
  15. public String decrypt(String encryptedText) {
  16. byte[] original;
  17. try {
  18. // 设置解密模式为AES的CBC模式
  19. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  20. SecretKeySpec keySpec = new SecretKeySpec(this.aesKey, "AES");
  21. IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(this.aesKey, 0, 16));
  22. cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
  23. // 使用BASE64对密文进行解码
  24. byte[] encrypted = Base64.decodeBase64(encryptedText);
  25. // 解密
  26. original = cipher.doFinal(encrypted);
  27. } catch (Exception e) {
  28. return null;
  29. }
  30. String trueContent;
  31. try {
  32. // 去除补位字符
  33. byte[] bytes = decode(original);
  34. // 分离16位随机字符串,网络字节序
  35. byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
  36. int contentLength = bytesNetworkOrder2Number(networkOrder);
  37. trueContent = new String(Arrays.copyOfRange(bytes, 20, 20 + contentLength), StandardCharsets.UTF_8);
  38. } catch (Exception e) {
  39. return null;
  40. }
  41. return trueContent;
  42. }
  43. public static byte[] decode(byte[] decrypted) {
  44. int pad = decrypted[decrypted.length - 1];
  45. if (pad < 1 || pad > 32) {
  46. pad = 0;
  47. }
  48. return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
  49. }
  50. /**
  51. * 4个字节的网络字节序bytes数组还原成一个数字.
  52. */
  53. private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
  54. int sourceNumber = 0;
  55. for (int i = 0; i < 4; i++) {
  56. sourceNumber <<= 8;
  57. sourceNumber |= bytesInNetworkOrder[i] & 0xff;
  58. }
  59. return sourceNumber;
  60. }
  61. }