生活随笔
收集整理的這篇文章主要介紹了
廖雪峰Java10加密与安全-4加密算法-5非对称加密算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.非對稱加密
非對稱加密就是加密和解密使用的不是相同的密鑰
package com.testList;import org.bouncycastle.jcajce.provider.symmetric.ARC4;import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;public class RSAKeyPair {PrivateKey sk;//私鑰PublicKey pk;//公鑰//構造方法1:生成公鑰/私鑰對public RSAKeyPair() throws GeneralSecurityException {KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");kpGen.initialize(1024);//初始化,密鑰長度為1024位KeyPair kp = kpGen.generateKeyPair();//生成KeyPairthis.sk = kp.getPrivate();//通過getPrivate()生成私鑰this.pk = kp.getPublic();//通過getPublic()生成公鑰}//構造方法2:從已保存的字節中(例如,讀取文件)恢復公鑰/私鑰public RSAKeyPair(byte[] pk, byte[] sk) throws GeneralSecurityException{KeyFactory kf = KeyFactory.getInstance("RSA");//恢復公鑰X509EncodedKeySpec pkSpec = new X509EncodedKeySpec(pk);this.pk = kf.generatePublic(pkSpec);//恢復私鑰PKCS8EncodedKeySpec skSpec = new PKCS8EncodedKeySpec(sk);this.sk = kf.generatePrivate(skSpec);}//把私鑰導出為字節數組public byte[] getPrivateKey(){return this.sk.getEncoded();}//把公鑰導出為字節數組public byte[] getPublicKey(){return this.pk.getEncoded();}//用公鑰加密public byte[] encrypt(byte[] message) throws GeneralSecurityException{Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE,this.pk);return cipher.doFinal(message);}//用公鑰解密public byte[] decrpt(byte[] input) throws GeneralSecurityException{Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE,this.sk);return cipher.doFinal(input);}public static void main(String[] args) throws Exception{byte[] plain = "Hello,使用RSA非對稱加密算法對數據進行加密!".getBytes("utf-8");//創建公鑰和私鑰對RSAKeyPair rsa = new RSAKeyPair();//加密byte[] encrypted = rsa.encrypt(plain);System.out.println("encrypted:"+ Base64.getEncoder().encodeToString(encrypted));byte[] decrypted = rsa.decrpt(encrypted);System.out.println("decryted:"+new String(decrypted));//保存公鑰和私鑰byte[] sk = rsa.getPrivateKey();byte[] pk = rsa.getPublicKey();System.out.println("pk:"+Base64.getEncoder().encodeToString(pk));System.out.println("sk"+Base64.getEncoder().encodeToString(sk));//重新恢復公鑰和私鑰RSAKeyPair rsa2 = new RSAKeyPair(pk,sk);//加密byte[] encrypted2 = rsa2.encrypt(plain);System.out.println("encrypted2:"+Base64.getEncoder().encodeToString(encrypted2));//解密byte[] decrypted2 = rsa2.decrpt(encrypted2);System.out.println("decrypted2:"+new String(decrypted2));}
}
3.非對稱加密算法優缺點:
- 優點
* 對稱加密需要協商密鑰,而非對稱加密可以安全地公開各自的公鑰
* N個人之間通信: - 使用非對稱加密只需要N個密鑰對。每個人值管理自己的密鑰對
- 使用對稱加密需要N*(N-1)/2個密鑰。每個人需要管理N-1個密鑰
缺點:速度慢
4.總結:
- 非對稱加密就是加密和解密使用的不是相同的密鑰
- 只有同一個公鑰/私鑰對才能正常加密/解密
只使用非對稱加密算法不能防止中間人攻擊
轉載于:https://www.cnblogs.com/csj2018/p/10871900.html
總結
以上是生活随笔為你收集整理的廖雪峰Java10加密与安全-4加密算法-5非对称加密算法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。