Simple complete code, through this code you will be the RSA encryption algorithm in Java implementation method has a preliminary understanding, this class, you can directly use, the level of high, on their own modifications to improve the code.
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.*;p ublic 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 ();//Save public key FileOutputStream F1 = new FileOutputStream ("Pubkey.dat"); ObjectOutputStream B1 = new ObjectOutputStream (F1); B1.writeobject (pbkey);//Save private key 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!"; /Get public key and parameter e,nfileinputstream 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);//Get plaintext MByte ptext[] = s.getbytes ("UTF-8"); BigInteger m = new BigInteger (ptext);//calculation of ciphertext Cbiginteger C = M.modpow (e, N); System.out.println ("c=" + c);//Save ciphertext 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 {//Read ciphertext BufferedReader in =new BufferedReader (new InputStreamReader (New File InputStream ("Encrypt.dat")); String Ctext = In.readline (); BigInteger C = new BigInteger (ctext);//Read private key FileInputStream F = new FileInputStream ("Privatekey.dat"); ObjectInputStream b = new ObjectInputStream (f); Rsaprivatekey PRK = (rsaprivatekey) b.readobject (); BigInteger d = prk.getprivateexponent ();//Get private key parameter and decrypt BigInteger n = prk.getmodulus (); System.out.println ("d=" + D); System.out.println ("n=" + N); BigInteger m = C.modpow (d,n);//Show decryption result 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 ();d ecrypt ();} catch (Exception e) {System.out.println (E.tostring ());}}}
RSA encryption algorithm Java simple implementation