Maven依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.17.0</version>
</dependency>
测试代码
public class CodecTest {
private String plainText = "123456";
@Test
void base64_1() {
Base64 base64 = new Base64();
byte[] b = plainText.getBytes(StandardCharsets.UTF_8);
System.out.println(new String(base64.encode(b)));
String encode = base64.encodeToString(plainText.getBytes());
System.out.println(encode);
System.out.println(new String(base64.decode(encode)));
}
@Test
public void base64_2() throws UnsupportedEncodingException {
byte[] b = plainText.getBytes(StandardCharsets.UTF_8);
String encodeStr = Base64.encodeBase64String(b);
System.out.println("Base64 编码后:" + encodeStr);
String decodeStr = new String(Base64.decodeBase64(encodeStr));
System.out.println("Base64 解码后:" + decodeStr);
}
@Test
void hex_1() throws DecoderException {
byte[] b = plainText.getBytes(StandardCharsets.UTF_8);
Hex hex = new Hex();
byte[] bytes = hex.encode(b);
String hexStr = new String(bytes);
System.out.println(hexStr);
byte[] result = hex.decode(hexStr.getBytes());
System.out.println(new String(result));
}
@Test
void hex_2() throws DecoderException {
byte[] b = plainText.getBytes(StandardCharsets.UTF_8);
String hexString = Hex.encodeHexString(b);
System.out.println(hexString);
byte[] decodeHex1 = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(decodeHex1));
char[] encodeHex = Hex.encodeHex(b, true);
System.out.println(new String(encodeHex));
byte[] decodeHex = Hex.decodeHex(encodeHex);
System.out.println(new String(decodeHex));
}
@Test
void digestUtils() {
byte[] b = plainText.getBytes(StandardCharsets.UTF_8);
System.out.println(DigestUtils.md5Hex(b));
System.out.println(DigestUtils.sha1Hex(b));
System.out.println(DigestUtils.sha256Hex(b));
System.out.println(DigestUtils.sha384Hex(b));
System.out.println(DigestUtils.sha512Hex(b));
}
@Test
void urlCodec() throws EncoderException, DecoderException {
String url = "http://baidu.com?name=你好";
URLCodec codec = new URLCodec();
String encode = codec.encode(url);
System.out.println(encode);
String decodes = codec.decode(encode);
System.out.println(decodes);
}
}