java中Base64编码与解码
来源:互联网 发布:tensorflow 视频教程 编辑:程序博客网 时间:2024/05/17 04:07
一、Base64简介
Base64是一种编码与解码方式,用于将二进制数据编码为64个可打印字符,或者相反操作。
这64个可打印字符包括:A-Z,a-z,0-9,+,/,它们的编码分别从0到63。
Base64内部实现是:将二进制流以6位分组,然后每个分组高位补2个0(计算机是8位存数),
这样每个组值就是在64以内,然后转为对应的编码。
二、实例
1、实现方式一,借助jdk自身的BASE64Encoder和BASE64Decoder
public class Base64Main { public static void main(String[] args) throws Exception { String source = "study hard and make progress everyday"; System.out.println("source : "+ source); String result = base64Encode(source.getBytes("utf8")); //编码 System.out.println("encode result : " + result); String rawSource = new String(base64Decode(result),"utf8"); //解码 System.out.println("decode result : "+ rawSource); } //编码 static String base64Encode(byte[] source) { BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(source); } //解码 static byte[] base64Decode(String source){ try { BASE64Decoder decoder = new BASE64Decoder(); return decoder.decodeBuffer(source); } catch (IOException e) { } return null; }}运行结果:
source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday
2、实现方式二,借助commons-codec包
添加maven依赖:
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version></dependency>代码:
public class Base64FromCommonsMain { public static void main(String[] args) throws Exception { String source = "study hard and make progress everyday"; System.out.println("source : "+ source); String result = Base64.encodeBase64String(source.getBytes("utf8")); //编码 System.out.println("encode result : " + result); String rawSource = new String(Base64.decodeBase64(result),"utf8"); //解码 System.out.println("decode result : "+ rawSource); }}运行结果:
source : study hard and make progress everyday
encode result : c3R1ZHkgaGFyZCBhbmQgbWFrZSBwcm9ncmVzcyBldmVyeWRheQ==
decode result : study hard and make progress everyday
阅读全文
0 0
- java中Base64编码与解码
- java中BASE64与urlUncode的编码与解码
- JS中Base64的编码与解码
- mysql中Base64编码与解码
- Base64编码与解码的java实现
- java安全技术-Base64编码与解码
- Base64编码与解码
- BASE64编码与解码
- BASE64编码与解码
- Base64编码与解码
- base64编码与解码
- base64编码与解码
- Base64 编码与解码
- Base64编码与解码
- Base64编码与解码
- Base64编码与解码
- base64编码与解码
- BASE64编码与解码
- jsp 动作标签
- popwindow的显示层面
- 代理ARP和RARP
- 卡特兰数
- 回车和换行
- java中Base64编码与解码
- UDP协议
- 工作总结32 xfire-servlet.xml项目启动加载时报cvc-elt.1:找不到元素“beans”的声明
- ctf bugku wirteup 入门题目,社工帝?
- 写作建议
- Internet路由之路由表查找算法概述
- StretchBlt()用法详解
- IntelliJ IDEA教程
- 脚本、shell、shell脚本、bash的个人理解