SignUtil.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package com.uas.eis.utils;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.IvParameterSpec;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.security.MessageDigest;
  7. public class SignUtil {
  8. public static String decryptAes(String encryptedContent, String aesKey) throws Exception {
  9. byte[] ciphertextBytes = Base64.decodeBase64(encryptedContent); // decode加密密文结果
  10. byte[] aesKeyBytes = Base64.decodeBase64(aesKey); // decode 秘钥
  11. SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");
  12. IvParameterSpec iv = new IvParameterSpec(aesKeyBytes, 0, 16); // 初始化向量
  13. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 加密模式为CBC
  14. cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
  15. byte[] plaintextBytes = cipher.doFinal(ciphertextBytes);
  16. String result = new String(plaintextBytes, "utf-8"); // 解密结果
  17. return result;
  18. }
  19. public static String encryptAes(String result, String aesKey) throws Exception {
  20. byte[] plaintextBytes = result.getBytes();
  21. byte[] aesKeyBytes = Base64.decodeBase64(aesKey);
  22. SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");
  23. IvParameterSpec iv = new IvParameterSpec(aesKeyBytes, 0, 16);
  24. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  25. cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
  26. byte[] encryptedBytes = cipher.doFinal(plaintextBytes);
  27. String encryptedResult = Base64.encodeBase64String(encryptedBytes); //转换为64位编码
  28. return encryptedResult;
  29. }
  30. public static String shaEncode(String text) throws Exception {
  31. MessageDigest shaDigest = MessageDigest.getInstance("SHA");
  32. byte[] byteArray = text.getBytes("UTF-8");
  33. byte[] md5Bytes = shaDigest.digest(byteArray);
  34. StringBuffer hexValue = new StringBuffer();
  35. for (int i = 0; i < md5Bytes.length; i++) {
  36. int val = ((int) md5Bytes[i]) & 0xff;
  37. if (val < 16) {
  38. hexValue.append("0");
  39. }
  40. hexValue.append(Integer.toHexString(val));
  41. }
  42. return hexValue.toString();
  43. }
  44. }