个人技术分享

【无标题】

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);
        //字符串类型的,该方法要求传入的是char[]
        byte[] decodeHex1 = Hex.decodeHex(hexString.toCharArray());
        System.out.println(new String(decodeHex1));


        //先转换成char数组,第二个参数意思是是否全部转换成小写
        char[] encodeHex = Hex.encodeHex(b, true);
        System.out.println(new String(encodeHex));
        //char数组型的
        byte[] decodeHex = Hex.decodeHex(encodeHex);
        System.out.println(new String(decodeHex));
    }

    // DigestUtils 工具类,该类用于简化常见 MessageDigest(消息摘要)任务的操作
    @Test
    void digestUtils() {
        // MD5是RSA数据安全公司开发的一种单向散列算法,非可逆,相同的明文产生相同的密文
        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);
    }

}