生活随笔
收集整理的這篇文章主要介紹了
廖雪峰Java10加密与安全-4加密算法-5非对称加密算法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.非對(duì)稱(chēng)加密
非對(duì)稱(chēng)加密就是加密和解密使用的不是相同的密鑰
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;//公鑰//構(gòu)造方法1:生成公鑰/私鑰對(duì)public RSAKeyPair() throws GeneralSecurityException {KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");kpGen.initialize(1024);//初始化,密鑰長(zhǎng)度為1024位KeyPair kp = kpGen.generateKeyPair();//生成KeyPairthis.sk = kp.getPrivate();//通過(guò)getPrivate()生成私鑰this.pk = kp.getPublic();//通過(guò)getPublic()生成公鑰}//構(gòu)造方法2:從已保存的字節(jié)中(例如,讀取文件)恢復(fù)公鑰/私鑰public RSAKeyPair(byte[] pk, byte[] sk) throws GeneralSecurityException{KeyFactory kf = KeyFactory.getInstance("RSA");//恢復(fù)公鑰X509EncodedKeySpec pkSpec = new X509EncodedKeySpec(pk);this.pk = kf.generatePublic(pkSpec);//恢復(fù)私鑰PKCS8EncodedKeySpec skSpec = new PKCS8EncodedKeySpec(sk);this.sk = kf.generatePrivate(skSpec);}//把私鑰導(dǎo)出為字節(jié)數(shù)組public byte[] getPrivateKey(){return this.sk.getEncoded();}//把公鑰導(dǎo)出為字節(jié)數(shù)組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非對(duì)稱(chēng)加密算法對(duì)數(shù)據(jù)進(jìn)行加密!".getBytes("utf-8");//創(chuàng)建公鑰和私鑰對(duì)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));//重新恢復(fù)公鑰和私鑰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.非對(duì)稱(chēng)加密算法優(yōu)缺點(diǎn):
轉(zhuǎn)載于:https://www.cnblogs.com/csj2018/p/10871900.html
總結(jié)
以上是生活随笔為你收集整理的廖雪峰Java10加密与安全-4加密算法-5非对称加密算法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。