Java Base64 编码解码方案总结

早期作法

早期在Java上做Base64的编码与解码,会使用到JDK里sun.misc套件下的BASE64Encoder和BASE64Decoder这两个类别,用法如下:

private static void beforeJDK1_8() throws IOException {
    BASE64Encoder encoder = new BASE64Encoder();
    BASE64Decoder decoder = new BASE64Decoder();

    String text = "你好么?";

    byte[] bytesText = text.getBytes("UTF-8");

    String encodeString = encoder.encode(bytesText);

    System.out.println("编码: " + encodeString);

    byte[] bytesDeText = decoder.decodeBuffer(encodeString);
    System.out.println(new String(bytesDeText,"UTF-8"));
}

Apache Commons Codec作法

public static String base64Encode(String data){

    return Base64.encodeBase64String(data.getBytes());
}

public static byte[] base64Decode(String data){

    return Base64.decodeBase64(data.getBytes());
}

public static String md5(String data) {

    return DigestUtils.md5Hex(data);
}

public static String sha1(String data) {

    return DigestUtils.shaHex(data);
}

public static String sha256Hex(String data) {

    return DigestUtils.sha256Hex(data);
}

 

private static void ApacheUtils() throws UnsupportedEncodingException {

    String base64 = base64Encode("ricky");
    System.out.println("base64 encode="+base64);

    byte[] buf = base64Decode(base64);
    System.out.println("base64 decode="+new String(buf));

    String md5 = md5("ricky");
    System.out.println("md5="+md5+"**len="+md5.length());

    String sha1 = sha1("test");
    System.out.println("sha1="+sha1+"**len="+sha1.length());
}

 

Java 8之后的作法

Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下:

private static void afterJDK1_8() throws UnsupportedEncodingException {
    Base64.Encoder encoder = Base64.getEncoder();
    Base64.Decoder decoder = Base64.getDecoder();

    String text = "你妹的!";

    byte[] bytesEnText = text.getBytes("UTF-8");

    String encodeToString = encoder.encodeToString(bytesEnText);

    System.out.println(encodeToString);

    byte[] byteDeText = decoder.decode(encodeToString);

    System.out.println(new String(byteDeText,"UTF-8"));
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值