當前位置:
首頁 > 知識 > base64加密的解密

base64加密的解密

[java] view plain copy

  1. package

    com.sms.utils;
  2. import

    java.util.HashMap;
  3. import

    java.util.Map;
  4. import

    javax.crypto.Cipher;

  5. import

    javax.crypto.spec.IvParameterSpec;
  6. import

    javax.crypto.spec.SecretKeySpec;
  7. import

    org.apache.commons.codec.binary.Base64;
  8. import

    org.apache.commons.lang3.StringUtils;
  9. import

    com.alibaba.fastjson.JSONObject;
  10. public

    class

    AESUtils {
  11. public

    static

    String key = "123456!@#";
  12. public

    static

    String iv = "1234567812345678";
  13. /**
  14. * 加密
  15. *
  16. * @param data
  17. * @return
  18. */
  19. public

    static

    String encrypt(String data)

    throws

    Exception {
  20. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  21. int

    blockSize = cipher.getBlockSize();
  22. byte

    [] dataBytes = data.getBytes();
  23. int

    plaintextLength = dataBytes.length;
  24. if

    (plaintextLength % blockSize != 0) {
  25. plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
  26. }
  27. byte

    [] plaintext =

    new

    byte

    [plaintextLength];
  28. System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
  29. SecretKeySpec keyspec =

    new

    SecretKeySpec(key.getBytes(), "AES");
  30. IvParameterSpec ivspec =

    new

    IvParameterSpec(iv.getBytes());
  31. cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
  32. byte

    [] encrypted = cipher.doFinal(plaintext);
  33. return

    Base64.encodeBase64String(encrypted);
  34. }
  35. /**
  36. * 解密
  37. *
  38. * @param data
  39. * @return
  40. */
  41. public

    static

    String desEncrypt(String data)

    throws

    Exception {
  42. //base64加密串在http中會把"+"號變為" "
  43. data = StringUtils.replace(data, " ", "+");
  44. // byte[] contentBytes = Base64.decode(data, 0);
  45. byte

    [] contentBytes = Base64.decodeBase64(data);
  46. Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  47. SecretKeySpec keyspec =

    new

    SecretKeySpec(key.getBytes(), "AES");

  48. IvParameterSpec ivspec =

    new

    IvParameterSpec(iv.getBytes());
  49. cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
  50. byte

    [] original = cipher.doFinal(contentBytes);
  51. String originalString =

    new

    String(original);
  52. return

    originalString;
  53. }
  54. public

    static

    void

    main(String[] args)

    throws

    Exception {
  55. Map<String, String> map =

    new

    HashMap<String, String>();
  56. // map.put("username", "admin");
  57. // map.put("password", "123456");
  58. System.out.println(AESUtils.encrypt(JSONUtil.toJson(map)));
  59. }
  60. }

base64加密的解密

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

一套返利網程序源碼
使用RedisTemplate(JDK序列化策略)緩存實體類

TAG:程序員小新人學習 |