Wirelessly default mode is not the same as Java project, be careful
Use the public key to encrypt the decryption code on the Android side
Note that this class is required for initialization, and the jar needs to be downloaded separately Org.bouncycastle.jce.provider.BouncyCastleProvider
The CONSTANTS.GETPBK () in the code gets the public key
Import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.math.biginteger;import Java.security.key;import java.security.KeyFactory; Import Java.security.keypair;import Java.security.keypairgenerator;import java.security.NoSuchAlgorithmException; Import Java.security.privatekey;import Java.security.publickey;import Java.security.interfaces.RSAPrivateKey; Import Java.security.interfaces.rsapublickey;import Java.security.spec.invalidkeyspecexception;import Java.security.spec.pkcs8encodedkeyspec;import Java.security.spec.rsapublickeyspec;import Java.security.spec.x509encodedkeyspec;import Javax.crypto.Cipher; /** * @author Young * @date * One-click Encryption decrypts the Android version */public final class Rsautils{private static String RSA = "RSA";p Riv Ate static PublicKey publickey;/** * Randomly generated RSA key pair (default key length is 1024x768) * * @return */private static KeyPair Generatersakeypair () {RE Turn Generatersakeypair (1024);} /** * Randomly generated RSA key pair * * @param keylength * Key length, Range:512~2048<br> * General 1024x768 * @return */private static KeyPair generatersakeypair (int keylengt h) {Try{keypairgenerator KPG = keypairgenerator.getinstance (rsa,new Org.bouncycastle.jce.provider.BouncyCastleProvider ()); Kpg.initialize (keylength); return Kpg.genkeypair (); catch (Throwable e) {e.printstacktrace (); return null;}} /** * Encrypted with public key <br> * Number of bytes per encryption, cannot exceed key length value minus one * * @return encrypted data */public static string EncryptData (String data) {TR Y{if (publickey==null) {Publickey=loadpublickey (constants.getpbk ());} Cipher Cipher = cipher.getinstance (RSA); Cipher Cipher = cipher.getinstance ("rsa/ecb/pkcs1padding");//encode before encoding method and key Cipher.init (Cipher.encrypt_mode, PublicKey);//pass in the encoded data and return the encoded result of return Base64utils.encode (Cipher.dofinal (Data.getbytes ())); } catch (Exception e) {e.printstacktrace (); return null;}} /** * Decryption with public key * * @return */public static string Decryptdata (String data) {Try{if (publickey==null) {Publickey=loadpublick EY (CONSTANTS.GETPBK ());} Byte[] Encrypteddata=Base64utils.decode (data);//cipher Cipher = Cipher.getinstance (RSA); Cipher Cipher = cipher.getinstance ("rsa/ecb/pkcs1padding"); Cipher.init (Cipher.decrypt_mode, PublicKey); return new String (Cipher.dofinal (EncryptedData));} catch (Exception e) {return null;}} /** * Public key is restored by public key byte[] (publickey.getencoded ()) for RSA algorithm * * @param keybytes * @return * @throws nosuchalgorithmexception * @throws invalidkeyspecexception */private static PublicKey Getpublickey (byte[] keybytes) throws Nosuchalgorithmexception,invalidkeyspecexception{x509encodedkeyspec KeySpec = new X509encodedkeyspec (keyBytes); Keyfactory keyfactory = keyfactory.getinstance (RSA); PublicKey PublicKey = Keyfactory.generatepublic (KeySpec); return publickey;} /** * The public key is restored by the private key byte[] for the RSA algorithm * * @param keybytes * @return * @throws nosuchalgorithmexception * @throws invalidkeyspece Xception */private static Privatekey Getprivatekey (byte[] keybytes) throws NoSuchAlgorithmException, Invalidkeyspecexception{pkcs8encodedkeyspec KeySpec = new Pkcs8enCodedkeyspec (keybytes); Keyfactory keyfactory = keyfactory.getinstance (RSA); Privatekey Privatekey = keyfactory.generateprivate (KeySpec); return privatekey;} /** * Use N, e value to restore public key * * @param modulus * @param publicexponent * @return * @throws nosuchalgorithmexception * @throws Invali Dkeyspecexception */private static PublicKey Getpublickey (string modulus, string publicexponent) throws NoSuchAlgorithmException, Invalidkeyspecexception{biginteger bigintmodulus = new BigInteger (modulus); BigInteger bigintprivateexponent = new BigInteger (publicexponent); Rsapublickeyspec KeySpec = new Rsapublickeyspec (Bigintmodulus, bigintprivateexponent); Keyfactory keyfactory = keyfactory.getinstance (RSA); PublicKey PublicKey = Keyfactory.generatepublic (KeySpec); return publickey;} /** * Use N, D value to restore private key * * @param modulus * @param privateexponent * @return * @throws nosuchalgorithmexception * @throws inval Idkeyspecexception */private static Privatekey Getprivatekey (string modulus, string privateexponent) throws NosuchalgoriThmexception, Invalidkeyspecexception{biginteger bigintmodulus = new BigInteger (modulus); BigInteger bigintprivateexponent = new BigInteger (privateexponent); Rsapublickeyspec KeySpec = new Rsapublickeyspec (Bigintmodulus, bigintprivateexponent); Keyfactory keyfactory = keyfactory.getinstance (RSA); Privatekey Privatekey = keyfactory.generateprivate (KeySpec); return privatekey;} /** * Load Public key from String * * @param publickeystr * Public Key Data String * @throws Exception * Exception generated when loading public key */private Stati C PublicKey Loadpublickey (String publickeystr) throws exception{try{byte[] buffer = Base64utils.decode (PUBLICKEYSTR); Keyfactory keyfactory = keyfactory.getinstance (RSA); X509encodedkeyspec KeySpec = new X509encodedkeyspec (buffer); return (Rsapublickey) keyfactory.generatepublic (KEYSPEC) ;} catch (NoSuchAlgorithmException e) {throw new Exception ("No This Algorithm"),} catch (Invalidkeyspecexception e) {throw new Exception ( "Public key is illegal");} catch (NullPointerException e) {throw new Exception ("Public key data is empty");}} /** * Loading the private key from a string <br> * PKCS8ENCODEDKEYSPEC (PKCS#8 encoded key instruction) is used when loading. * * @param privatekeystr * @return * @throws Exception */private static Privatekey Loadprivatekey (String privatekeystr) t Hrows exception{try{byte[] buffer = Base64utils.decode (PRIVATEKEYSTR);//X509encodedkeyspec KeySpec = new X509encodedkeyspec (buffer); Pkcs8encodedkeyspec KeySpec = new Pkcs8encodedkeyspec (buffer); Keyfactory keyfactory = keyfactory.getinstance (RSA); return (Rsaprivatekey) keyfactory.generateprivate (KEYSPEC);} catch (NoSuchAlgorithmException e) {throw new Exception ("No This Algorithm"),} catch (Invalidkeyspecexception e) {throw new Exception ( "Private key is illegal");} catch (NullPointerException e) {throw new Exception ("Private key data is empty");}} /** * Load public key from file input stream * * @param in * public key input stream * @throws Exception * Exception generated when loading public key */private static Publick EY Loadpublickey (InputStream in) throws Exception{try{return Loadpublickey (ReadKey (in))} catch (IOException e) {throw New Exception ("Public key data stream read error");} catch (NullPointerException e) {throw new Exception ("The public key input stream is empty");}}/** * Load private key from File * * @param keyfilename * Private key file name * @return Success * @throws Exception */private static Privatekey Loadprivatekey (InputStream in) throws Exception{try{return Loadprivatekey (ReadKey (in)),} catch (IOException e) {throw New Exception ("Private key Data read error");} catch (NullPointerException e) {throw new Exception ("The private key input stream is empty");}} /** * Read key information * * @param in * @return * @throws ioexception */private static String ReadKey (InputStream in) throws Ioexcep Tion{bufferedreader br = new BufferedReader (new InputStreamReader (in)); String readLine = null; StringBuilder sb = new StringBuilder (); while ((ReadLine = Br.readline ()) = null) {if (Readline.charat (0) = = '-') {continue; } else{sb.append (ReadLine); Sb.append (' \ R ');}} Br.close (); return sb.tostring ();} /** * Print Public key information * * @param publickey */private static void Printpublickeyinfo (PublicKey publickey) {Rsapublickey Rsapublickey = (Rsapublickey) PublicKey; System.out.println ("----------rsapublickey----------"); System.out.println ("modulus.length=" + rsapubliCkey.getmodulus (). Bitlength ()); System.out.println ("modulus=" + rsapublickey.getmodulus (). toString ()); System.out.println ("publicexponent.length=" + rsapublickey.getpublicexponent (). Bitlength ()); System.out.println ("publicexponent=" + rsapublickey.getpublicexponent (). toString ());} private static void Printprivatekeyinfo (Privatekey privatekey) {Rsaprivatekey Rsaprivatekey = (rsaprivatekey) Privatekey; System.out.println ("----------rsaprivatekey----------"); System.out.println ("modulus.length=" + rsaprivatekey.getmodulus (). Bitlength ()); System.out.println ("modulus=" + rsaprivatekey.getmodulus (). toString ()); System.out.println ("privateexponent.length=" + rsaprivatekey.getprivateexponent (). Bitlength ()); System.out.println ("privatecexponent=" + rsaprivatekey.getprivateexponent (). toString ());}}
Package Com.yagou.yggx.android.utils.rsa;import java.io.unsupportedencodingexception;/** * @author Mr.Zheng * @date August 22, 2014 PM 9:50:28 */class base64utils{private static char[] Base64encodechars = new char[]{' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ', ' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N ', ' O ', ' P ', ' Q ', ' R ', ' S ', ' T ', ' U ', ' V ', ' W ', ' X ', ' Y ', ' Z ', ' A ', ' B ', ' C ', ' d ', ' E ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n ', ' o ', ' P ', ' Q ', ' R ', ' s ', ' t ', ' u ', ' V ', ' w ', ' x ', ' y ', ' z ', ' 0 ', ' 1 ', ' 2 ' , ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' + ', '/'};p rivate static byte[] Base64decodechars = new byte[]{-1,-1,-1,-1,-1,- 1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1, 1,-1,-1,-1, 1,-1, -1,-1,-1,-1,-1,-1,-1, 62,-1,-1,-1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,-1,-1, 1, 1, 1 , 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,-1, 1,-1, 1, 1, 1, 26, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,-1, -1,-1,-1,-1};/** * Encryption * * @param data * @return */pub Lic static String encode (byte[] data) {StringBuffer SB = new StringBuffer (); int len = Data.length;int i = 0;int B1, B2, B3; while (I < len) {B1 = data[i++] & 0xff;if (i = = len) {sb.append (base64encodechars[b1 >>> 2]); Sb.append (base6 4encodechars[(B1 & 0x3) << 4]) sb.append ("= ="); B2 = data[i++] & 0xff;if (i = = len) {sb.append (base64encodechars[b1 >>> 2]); Sb.append (base64encodechars[( B1 & 0x03) << 4) | ((B2 & 0xf0) >>> 4)]); Sb.append (base64encodechars[(B2 & 0x0f) << 2]); Sb.append ("="); break;} B3 = data[i++] & 0xff;sb.append (BASE64ENCODECHARS[B1 >>> 2]); Sb.append (base64encodechars[(B1 & 0x03) << 4) | ((B2 & 0xf0) >>> 4)]); Sb.append (base64encodechars[(B2 & 0x0f) << 2) | ((B3 & 0xc0) >>> 6)]); Sb.append (Base64encodechars[b3 & 0x3f]);} ReTurn sb.tostring ();} /** * Decryption * * @param str * @return */public static byte[] decode (String str) {Try{return decodeprivate (str);} catch (Unsupp Ortedencodingexception e) {e.printstacktrace ();} return new byte[]{};} private static byte[] Decodeprivate (String str) throws Unsupportedencodingexception{stringbuffer SB = new StringBuffer () ; byte[] data = Null;data = Str.getbytes ("Us-ascii"); int len = Data.length;int i = 0;int B1, B2, B3, B4;while (i < len) { DO{B1 = base64decodechars[data[i++]];} while (I < len && B1 = =-1); if (B1 = =-1) break;do{b2 = Base64decodechars [data[i++];} while (i < len && B2 = =-1); if (B2 = =-1) break;sb.append ((char) ((B1 << 2) | ((B2 & 0x30) >>> 4))); DO{B3 = data[i++];if (B3 = =) return sb.tostring (). GetBytes ("iso8859-1"); b3 = Base64decodechars[b3];} while (I < Len & amp;& B3 = =-1); if (B3 = =-1) break;sb.append ((char) (((B2 & 0x0f) << 4) | ((B3 & 0x3c) >>> 2))); DO{B4 = data[i++];if (B4 = =) returnSb.tostring (). GetBytes ("iso8859-1"); b4 = base64decodechars[b4];} while (i < len && b4 = =-1), if (B4 = =-1) break;sb.append ((char) (((B3 & 0x03) << 6) | b4);} Return sb.tostring (). GetBytes ("Iso8859-1");}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android RSA encryption, adapter Javaweb