jsp:需下载base64.js
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="base64.js"></script> <script type="text/javascript"> var b = new Base64(); var str = b.encode("在"); alert("base64 encode:" + str); //解密 str = b.decode(str); alert("base64 decode:" + str); </script> </head> <body> </body> </html>
java:
import java.io.UnsupportedEncodingException; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class EncodeAndDecode { /** * 加密str * @param str * @return */ public static String getBase64(String str) { byte[] b = null; String s = null; try { b = str.getBytes("utf-8"); for(int i=0;i<b.length;i++){ // b[i]=(byte) (b[i]+1); // System.out.print(b[i]); } //System.out.println(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } // getFromBase64(s); return s; } /** * 加密s * @param str * @return */ public static String getFromBase64(String s) { byte[] b = null; String result = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); for(int i=0;i<b.length;i++){ // b[i]=(byte) (b[i]-1); // System.out.print(b[i]); } result = new String(b, "utf-8"); // System.out.println(); // System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } return result; } public static void main(String[] args) { String base64 = getBase64("在"); String fromBase64 = getFromBase64(base64); System.out.println(base64); System.out.println(fromBase64); } }