First, RSA is an asymmetric encryption algorithm. Therefore, before encrypting and decrypting using this algorithm, the key pair must be generated beforehand. Include public and private keys
The class keypairgenerator for generating key pairs is provided in the JDK, with the actual proportions as follows:
public static map<string, Object> Genkeypair () throws Exception {//Get the generator of the private key pair for keypairgenerator KPG = Keypairgene Rator.getinstance ("RSA");//Initialize key generator to determine key size kpg.initialize (1024);//Generate key pair keypair KP = Kpg.generatekeypair (); Rsapublickey PublicKey = (rsapublickey) kp.getpublic (); Rsaprivatekey Privatekey = (rsaprivatekey) kp.getprivate (); map<string, object> keyMap = new hashmap<string, object> (); Keymap.put (Public_key, PublicKey); KeyMap.put ( Private_key, Privatekey); return keyMap;}
The above code returns a map type of data. The public and private keys are stored
When you're finished with the key pair, you're ready to expose the public key. Allow the relevant cryptographic program to implement RSA encryption through the public key
public static byte[] Encryptbypublickey (byte[] data, String publickey) throws Exception { //data is the data to be encrypted string.getbytes can byte[] keybytes = Base64utils.decode (publickey); // Creates a new x509encodedkeyspec x509encodedkeyspec based on the specified encoding key X509keyspec = new X509encodedkeyspec (keybytes); keyfactory keyfactory = keyfactory.getinstance ( Encrypt_algorithm); //generate a public key object based on the provided key specification Key Publick = keyfactory.generatepublic (x509keyspec); //to Data encryption cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); //Initializes the cipher of the encryption mode with the key. All that's behind the Dofinal method is encryption cipher.init(Cipher.encrypt_mode, Publick); int Inputlen = data.length; bytearrayoutputstream out = new Bytearrayoutputstream (); int OffSet = 0; byte[] cache; int i = 0; & nbsp //Data Segmentation encryption while (Inputlen-offset > 0) { & nbsp; if (Inputlen-offset > Max_encrypt_block) {//One-time encrypted byte length cache = cipher.dofinal (data, OffSet, Max_encrypt_block ); } else { cache = cipher.dofinal (data, OffSet, Inputlen-offset); } out.write (cache, 0, cache.length); i++; offset = i * max_encrypt_block; } byte[] EncryptedData = Out.tobytearray (); out.close (); return encrypteddata; }
Decrypt the ciphertext with your private key after the encryption is complete
public static byte[] Decryptbyprivatekey (byte[] data, String Privatekey) throws Exception {byte[] keybytes = BASE64UTILS.D Ecode (Privatekey); Pkcs8encodedkeyspec Pkcs8keyspec = new Pkcs8encodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (encrypt_algorithm); Key Privatek = keyfactory.generateprivate (Pkcs8keyspec); Cipher Cipher = cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, privatek); int Inputlen = Data.length; Bytearrayoutputstream out = new Bytearrayoutputstream (), int offSet = 0;byte[] cache;int i = 0;//the data fragment decryption while (Inputlen- OffSet > 0) {if (Inputlen-offset > Max_decrypt_block) {cache = cipher.dofinal (data, OffSet, Max_decrypt_block);} E LSE {cache = cipher.dofinal (data, OffSet, Inputlen-offset);} Out.write (cache, 0, cache.length); i++;offset = i * max_decrypt_block;} byte[] Decrypteddata = Out.tobytearray (); Out.close (); return decrypteddata;}
To generate a key pair:
try {map<string, object> keyMap = Rsautils.genkeypair ();p Ublickey = Rsautils.getpublickey (keyMap);p Rivatekey = Rsautils.getprivatekey (KEYMAP); SYSTEM.OUT.PRINTLN ("Public key--" + PublicKey); SYSTEM.OUT.PRINTLN ("Private key--" + Privatekey);} catch (Exception e) {e.printstacktrace ();}
Execution results show:
Public Key-->migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcjjodvrldn/5nwhmpftc9xffgmt2saj7b+ybk55hsr1iqqt5k8/ 4o5qdnk3qxhgigwusydpxr2fk5dzfxsomjc0l2czgastakbbvw1wbosyo11cxnpkphn3pivbubxrpeucj4hrmktubk662aa0ysxy2/ Brk4nxxtrlmxi+/bysqidaqab
Private key-->miicdwibadanbgkqhkig9w0baqefaascamewggjdageaaogbakmk51vgum3/mdyeakw1z1d9+czpzicptv7igtnkdkvwjbc3mtz/ g7mp2eterggaiba5lionfhyurl3n9eyianzqvyjkzpk0crtu/ Dxbs5jijxvze2msmgfc8hvu4hguks4ingeswpo4gtrrzodtkzhlb8gsrg1fg1guzej78fixagmbaaecgyboqptzsxobsi0gh3maaoz1rdkhimsywz4vopk8pz mxfa8gx801bbopudlcrs+xnwlypa0onh8g1kb3av7euqrgxjhzqk61ahfbz7w2yjl326uag+ q7szi3bxolkeqhcsd6gggvs9psegxu9u21gabxrysgerqe42sllnpg8ykmaqjbapv8j8mbmip+mhnykmvplmza0/ nuzlblgzraht0umupey6bhiyqnwxaabchs3qlrcmrt7payik9cjo53ojprrvkcqqclvhmgvursiuoiazjkxge11iphw6fox4nf/om+ jnndeeo6vv//lnqwadkas1f7jwo6vyisqjitpj9kugtzm2mzakba5qewd9/4o/y8lzjjq9++6u+lts7+ 6l2fdf4gajs7dgvdk0rrumt4vmue6wxvn4hserv1dlud3kwpf01vdjzbakeajwwpbc5z2l1muglpchjwygvxvjvdeec12erdzcgtncdp2nybvy4onjdmtlq2g rkba+x2watiow6je7goxrzq2qjbajcwgti2lp9ftl2x5xhz0vk+dogirdbzxs/g/ zkknh393vejvb7qlok03ay4r4vw4sscusf3yashmqupjodfqeg=
Use public key cryptography. Private key decryption:
SYSTEM.OUT.PRINTLN ("Public key encryption-private key decryption"); System.out.println ("Content of pre-encryption data is--" + sourcestr); byte[] data = Sourcestr.getbytes (); byte[] EncryptData = Rsautils.encryptbypublickey (data, PublicKey); SYSTEM.OUT.PRINTLN ("Encrypted data content is--" + New String (EncryptData)); byte[] Decryptdata = Rsautils.decryptbyprivatekey ( Encryptdata,privatekey); SYSTEM.OUT.PRINTLN ("Decrypted data content is--" + New String (Decryptdata));
Public key encryption--private key decryption
The content of the data before the encryption is--this is a piece of data to be encrypted
The encrypted data content is--(??? %5 [?? W?? Ua-?? M?u?&w?2?? Gq??? -5? Q??? ' 7:й? C,?8t?qm?gj?? E2 "?) Y???????? [Email protected]?y*_?] M????? x*;? F1??? [Email protected]?h?} P? X?2
The decrypted data content is--this is a piece of data to be encrypted
Attached Base64utils.java
Package Rsa;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import java.io.outputstream;public Class Base64utils {private static final char[] Legalchars = " abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/". ToCharArray ();/** * data[] encode * * @param data * @ return */public static String encode (byte[] data) {int start = 0;int len = data.length; StringBuffer buf = new StringBuffer (data.length * 3/2); int end = Len-3;int i = start;int n = 0;while (i <= end) {in T d = (((((int) data[i]) & 0X0FF) << 16) | (((((int) Data[i + 1]) & 0X0FF) << 8) | (((int) Data[i + 2]) & 0X0FF); Buf.append (legalchars[(d >>) & []]) Buf.append (legalchars[(d >> 12) & Amp (legalchars[(d >> 6) & Buf.append]), Buf.append (Legalchars[d &)); i + = 3;if (n++ >=) {n = 0;bu F.append ("");}} if (i = = start + len-2) {int d = ((((int) data[i]) & 0X0FF) << 16) | (((((int) Data[i + 1]) & 255) << 8); buf.append(legalchars[(d >>) & Buf.append]), Buf.append (legalchars[(d >> +) & []); legalchars[(D > > 6) & []); Buf.append ("=");} else if (i = = start + len-1) {int d = ((int) data[i]) & 0x0ff) << 16;buf.append (legalchars[(d >>) &A mp Buf.append (legalchars[(d >>) &]), buf.append ("= ="); return buf.tostring ();} private static int decode (char c) {if (C >= ' a ' && C <= ' Z ') return ((int) c)-65;else if (c >= ' a ' & & c <= ' Z ') return ((int) c)-26;else + if (c >= ' 0 ' && C <= ' 9 ') return ((int) c)-+ + + 26;e Lseswitch (c) {case ' + ': return 62;case '/': return 63;case ' = ': Return 0;default:throw new RuntimeException ("Unexpected cod E: "+ C);}} /** * Decodes the given BASE64 encoded String to a new byte array. The byte array holding the decoded data is returned. */public Static byte[] Decode (String s) {bytearrayoutputstream bos = new Bytearrayoutputstream (); try {decode (s, BOS);} cat CH (IOException e) {throw new RuntimeException ();} byte[] decodedbytes = Bos.tobytearray (); try {bos.close (); bos = null;} catch (IOException ex) {System.err.println ("Error W Hile decoding BASE64: "+ ex.tostring ());} return decodedbytes;} private static void Decode (String s, OutputStream os) throws IOException {int i = 0;int len = s.length (); while (true) {WHI Le (i < len && S.charat (i) <= ") i++;if (i = = len) Break;int tri = (decode (S.charat (i)) << +) + (deco De (S.charat (i + 1)) <<) + (decode (S.charat (i + 2)) << 6) + (decode (S.charat (i + 3)); Os.write (Tri >> & 255), if (S.charat (i + 2) = = ' = ') break;os.write ((Tri >> 8) & 255), if (S.charat (i + 3) = = ' = ') Break;os. Write (Tri & 255); i + = 4;}} /** * data[] encoded * * @param data * @return */public static String Base64encoder (byte[] data) {int start = 0;int len = dat A.length; StringBuffer buf = new StringBuffer (data.length * 3/2); int end = Len-3;int i = start;int n = 0;while (i <= end) {in T D = (((((int) data[i]) & 0X0FF) << 16) | (((((int) Data[i + 1]) & 0X0FF) << 8) | (((int) Data[i + 2]) & 0X0FF); Buf.append (legalchars[(d >>) & []]) Buf.append (legalchars[(d >> 12) & Amp (legalchars[(d >> 6) & Buf.append]), Buf.append (Legalchars[d &)), i + = 3;if (n++ >= 14) {//No space n required = 0;}} if (i = = start + len-2) {int d = ((((int) data[i]) & 0X0FF) << 16) | ((((((int) Data[i + 1]) & 255) << 8) buf.append (legalchars[(d >>) & []) Buf.append (legalchars[(d Buf.append (legalchars[(d >> 6) &;>]) buf.append ("=");} else if (i = = start + len-1) {int d = ((int) data[i]) & 0x0ff) << 16;buf.append (legalchars[(d >>) &A mp Buf.append (legalchars[(d >>) &]), buf.append ("= ="); return buf.tostring ();}}
Implementation of RSA encryption and decryption asymmetric algorithm by Java