java安全--對稱加密
加密不多說了,無非就是拿鑰匙開門,現在先看看對稱加密,就是一把鎖,鎖上門是這把鑰匙,開門還是這把鑰匙
1 import javax.crypto.Cipher;
2 import javax.crypto.KeyGenerator;
3 import javax.crypto.SecretKey;
4
5 public class SecretKeyTest {
6
7 public static void main(String[] args) throws Exception {
8
9 // 加密類,只能通過類自帶的getInstance靜態方法獲得對象
10 Cipher cipher = Cipher.getInstance("AES");// 加密算法
11
12 // 創建一個密鑰,可以看到SecretKey是個接口,通過KeyGenerator這個發生器獲得
13 SecretKey key = KeyGenerator.getInstance("AES").generateKey();
14
15 // 初始化為加密模式,密鑰是剛才創建的密鑰
16 cipher.init(Cipher.ENCRYPT_MODE, key);
17
18 // update是加密緩沖區內容,這里方便配合輸入流加密
19 cipher.update("aaa".getBytes());
20 cipher.update("bbb".getBytes());
21
22 // 取得加密后的結果
23 byte[] eresults = cipher.doFinal();
24 //這里是直接加密運算
25 // byte[] eresults =cipher.doFinal("aaabbb".getBytes());
26
27 // 將加密的結果格式化為字符串
28 String result = new String(eresults);
29 System.out.println(result);
30
31 // 初始化為解密模式,密鑰是加密時使用的key
32 cipher.init(Cipher.DECRYPT_MODE, key);
33
34 // 取得解密后的結果
35 byte[] dresults = cipher.doFinal(eresults);
36 result = new String(dresults);
37
38 System.out.println(result);
39 }
40 }
-----待續
浙公網安備 33010602011771號