一、使用JRE默认提供的Base64功能
1、需要导入一下的包
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
2、使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public static void main(String[] args) throws Exception { String str = "hello base64"; String ret = ""; ret = new BASE64Encoder().encode(str.getBytes()); System.out.println("加密前:" + str + " 加密后:" + ret); str = "amF2YTEyMzQ1"; try { ret = new String(new BASE64Decoder().decodeBuffer(str)); } catch (IOException e) { e.printStackTrace(); } System.out.println("解密前:" + str + " 解密后:" + ret); } |
二、使用commons-codec包
项目地址:http://commons.apache.org/proper/commons-codec/
maven引用:
1 2 3 4 5 6 |
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> |
使用样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * 解密 */ public static String decodeStr(String pwd) { Base64 base64 = new Base64(); byte[] debytes = base64.decodeBase64(new String(pwd).getBytes()); return new String(debytes); } /** * 加密 */ public static String encodeStr(String pwd) { Base64 base64 = new Base64(); byte[] enbytes = base64.encodeBase64Chunked(pwd.getBytes()); return new String(enbytes); } |
文章评论