package com.util; import java.nio.charset.StandardCharsets; public class Base64 { final static java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); final static java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); /** * 符串加密 * * @param text * @return */ public static String encode(String text) { // byte[] textByte = text.getBytes(StandardCharsets.UTF_8); // String encodedText = encoder.encodeToString(textByte); // return encodedText; return encoder.encodeToString( text.getBytes( StandardCharsets.UTF_8 ) ); // StandardCharsets.UTF_8 代替了 "UTF-8 } /** * 将加密后的字符串进行解密 * * @param encodedText * @return */ public static String decode(String encodedText) { return new String( decoder.decode( encodedText ), StandardCharsets.UTF_8 ); } // 测试 // public static void main(String[] args) { String url = "jdbc:mysql://118.24.13.38:3308/goods?characterEncoding=utf8&useSSL=false"; String username = "11353268@qq.com.com"; String password = "pass=p@sSW0rd"; // 加密 System.out.println( "==== [加密后] 用户名/密码 =====" ); System.out.println( Base64.encode( url ) ); System.out.println( Base64.encode( username ) ); System.out.println( Base64.encode( password ) ); // 解密 System.out.println( " ==== [解密后] 用户名/密码 =====" ); System.out.println( Base64.decode( Base64.encode( url ) ) ); System.out.println( Base64.decode( Base64.encode( username ) ) ); System.out.println( Base64.decode( Base64.encode( password ) ) ); System.out.println( "===============" + Base64.decode( Base64.encode( password ) ) ); } }
测试结果: