[問題] 使用JAVA API寫AES加密器的問題
您好~小弟又來問問題了
我用JAVA 的API來處理AES加密的問題
因為小弟是新手,所以有參考別人的寫法
參考的網址為http://cooking-java.blogspot.tw/2010/03/java-aes-encrypt.html
我修改成下列程式碼
為了提高可讀性,我import的部分就省略了
執行結果 有列印出明文 與 key
不過key怎麼是亂碼??
另外如果用128長度的key可以執行
但用192與256長度就會抓到InvalidKeyException
如下(我用eclipse)
Exception:java.security.InvalidKeyException: Illegal key size or default parameters
Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized
at javax.crypto.Cipher.c(DashoA12275)
at javax.crypto.Cipher.doFinal(DashoA12275)
所以想請教
1.怎麼讓key不是亂碼
2.如何可執行192與256key
3.另外我還沒寫到先問,可以使用PKCS7Padding 嗎?
--------------------------------------------------------------------------
1. public class AES
2. {
3.
4. public static void main(String args[])
5. {
6. String msg = "This is a message."; //欲加密的字串
7.
8. KeyGenerator keyG = null;
9. try
10. {
11. keyG = KeyGenerator.getInstance("AES"); //設定要使用的加密演算法
12. }
13. catch(NoSuchAlgorithmException e )
14. {
15. System.out.println("Exception:" + e);
16. }
17. System.out.println("原始字串:" + new String(msg));
18. keyG.init(192); //設定key的長度
19. SecretKey secuK = keyG.generateKey(); //產生SecretKey
20. byte[] key = secuK.getEncoded(); //取得要用來加密的key(解密也需使用這把key)
21. System.out.println("key:"+new String(key));
22. SecretKeySpec spec = new SecretKeySpec(key, "AES");
23.
24. Cipher cipher = null;
25. try
26. {
27. cipher = Cipher.getInstance("AES");
28. }
29. catch(NoSuchAlgorithmException e)
30. {
31. System.out.println("Exception:" + e);
32. }
33. catch(NoSuchPaddingException e)
34. {
35. System.out.println("Exception:" + e);
36. }
37.
38. try
39. {
40. cipher.init(Cipher.ENCRYPT_MODE, spec); //設定為加密模式
41. }
42. catch(InvalidKeyException e)
43. {
44. System.out.println("Exception:" + e);
45. }
46.
47. byte[] encryptData = null;
48. try
49. {
50. encryptData = cipher.doFinal(msg.getBytes()); //將字串加密,並取得加密後的資料
51. }
52. catch(IllegalBlockSizeException e)
53. {
54. System.out.println("Exception:" + e);
55. }
56. catch(BadPaddingException e)
57. {
58. System.out.println("Exception:" + e);
59. }
60.
61.
62. System.out.println("加密後字串:"+new String(encryptData));
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 113.61.142.192
→
12/09 15:36, , 1F
12/09 15:36, 1F
推
12/09 15:37, , 2F
12/09 15:37, 2F
→
12/09 15:37, , 3F
12/09 15:37, 3F
→
12/09 15:38, , 4F
12/09 15:38, 4F
→
12/09 15:44, , 5F
12/09 15:44, 5F
→
12/09 19:41, , 6F
12/09 19:41, 6F
→
12/09 20:36, , 7F
12/09 20:36, 7F
推
01/15 13:30, , 8F
01/15 13:30, 8F
討論串 (同標題文章)