為了安全地進行數據傳輸,就需要對數據進行加密與解密操作,Base64就是Java提供的加密處理器。本博客主要講解Base64工具類的使用以及加密和解密信息操作實現。
Base64是一種直接利用64個可打印字符來表示二進制數據的算法,也是網絡傳輸中較為常見的一種加密算法。從JDK1.8版本開始提供java.util.Base64的工具類,同時提供了兩個Base64的內部類實現數據加密與解密操作。
【數據加密】java.util.Base64.Encoder, 對象獲取方法:public static Base64.Encoder getEncoder()。數據加密處理:public byte[] encoder(byte[] src)。
【數據解密】java.util.Base64.Decoder, 對象獲取方法:public static Base64.Decoder getDecoder()。
數據解密處理:public byte[] decoer (String src)。
### 范例:實現Base64加密與解密操作
1
2
3
4
5
6
7
8
9
10
11
|
package cn.mldn.demo; 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); //輸出密文 String oldMsg= new String(Base64.getDecoder().decode(encMsg)); //數據解密 System.out.println(oldMsg); //輸出明文 } } |
程序執行結果:
d3d3Lm1sZG4uY24=(密文)
www.mldn.cn(明文)
本程序直接利用Base64提供的方法獲取了Base64.Encoder與Base64.Decoder實例化對象,并且對原始數據進行了加密與解密處理。但需要注意的是,由于Base64屬于JDK的原始實現,所以單純地加密是不安全的,此時為了獲取更加安全的數據加密操作,可以利用鹽值(salt)、自定義格式以及多次加密的方式來保證項目中的數據安全。
### 范例:基于Base64定義復雜加密與解密操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package cn.mldn.demo; import java.util.Base64; class StringUtil { private static final String SALT= "mldnjava" ; //公共的鹽值 private static final int REPEAT= 5 ; //加密次數 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); //返回加密后的內容 } 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(StringUtil.decode(str)); } } |
本程序基于Base64類的功能實現了一個自定義加密與解密程序,為了保證加密后的數據安全,采用的鹽值格式為“鹽值{原始數據}”,同時利用多次加密的形式確保了密文數據的可靠性。在實際開發中只要不對外公布鹽值內容和加密次數就可以在較為安全的環境下進行數據傳輸.
到此這篇關于java必懂的冷知識點之Base64加密與解密的文章就介紹到這了,更多相關java Base64加密與解密內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qqshenbaobao/article/details/114701905