Apache Codec 通过 org.apache.commons.codec.binary.Base64 类提供 RFC2045 定义的 base64 编码和解码。
这个类实现了6.8节。Base64 内容传输-编码从 RFC2045 多用途互联网邮件扩展 (MIME) 第一部分:Freed 和 Borenstein 编写的 Internet 邮件正文格式。
以使用各种构造函数以下列方式对该类进行参数化:
a、是否使用“base32hex”变量而不是默认的“base32”
b、行长:默认为76。在编码的数据中,不是8倍的行长度实际上仍然是8的倍数。
c、行分隔符:默认为 CRLF (“\r\n”)
URL安全参数仅应用于编码操作。解码可以无缝地处理两种模式。
(1)对“hello world”字符串进行 BASE64 加密。代码如下:
package com.huangx.codec.base64;
import org.apache.commons.codec.binary.Base64;
public class Base64Demo {
public static void main(String[] args) {
Base64 base64 = new Base64();
byte[] bytes = base64.encode("hello world".getBytes());
System.out.println(new String(bytes));
}
}运行程序输出如下:
aGVsbG8gd29ybGQ=(2)使用 Base64 对加密的 Base64 字符串进行解密,代码如下:
package com.huangx.codec.base64;
import org.apache.commons.codec.binary.Base64;
public class Base64Demo2 {
public static void main(String[] args) {
Base64 base64 = new Base64();
byte[] bytes = base64.encode("hello world".getBytes());
String encodeResult = new String(bytes);
System.out.println( encodeResult );
System.out.println( new String(base64.decode(encodeResult)) );
}
}运行程序输出如下:
aGVsbG8gd29ybGQ=
hello world(3)使用带有长度参数的 Base64(int lineLength) 构造方法,对加密的结果按照指定的长度换行。代码如下:
package com.huangx.codec.base64;
import org.apache.commons.codec.binary.Base64;
public class Base64Demo3 {
public static void main(String[] args) {
// 将行长度设置为 10,即 lineLength = 10
Base64 base64 = new Base64(10);
byte[] bytes = base64.encode("administrator".getBytes());
System.out.println( new String(bytes) );
}
}运行程序输出如下:
YWRtaW5p
c3RyYXRv
cg==(4)使用“Base64(int lineLength, byte[] lineSeparator)”参数设置加密结果每行的长度,并且设置每行的分隔符号。代码如下:
package com.huangx.codec.base64;
import org.apache.commons.codec.binary.Base64;
public class Base64Demo4 {
public static void main(String[] args) {
Base64 base64 = new Base64(10, "##".getBytes());
byte[] bytes = base64.encode("administrator".getBytes());
System.out.println( new String(bytes) );
}
}运行程序输出如下:
YWRtaW5p##c3RyYXRv##cg==##(5)Base64 工具类还提供了很多的静态工具方法,下面将进行演示:
package com.huangx.codec.base64;
import org.apache.commons.codec.binary.Base64;
public class Base64Demo5 {
public static void main(String[] args) {
System.out.println("加密数据:");
// 加密数据,返回字节数组
System.out.println(new String(Base64.encodeBase64("hello world".getBytes())));
// 加密数据,返回字符串
System.out.println(Base64.encodeBase64String("hello world".getBytes()));
// 使用 Base64 算法的 URL 安全变体对二进制数据进行编码,但不对输出分块。
// URL 安全的变体输出 - 和 _ 而不是 + 和 / 字符。
// 注意:不添加填充物,即 =。
System.out.println(new String(Base64.encodeBase64URLSafe("hello world".getBytes())));
System.out.println(Base64.encodeBase64URLSafeString("hello world".getBytes()));
System.out.println("解密数据:");
String encodeStr = "aGVsbG8gd29ybGQ=";
// 解密数据,接收字符串参数
System.out.println(new String(Base64.decodeBase64(encodeStr)));
// 解密数据,接收字节数组参数
System.out.println(new String(Base64.decodeBase64(encodeStr.getBytes())));
}
}