JDK1.8版本以来,新增了加密的API,而加密的算法有很多种,有的能加密后再解密,还有的只能单向加密(MD5),而这里要用到的是加密后还能反解密的Base64。

Base64的加密解密核心方法

public byte[] encode(byte[] src) ;—加密
public byte[] decode(byte[] src) ;—解密
因为Base64的加密API是公开的,所以如果直接对其加密是不安全的,因此在实际开发的时候,通常都是混入盐值(掺杂一些字符串之类的),然后反复加密几次,甚至是采用两种乃至更多的加密方式来保证数据的安全。

  1. package chenfu.util;
  2. import java.util.Base64;
  3. /**
  4. * @Author: romantic_ke@163.com
  5. * @Description:
  6. * @Date: 2019/3/2 19:08
  7. */
  8. public class StringUtil {
  9. // 盐值
  10. private final static String SALT = "{salt}";
  11. // 加密次数
  12. private final static Integer TIMES = 3;
  13. /**
  14. * 加密方法
  15. *
  16. * @param pwd
  17. * @return
  18. */
  19. public static String encode(String pwd) {
  20. pwd += SALT;
  21. byte p[] = pwd.getBytes();
  22. for (int i = 0; i < TIMES; i++) {
  23. p = Base64.getEncoder().encode(p);
  24. }
  25. return new String(p);
  26. }
  27. /**
  28. * 解密方法
  29. *
  30. * @param pwd
  31. * @return
  32. */
  33. public static String decode(String pwd) {
  34. byte[] bytes = pwd.getBytes();
  35. for (int i = 0; i < TIMES; i++) {
  36. bytes = Base64.getDecoder().decode(bytes);
  37. }
  38. return new String(bytes).replaceAll("\\{\\w+\\}", "");
  39. }
  40. public static void main(String[] args) {
  41. String string = "臣服Romantic";
  42. String encode = encode(string);
  43. System.out.println(encode);
  44. String decode = decode(encode);
  45. System.out.println(decode);
  46. }
  47. }