原生的Base64加密方式,比md5简单,但是相对来说不靠谱。
一、代码实现
- 先引入包:import org.apache.commons.codec.binary.Base64;
- 加密的方法:Base64.encodeBase64URLSafeString(result.getBytes())(需要加密的一般是string还是什么的字符串,需要转成Bytes格式才能进行加密,加密的结果是string字符串)
- 解密的方法:Base64.decodeBase64(in)
需要注意的是:解密出来的格式是Bytes类型的,需要转成你需要的数据格式才能使用。
例如我要转成String:
1 2 3 4 5 |
try { result = new String(Base64.decodeBase64(in), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } |
代码实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package onlyfortest; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; public class base64 { public static String dobase64(String in) { System.out.println("加密前:" + in); return Base64.encodeBase64URLSafeString(in.getBytes()); } public static String frombase64(String in) { String result = null; try { result = new String(Base64.decodeBase64(in), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("解密后的bytes,不转换的下场:"+Base64.decodeBase64(in)); return result; } public static void main(String[] args) { System.out.println("加密后:" + dobase64("godlikexie")); System.out.println("解密后:" + frombase64("Z29kbGlrZXhpZQ")); } } |
运行结果:
1 2 3 4 |
加密前:godlikexie 加密后:Z29kbGlrZXhpZQ 解密后的bytes,不转换的下场:[B@1f4acd0 解密后:godlikexie |
二、总结
记录一下。