package cn.ljs.util; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Base64; import java.util.Base64.Decoder; import java.util.Base64.Encoder; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Miracle Luna * @version 1.0 * @date 2019/7/3 18:55 */ public class Base64Util { public static void main(String[] args) throws UnsupportedEncodingException { String sotcbb = "sotcbb_";//自定义盐值 Map<String, Object> map = new HashMap<String, Object>(); map.put("id", "1"); map.put("name", "地铁"); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("id", "2"); map1.put("name", "公交车"); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); list.add(map); list.add(map1); for (int i = 0; i < list.size(); i++) { map = list.get(i); String aString = null; try { aString = Base64Util.encoder(sotcbb+(String) map.get("name")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("编码:"+aString); map.put("name", aString); } System.out.println("编码:"+list); for (int i = 0; i < list.size(); i++) { map = list.get(i); String aString = null; try { aString = Base64Util.decoder((String) map.get("name")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("解码:"+aString.split("_")[1]); map.put("name", aString.split("_")[1]); } System.out.println("解码:"+list); String string = "李某"; String eString = "5p2O5p+Q"; System.out.println(string+"<---编码--->"+Base64Util.encoder(string)); System.out.println(eString+"<---解码--->"+Base64Util.decoder(eString)); } /** * base64编码 * @param string * @return * @throws UnsupportedEncodingException */ public static String encoder(String string) throws UnsupportedEncodingException { Encoder encoder = Base64.getEncoder(); byte[] textByte = string.getBytes("UTF-8"); return encoder.encodeToString(textByte); } /** * base64解码 * @param string * @return * @throws UnsupportedEncodingException */ public static String decoder(String string) throws UnsupportedEncodingException { Decoder decoder = Base64.getDecoder(); return new String(decoder.decode(string), "UTF-8"); } }
记录一下平常遇到的问题及新的知识,方便以后查看