AesUtil.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.edufound.mobile.util;
  2. import org.bouncycastle.util.encoders.Base64;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.spec.SecretKeySpec;
  5. public class AesUtil {
  6. static final String sKey = "GfqqwfctR8gdNGUS";
  7. // 解密
  8. public static String Decrypt(String sSrc) throws Exception {
  9. try {
  10. // 判断Key是否正确
  11. if (sKey == null) {
  12. System.out.print("Key为空null");
  13. return null;
  14. }
  15. // 判断Key是否为16位
  16. if (sKey.length() != 16) {
  17. System.out.print("Key长度不是16位");
  18. return null;
  19. }
  20. byte[] raw = sKey.getBytes("utf-8");
  21. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  22. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
  23. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  24. //先用base64转码
  25. //byte[] encrypted1 = new Base64().decode(sSrc);
  26. byte[] encrypted1 = Base64.decode(sSrc);
  27. try {
  28. byte[] original = cipher.doFinal(encrypted1);
  29. String originalString = new String(original, "utf-8");
  30. return originalString;
  31. } catch (Exception e) {
  32. System.out.println(e.toString());
  33. return null;
  34. }
  35. } catch (Exception ex) {
  36. System.out.println(ex.toString());
  37. return null;
  38. }
  39. }
  40. //加密
  41. public static String Encrypt(String sSrc) throws Exception {
  42. if (sKey == null) {
  43. System.out.print("Key为空null");
  44. return null;
  45. }
  46. // 判断Key是否为16位
  47. if (sKey.length() != 16) {
  48. System.out.print("Key长度不是16位");
  49. return null;
  50. }
  51. byte[] raw = sKey.getBytes("utf-8");
  52. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  53. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
  54. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  55. byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
  56. //此处使用BASE64做转码功能,同时能起到2次加密的作用。
  57. //return new Base64().encodeToString(encrypted);
  58. return new String(Base64.encode(encrypted));
  59. }
  60. }