Apache Codec 的 org.apache.commons.codec.binary.Base16 提供 base16 编码和解码,Base16 类是线程安全的。
此实现严格遵循 RFC4648,因此与 Base 32 和 Base 64 实现不同,它不忽略无效的字母表字符或空格,也不提供块字符或填充字符。
除了默认的大写字母之外,RFC 4648中指定的惟一附加功能是支持使用小写字母表。
(1)使用 Base16 实现简单的编码和解码,代码如下:
package com.huangx.codec.base16;
import org.apache.commons.codec.binary.Base16;
public class Base16Demo {
public static void main(String[] args) {
// 创建 Base16 对象
Base16 base16 = new Base16();
// 原始字符串
String str = "hello world";
// 加密
String encodeStr = new String(base16.encode(str.getBytes()));
System.out.println(encodeStr);
// 解密
System.out.println(new String(base16.decode(encodeStr.getBytes())));
}
}运行上面代码,输出结果如下:
68656C6C6F20776F726C64
hello world(2)使用 encodeAsString() 和 encodeToString() 方法加密,直接返回字符串。代码如下:
package com.huangx.codec.base16;
import org.apache.commons.codec.binary.Base16;
public class Base16Demo2 {
public static void main(String[] args) {
// 创建 Base16 对象
Base16 base16 = new Base16();
// 原始字符串
String str = "hello world";
// 加密
String encodeStr = base16.encodeAsString(str.getBytes());
String encodeStr2 = base16.encodeToString(str.getBytes());
System.out.println(encodeStr);
System.out.println(encodeStr2);
// 解密
System.out.println(new String(base16.decode(encodeStr)));
}
}运行上面代码,输出结果如下:
68656C6C6F20776F726C64
68656C6C6F20776F726C64
hello world