java安全–對稱式加密

來源:互聯網
上載者:User

加密不多說了,無非就是拿鑰匙開門,現在先看看對稱式加密,就是一把鎖,鎖上門是這把鑰匙,開門還是這把鑰匙

 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 }

-----待續

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.