Base64ToString互相转换、HexToString相互转换

我们为什么要去使用Base64呢?

Base64并不是一种加密技术,而是一种可逆的编码操作,大家试想,当前操作的数据并非全英而是含有中文,或者一些特殊的转义字符(&,\n)等,这样如果对数据不进行编码操作的话,那肯定对于操作结果而言是受影响的。又或者对于一段明文数据,为了区别人们肉眼可见,我们当然可以采取Base64对数据进行编码操作。

Base64编码片段(本文采用org.bouncycastle.util.encoders.Base64类库,也可使用import java.util.Base64;)
需要导入依赖


   org.bouncycastle
   bcprov-jdk15on
   1.60


public static String encodeBase64(String data) throws UnsupportedEncodingException {    
       byte[] encode = Base64.encode(data.getBytes());
        return new String(encode);
    }

Base64解码片段 (org.bouncycastle.util.encoders.Base64)

 public static String decodeBase64(String data) throws UnsupportedEncodingException {
      byte[] decode = Base64.decode(data.getBytes());
        return new String(decode);
    }

如果需要对字符转成Hex(16进制)操作如下

  • String转16进制片段* (org.bouncycastle.util.encoders.Hex)
public static String encodeHex(String data) throws UnsupportedEncodingException {
    byte[] encode = Hex.encode(data.getBytes());
    return new String(encode);
}
  • Hex转String片段* (org.bouncycastle.util.encoders.Hex)
public static String decodeHex(String data) throws UnsupportedEncodingException {
    byte[] decode = Hex.decode(data.getBytes());
    return new String(decode);
}

需要注意的是有些项目需求Base64返回值应该为byte[]数组类型 改变返回值即可 这里举例Base64Util包 (import java.util.Base64)

public static byte[] encodeBase64Byte(String data){
    byte[] encode = Base64.getEncoder().encode(data.getBytes());
    return encode;
}

你可能感兴趣的:(编码解码加密)