下面是一个使用Java 8编写的Base64加密函数,与org.apache.commons.codec.binary.Base64类似,提供源代码:

import java.util.Base64;

public class MyBase64 {

    public static String encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static byte[] decode(String str) {
        return Base64.getDecoder().decode(str);
    }
}

这个类包含两个静态方法:encode和decode。encode方法接受一个byte数组,返回一个Base64编码的字符串。decode方法接受一个Base64编码的字符串,返回一个byte数组。

使用这个类非常简单:

String str = "Hello, world!";
String encodedStr = MyBase64.encode(str.getBytes());
byte[] decodedBytes = MyBase64.decode(encodedStr);
String decodedStr = new String(decodedBytes);
System.out.println(str.equals(decodedStr)); // true

在这个示例中,我们将字符串“Hello, world!”编码为Base64字符串,然后将其解码回原始字符串,最后打印出true,证明解码成功。

用java8 写一个和orgapachecommonscodecbinaryBase64一样的base64加密函数并提供源码

原文地址: https://www.cveoy.top/t/topic/MMn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录