在實際場景中經常會有資料通信事件,而對于某些對安全性要求比較高的需求,簡單的資料傳輸是不夠用的,本節将為讀者介紹使用Base64加密解密資料的方法。
【本節目标】
通過閱讀本節内容,你将對資料加密解密工作有一個初步的認識,并能夠使用Base64結合附加鹽值、多層加密解密等技巧實作對資料的簡單加密。
Base64加密工具
正常來講加密基本上永遠都要伴随着解密,所謂的加密或者是解密往往都需要有一些規則。在JDK1.8開始提供有一組新的加密處理操作類,Base64處理。在這個類裡面有兩個内部類:
Base64.Encoder:進行加密處理;
|- 加密處理:public byte[] encode(byte[] src);
Base64.Decoder:進行解密處理;
|- 解密處理:public byte[] decode(byte[] src);
範例:實作加密與解密操作
import java.util.Base64;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
String msg="www.mldn.cn"; //要發送的資訊
String encMsg=new String(Base64.getEncoder().encode(msg.getBytes())); //資料加密
System.out.println(encMsg); //d3d3Lm1sZG4uY24=
String oldMsg=new String(Base64.getDecoder().decode(encMsg));
System.out.println(oldMsg); //www.mldn.cn
}
}
雖然Base64可以實作加密與解密的處理,但是其由于是一個公版的算法,是以如果直接對資料進行加密往往并不安全,是以最好的做法是使用鹽值操作。
import java.util.Base64;
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
String salt = "mldnjava"; //鹽值
String msg = "www.mldn.cn" + "{" + salt + "}"; //要發送的資訊
String encMsg = new String(Base64.getEncoder().encode(msg.getBytes())); //資料加密
System.out.println(encMsg); //d3d3Lm1sZG4uY257bWxkbmphdmF9
String oldMsg = new String(Base64.getDecoder().decode(encMsg));
System.out.println(oldMsg); //www.mldn.cn{mldnjava}
}
}
即便現在有鹽值實際上發現加密的效果也不是很好,最好的做法是多次加密。
範例:複雜加密
import java.util.Base64;
class StringUtil{
private static final String SALT="mldnjava";//公共的鹽值,不對外暴露,一旦使用不可更改
private static final int REPEAT=5;//加密次數:5次
/**
* 加密處理
* @param str 要加密的字元串,需要與鹽值整合
* @param repeat 加密的重複次數
* @return 加密後的資料
*/
public static String encode(String str){ //加密處理
String temp=str+"{" + SALT + "}"; //鹽值對外不公布
byte data []=temp.getBytes(); //将字元串變為位元組數組
for (int x = 0; x < REPEAT; x ++) {
data=Base64.getEncoder().encode(data); //重複加密
}
return new String(data);
}
/**
* 解密處理
* @param str 要解密的内容
* @return 解密後的原始資料
*/
public static String decode(String str){//解密處理
byte data []=str.getBytes(); //将字元串變為位元組數組
for (int x = 0; x < REPEAT; x++) {
data=Base64.getDecoder().decode(data);
}
return new String(data).replaceAll("\\{\\w+\\}","");
}
}
public class JavaAPIDemo {
public static void main(String[] args) throws Exception {
String str=StringUtil.encode("www.mldn.cn");
System.out.println(str); //VjJ0U1QyRXdNSGRsU0ZKT1YwVTFhRlZ1Y0ZOTlZtUlZVMVJHVDAxcmNGbGFWV1F3WVZkS1dWRnRPV0ZTZWtaSVZERkZPVkJSUFQwPQ==
System.out.println(StringUtil.decode(str)); //www.mldn.cn
}
}
最好的做法就是使用2-3種加密程式,同時再找到一些完全不可解密的加密算法。
想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。
本内容視訊來源于
阿裡雲大學 下一篇:揭開比較器的神秘面紗 | 帶你學《Java語言進階特性》之三十五 更多Java面向對象程式設計文章檢視此處