RSA加密算法java簡略完成辦法(必看)。本站提示廣大學習愛好者:(RSA加密算法java簡略完成辦法(必看))文章只能為提供參考,不一定能成為您想要的結果。以下是RSA加密算法java簡略完成辦法(必看)正文
簡略完全的代碼,經由過程這個代碼你將對RSA加密算法在Java中的完成辦法有一個初步的懂得,這個類,你可以直接應用,程度高的,就本身修正完美下代碼。
package security; import java.security.*; import java.security.spec.*; import java.security.interfaces.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import java.io.*; import java.math.*; public class RSADemo { public RSADemo() { } public static void generateKey() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); PublicKey pbkey = kp.getPublic(); PrivateKey prkey = kp.getPrivate(); // 保留公鑰 FileOutputStream f1 = new FileOutputStream("pubkey.dat"); ObjectOutputStream b1 = new ObjectOutputStream(f1); b1.writeObject(pbkey); // 保留私鑰 FileOutputStream f2 = new FileOutputStream("privatekey.dat"); ObjectOutputStream b2 = new ObjectOutputStream(f2); b2.writeObject(prkey); } catch (Exception e) { } } public static void encrypt() throws Exception { String s = "Hello World!"; // 獲得公鑰及參數e,n FileInputStream f = new FileInputStream("pubkey.dat"); ObjectInputStream b = new ObjectInputStream(f); RSAPublicKey pbk = (RSAPublicKey) b.readObject(); BigInteger e = pbk.getPublicExponent(); BigInteger n = pbk.getModulus(); System.out.println("e= " + e); System.out.println("n= " + n); // 獲得明文m byte ptext[] = s.getBytes("UTF-8"); BigInteger m = new BigInteger(ptext); // 盤算密文c BigInteger c = m.modPow(e, n); System.out.println("c= " + c); // 保留密文 String cs = c.toString(); BufferedWriter out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("encrypt.dat"))); out.write(cs, 0, cs.length()); out.close(); } public static void decrypt() throws Exception { // 讀取密文 BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream("encrypt.dat"))); String ctext = in.readLine(); BigInteger c = new BigInteger(ctext); // 讀取私鑰 FileInputStream f = new FileInputStream("privatekey.dat"); ObjectInputStream b = new ObjectInputStream(f); RSAPrivateKey prk = (RSAPrivateKey) b.readObject(); BigInteger d = prk.getPrivateExponent(); // 獲得私鑰參數及解密 BigInteger n = prk.getModulus(); System.out.println("d= " + d); System.out.println("n= " + n); BigInteger m = c.modPow(d, n); // 顯示解密成果 System.out.println("m= " + m); byte[] mt = m.toByteArray(); System.out.println("PlainText is "); for (int i = 0; i < mt.length; i++) { System.out.print((char) mt[i]); } } public static void main(String args[]) { try { generateKey(); encrypt(); decrypt(); } catch (Exception e) { System.out.println(e.toString()); } } }
以上這篇RSA加密算法java簡略完成辦法(必看)就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。