Base64 加密与解密
正常来讲加密基本上永远都要伴随着解密,所谓的加密或者是解密往往都要伴随着解密,所谓的加密或者是解密往往都需要有一些新的加密处理操作类,Base64 处理,在这个类里面有两个内部类:
-
Base64.Encoder:进行加密才能处理;
- 加密处理:
public byte[] encode(byte[] src);
- 加密处理:
-
Base64.Decoder:进行解密处理;
- 解密处理:
public byte[] decode(String src);
- 解密处理:
实现加密解密操作
String str = "~~~~~虫儿飞~~~~~";
String encStr = new String(Base64.getEncoder().encode(str.getBytes()));
System.out.println(encStr);
String oldStr = new String(Base64.getDecoder().decode(encStr.getBytes()));
System.out.println(oldStr);
虽然 Base64 可以实现加密与解密的处理,但是其由于其是一个公版的算法,所以如果对其进行加密,最好的做法是使用盐值操作。
String salt = "byfjava";
String str = "~~~~~虫儿飞~~~~~"+salt;
String encStr = new String(Base64.getEncoder().encode(str.getBytes()));
System.out.println(encStr);
String oldStr = new String(Base64.getDecoder().decode(encStr.getBytes()));
System.out.println(oldStr);
即便有盐值处理,但加密效果并不完善,所以要用到多次加密
多次加密
class StringUtils {
private static final String SALT = "byf666";// 公共的盐值
private static final int REPEAT = 5; // 加密次数
/**
* 加密处理
* @param str 要加密的字符串,需要与盐值整合
* @return
*/
public static String encode(String str) {
String temp = str + SALT;
byte data[] = temp.getBytes();
for (int i = 0; i < REPEAT; i++) {
data = Base64.getEncoder().encode(data);
}
return new String(data);
}
public static String decode(String str) {
byte data[] = str.getBytes();
for (int i = 0; i < REPEAT; i++) {
data = Base64.getDecoder().decode(data);
}
String result = new String(data).replaceAll(SALT, "");
return result;
}
}
public class Base64Test {
public static void main(String[] args) {
String str = "~~~~~虫儿飞~~~~~";
String encode = StringUtils.encode(str);// 加密
System.out.println(encode);
String decode = StringUtils.decode(encode);// 解密
System.out.println(decode);
}
}
最好的做法是使用 2-3 种加密程序,同时在找到一些完全不可解密的加密算法。