歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java安全之對稱加密與非對稱加密

Java安全之對稱加密與非對稱加密

日期:2017/3/1 11:11:22   编辑:Linux編程

Java中加密分為兩種方式一個是對稱加密,另一個是非對稱加密。對稱加密是因為加密和解密的鑰匙相同,而非對稱加密是加密和解密的鑰匙不同。

對稱加密與非對稱加密的區別:

對稱加密稱為密鑰加密,速度快,但加密和解密的鑰匙必須相同,只有通信雙方才能知道密鑰。

非對稱加密稱為公鑰加密,算法更加復雜,速度慢,加密和解密鑰匙不相同,任何人都可以知道公鑰,只有一個人持有私鑰可以解密。

對稱加密解密:

  1. /*
  2. * 對稱加密
  3. */
  4. private static void secretEncrypt() throws Exception {
  5. //使用Cipher的實例
  6. Cipher cipher =Cipher.getInstance("AES");
  7. //得到加密的鑰匙
  8. SecretKey key =KeyGenerator.getInstance("AES").generateKey();
  9. //初始化加密操作,傳遞加密的鑰匙
  10. cipher.init(Cipher.ENCRYPT_MODE,key);
  11. //將加密的鑰匙寫入secretKey.key文件中
  12. FileOutputStream fosKey=new FileOutputStream("secretKey.key");
  13. ObjectOutputStream oosSecretKey =new ObjectOutputStream(fosKey);
  14. oosSecretKey.writeObject(key);
  15. oosSecretKey.close();
  16. fosKey.close();
  17. //將加密的內容傳遞進去,返回加密後的二進制數據
  18. byte [] results =cipher.doFinal("哈哈哈哈哈".getBytes());
  19. //將加密後的二進制數據寫入到secretContent.dat文件中
  20. FileOutputStream fosData=new FileOutputStream("secretContent.dat");
  21. fosData.write(results);
  22. fosData.close();
  23. }
  24. /*
  25. * 對稱解密
  26. */
  27. private static void secretDecrypt() throws Exception{
  28. Cipher cipher =Cipher.getInstance("AES");
  29. //獲取文件中的key進行解密
  30. FileInputStream fisKey=new FileInputStream("secretKey.key");
  31. ObjectInputStream oisKey =new ObjectInputStream(fisKey);
  32. Key key =(Key)oisKey.readObject();
  33. oisKey.close();
  34. fisKey.close();
  35. //初始化解密操作,傳遞加密的鑰匙
  36. cipher.init(Cipher.DECRYPT_MODE,key);
  37. //獲取文件中的二進制數據
  38. FileInputStream fisDat=new FileInputStream("secretContent.dat");
  39. //獲取數據第一種方式
  40. byte [] src=new byte [fisDat.available()];
  41. int len =fisDat.read(src);
  42. int total =0;
  43. while(total<src.length){
  44. total +=len;
  45. len=fisDat.read(src,total,src.length-total);
  46. }
  47. //執行解密
  48. byte [] result=cipher.doFinal(src);
  49. fisDat.close();
  50. System.out.println(new String(result));
  51. // 讀文件中的數據第二種方式
  52. // ByteArrayOutputStream baos =new ByteArrayOutputStream();
  53. // copyStream(fisDat, baos);
  54. // byte [] result=cipher.doFinal(baos.toByteArray());
  55. // fisDat.close();
  56. // baos.close();
  57. }
  58. // private static void copyStream(InputStream ips,OutputStream ops) throws Exception{
  59. // byte [] buf =new byte[1024];
  60. // int len=ips.read(buf);
  61. // while(len!=-1){
  62. // ops.write(buf,0,len);
  63. // len =ips.read(buf);
  64. // }
  65. // }
Copyright © Linux教程網 All Rights Reserved