Recently, in order to analyze a request flow, we have to study RSA encryption.
First, emphasize one thing: The key "key" reads "Yue", not "Yao", the amount ...
On the Internet on the principle of RSA catch a lot of, here is just a brief talk about my understanding:
1. Two large enough Inma p, q;
2. Die n=p*q for modulo operation;
3. E in Public key KU (e, n) satisfies 1<e< (p-1) (q-1) and is associated with (p-1) (q-1) coprime;
4. The d in the key KR (d, N) satisfies d*e% (p-1) (q-1) = 1,% is the take remainder operation.
Because the public key is public, so I know the E and N, then according to the relationship of 2,3,4, we only need to launch p from the value of N, the value of Q can calculate the value of D, we can find the key.
However, the key is here, N=p*q, if the two Inma p and Q is large enough, then according to the current computer technology and other tools, so far has not been able to decompose from N p and Q, this is a mathematical problem, it is this puzzle has become the RSA encryption is widely used today . In other words, as long as the key length n is large enough (typically 1024 feet), it is virtually impossible to eject the private key information from the public key information.
Well, here as a study of the essay, to record how Java is used, the following are mainly three ways, basically the same, just get the public key private key path is not the same:
Method One:
Using Keypairgenerator to generate public keys and keys directly, the general private key is reserved to the server, and the public key is given to the client.
public class Rsacryptography {public static String data= ' Hello World ';p ublic static void Main (string[] args) throws Except Ion {//TODO auto-generated method Stubkeypair Keypair=genkeypair (1024);//Get the public key and print it in base64 format PublicKey publickey= Keypair.getpublic (); SYSTEM.OUT.PRINTLN ("Public key:" +new String (Base64.getencoder (). Encode (publickey.getencoded ())));//Get the private key, and printed out in base64 format Privatekey privatekey=keypair.getprivate (); SYSTEM.OUT.PRINTLN ("Private key:" +new String (Base64.getencoder (). Encode (privatekey.getencoded ())));//Public key encryption byte[] Encryptedbytes=encrypt (Data.getbytes (), PublicKey); SYSTEM.OUT.PRINTLN ("Encrypted:" +new String (encryptedbytes));//private key decryption byte[] Decryptedbytes=decrypt (encryptedbytes, Privatekey); System.out.println ("After decryption:" +new String (Decryptedbytes));} Generate key pair public static KeyPair Genkeypair (int keylength) throws Exception{keypairgenerator keypairgenerator= Keypairgenerator.getinstance ("RSA"); Keypairgenerator.initialize (1024x768); return Keypairgenerator.generatekeypair () ;} Public key cryptography publicly static byte[] Encrypt (byte[] contENT, PublicKey publickey) throws Exception{cipher cipher=cipher.getinstance ("RSA");//java default "RSA" = "rsa/ecb/ Pkcs1padding "Cipher.init (Cipher.encrypt_mode, PublicKey); return cipher.dofinal (content);} Private key decryption public static byte[] Decrypt (byte[] content, Privatekey privatekey) throws Exception{cipher cipher= Cipher.getinstance ("RSA"); Cipher.init (Cipher.decrypt_mode, Privatekey); return cipher.dofinal (content);}}
Operation Result:
Method Two:
In fact, the method is only used to generate the key is OK, the generated key needs to be saved to a local file, so generally do not call Keypairgenerator in the client for key generation operations.
Here, we can save the method one obtained key to the file, next time we can read directly. I assume that the file is stored as a string, and then the key is generated directly using the string read to it.
Of course, you can also use OpenSSL to generate it, but I don't think it's a problem.
public class Rsacryptography {public static string data= ' Hello World ';p ublic static string publickeystring= " migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcislp98m/56hexx/9fdm8iuieqozy6kn2jmcbzs5/bhj+ u4pzichjfggylwnd8nwn4byr2kxxyo8qgvc8rprzckn0oslqlgzgmnvosldw80uxq90zsvhdtohusfhw8bv// B4evunjbb8g9tpvxr6p5ej6fmor/ky2dvfqcqm4+5qidaqab ";p ublic static String privatekeystring=" miicdqibadanbgkqhkig9w0baqefaascal8wggjbageaaogbaihis/3wz/nod7ff/0umzyk4grcjplqsfykxxtlln8gen5tg9kgkel+ cbivad3w1afgfivathhi7xcc9zyulfkkq3q5iuoubkay2+hkupdzrrer3rmxucnm4e5iufdwg//8hh69q0kehyd22lxgvo/kqnouyhh+ rjz1uvajazj7lagmbaaecgyavh26vsggy0yl/asw/qztzn837w93hf3cvyiaokxlerl/lvbjz5otshq09f2iaxbfedfmy5cb9r0w/ aly851jxri8wakx2w2fnllzhha01fmlnlosumoirf++jcbsajdcrciir8esvnub6ymbcrx/fqhdx3+t/ vubsafxyt9tsgqjbalshurnovzs1qjctl6pkns0v5qio88szyp7lzgq0eyglvfupdllx8/ mrsdi4dhermtcutucatzgqu20uai0emyecqqc6il1kdkw8peeb0jzmhbs+cmcsbgatiat4pfo1b/i9/ bo0qnrgdqycjt3j9ux22dpybdpdtmjmrnrakfb4bjdfakbmrdwtzovc88il2mcc98sjcii5wdl3yseyozto7icmzuh/zlfzm5ctslq8/hdiqvarnj4jwzia/q6fg6e8ko2hakb0ek1vlf/ ox7e5gkk533hmuu8xgwn6i5bhnbyd06qyqytbbthmbrfsay4uh91qwd3u9gawqoczognft/o03v5lakbqq8jzd2lhifey+ 9cf1hshd5wqbjjkppib57ck08hn7vulx5epj02q8ahdzketaw+esqjwpngsu5wpqsy2uyno ";p ublic static void Main (String[] args) Throws Exception {//TODO auto-generated method stub//get public key PublicKey Publickey=getpublickey (publickeystring);//Get private key Privatekey Privatekey=getprivatekey (privatekeystring);//Public key encryption byte[] Encryptedbytes=encrypt (Data.getBytes (), PublicKey); SYSTEM.OUT.PRINTLN ("Encrypted:" +new String (encryptedbytes));//private key decryption byte[] Decryptedbytes=decrypt (encryptedbytes, Privatekey); System.out.println ("After decryption:" +new String (Decryptedbytes));} Convert the Base64 encoded public key string into a PublicKey instance of the publicly static PublicKey Getpublickey (String publickey) throws exception{byte[] Keybytes=base64.getdecoder (). Decode (Publickey.getbytes ()); X509encodedkeyspec keyspec=new X509encodedkeyspec (keybytes); Keyfactory keyfactory=keyfactory.getinstance ("RSA"); return Keyfactory.generatepublic (KEYSPEC);} The Base64 encoded private key string is transferred toPrivatekey instance public static Privatekey Getprivatekey (String privatekey) throws exception{byte[] Keybytes= Base64.getdecoder (). Decode (Privatekey.getbytes ()); Pkcs8encodedkeyspec keyspec=new Pkcs8encodedkeyspec (keybytes); Keyfactory keyfactory=keyfactory.getinstance ("RSA"); return Keyfactory.generateprivate (KEYSPEC);} Public key cryptography publicly static byte[] encrypt (byte[] content, PublicKey publickey) throws Exception{cipher cipher= Cipher.getinstance ("RSA");//java default "RSA" = "rsa/ecb/pkcs1padding" Cipher.init (Cipher.encrypt_mode, PublicKey); return cipher.dofinal (content);} Private key decryption public static byte[] Decrypt (byte[] content, Privatekey privatekey) throws Exception{cipher cipher= Cipher.getinstance ("RSA"); Cipher.init (Cipher.decrypt_mode, Privatekey); return cipher.dofinal (content);}}Operation Result:
Method Three:
In addition to saving the key string, it is common practice to save only modulo n (modulus), and E and D (exponent) of the public and private keys.
where N, E, D can be obtained, and obtained can be saved to a local file.
Get public key Rsapublickey publickey= (Rsapublickey) Getpublickey (publickeystring); BigInteger Modulus1=publickey.getmodulus (); BigInteger exponent1=publickey.getpublicexponent ();//Get private key Rsaprivatekey privatekey= (Rsaprivatekey) Getprivatekey ( privatekeystring); BigInteger Modulus2=privatekey.getmodulus (); BigInteger Exponent2=privatekey. Getprivateexponent ();
Here, let's say I've read modulus and exponent from the file:
public class Rsacryptography {public static string data= ' Hello World ';p ublic static string modulusstring= " 9570187688533527085782297416757716876462121140634157447781777890879840885607733451049651521156883984388449888158928044076 3139683446418982307428928523091367233376499779842840789220784202847513854967218444344438545354682865713417516385450114501 727182277555013890267914809715178404671863643421619292274848317157 ";p ublic static String publicexponentstring=" 65537 ";p ublic static String privateexponentstring=" 1511820088490281915850651161262991025253098862764322932952145299667042932827210040415597940072588307221472171324738423185 7130859555987849975263007110480563992945828011871526769689381461965107692102011772019212674436519765580328720044447875477 151172925640047963361834004267745612848169871802590337012858580097 ";p ublic static void Main (string[] args) throws Exception {//TODO auto-generated method stub//by N and e get public key PublicKey Publickey=getpublickey (modulusstring, publicexponentstring);//by N and D for privateKey Privatekey Privatekey=getprivatekey (modulusstring, privateexponentstring);//Public key encryption byte[] Encryptedbytes=encrypt ( Data.getbytes (), PublicKey); SYSTEM.OUT.PRINTLN ("Encrypted:" +new String (encryptedbytes));//private key decryption byte[] Decryptedbytes=decrypt (encryptedbytes, Privatekey); System.out.println ("After decryption:" +new String (Decryptedbytes));} Convert the Base64 encoded public key string into a PublicKey instance of the publicly static PublicKey Getpublickey (String modulusstr, String exponentstr) throws Exception{biginteger modulus=new BigInteger (MODULUSSTR); BigInteger exponent=new BigInteger (EXPONENTSTR); Rsapublickeyspec publickeyspec=new Rsapublickeyspec (modulus, exponent); Keyfactory keyfactory=keyfactory.getinstance ("RSA"); return Keyfactory.generatepublic (PUBLICKEYSPEC);} Convert Base64 encoded private key string to Privatekey instance public static Privatekey Getprivatekey (String modulusstr, String exponentstr) throws Exception{biginteger modulus=new BigInteger (MODULUSSTR); BigInteger exponent=new BigInteger (EXPONENTSTR); Rsaprivatekeyspec privatekeyspec=new Rsaprivatekeyspec (modulus, exponent); KeyFactory keyfactory=keyfactory.getinstance ("RSA"); return Keyfactory.generateprivate (PRIVATEKEYSPEC);} Public key cryptography publicly static byte[] encrypt (byte[] content, PublicKey publickey) throws Exception{cipher cipher= Cipher.getinstance ("RSA");//java default "RSA" = "rsa/ecb/pkcs1padding" Cipher.init (Cipher.encrypt_mode, PublicKey); return cipher.dofinal (content);} Private key decryption public static byte[] Decrypt (byte[] content, Privatekey privatekey) throws Exception{cipher cipher= Cipher.getinstance ("RSA"); Cipher.init (Cipher.decrypt_mode, Privatekey); return cipher.dofinal (content);}}Operation Result:
Here are three ways to sum up, which is
1,. Keypairgenerator get key;
2. String gets key;
3. Modulus and exponent get key.
However, when the encrypted data is too long, you need to
RSA use of Java encryption and decryption