Java generates RSA asymmetric cryptographic public and private keys (leveraging the Java API)

Source: Internet
Author: User
Tags decrypt asymmetric encryption

Asymmetric encryption is very suitable for multiple client and server secret communication, the client uses the same public key will be plaintext encryption, and this public key can not reverse the decryption, ciphertext sent to the server after the server side with the private key decryption, so that the plaintext encrypted transmission.

Asymmetric encryption also has its innate shortcomings, encryption, decryption slow restrictions on its play, if you have a large number of text need to encrypt the transmission, it is recommended that you use asymmetric encryption to the symmetric ' key ' distribution to the client, timely update the symmetric ' key '.

 PackageCom.paul.module.common.util;ImportSun.misc.BASE64Decoder;ImportSun.misc.BASE64Encoder;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportJava.security.Key;ImportJava.security.KeyPair;ImportJava.security.KeyPairGenerator;ImportJavax.crypto.Cipher; Public classRSASECURITYUTIL2 {/**specifies that the encryption algorithm is RSA*/    Private Static FinalString algorithm = "RSA"; /**Key length, used to initialize*/    Private Static Final intKEYSIZE = 1024; /**Specify the public key to store the file*/    Private StaticString public_key_file = "PublicKey"; /**Specify the private key to store the file*/    Private StaticString private_key_file = "Privatekey"; /*** Generate key pair *@throwsException*/    Private Static voidGeneratekeypair ()throwsException {//the/** RSA algorithm requires a trustworthy random number source * ///securerandom securerandom = new SecureRandom ();                /**Create a Keypairgenerator object for the RSA algorithm*/Keypairgenerator Keypairgenerator=keypairgenerator.getinstance (algorithm); /**Initialize the Keypairgenerator object with the above random data source*///keypairgenerator.initialize (KEYSIZE, securerandom);keypairgenerator.initialize (KEYSIZE); /**generate key Pair*/KeyPair KeyPair=Keypairgenerator.generatekeypair (); /**get the public key*/Key PublicKey=keypair.getpublic (); /**get the private key*/Key Privatekey=keypair.getprivate (); ObjectOutputStream OOS1=NULL; ObjectOutputStream Oos2=NULL; Try {            /**writes the generated key to the file with the object stream*/OOS1=NewObjectOutputStream (NewFileOutputStream (public_key_file)); Oos2=NewObjectOutputStream (NewFileOutputStream (private_key_file));            Oos1.writeobject (PublicKey);        Oos2.writeobject (Privatekey); } Catch(Exception e) {Throwe; }        finally{            /**empty the cache, close the file output stream*/Oos1.close ();        Oos2.close (); }    }    /*** Encryption Method *@paramSource Data *@return     * @throwsException*/     Public StaticString Encrypt (string source)throwsException {generatekeypair ();        Key PublicKey; ObjectInputStream Ois=NULL; Try {            /**to read a public key object in a file*/Ois=NewObjectInputStream (NewFileInputStream (public_key_file)); PublicKey=(Key) ois.readobject (); } Catch(Exception e) {Throwe; }        finally{ois.close (); }                /**get the Cipher object to implement RSA encryption of the source data*/Cipher Cipher=cipher.getinstance (algorithm);        Cipher.init (Cipher.encrypt_mode, PublicKey); byte[] B =source.getbytes (); /**Performing Cryptographic Operations*/        byte[] B1 =cipher.dofinal (b); Base64encoder Encoder=NewBase64encoder (); returnEncoder.encode (B1); }    /*** Decryption Algorithm *@paramcryptograph Ciphertext *@return     * @throwsException*/     Public StaticString Decrypt (String cryptograph)throwsException {Key privatekey; ObjectInputStream Ois=NULL; Try {            /**to read a private key object in a file*/Ois=NewObjectInputStream (NewFileInputStream (private_key_file)); Privatekey=(Key) ois.readobject (); } Catch(Exception e) {Throwe; }        finally{ois.close (); }                /**get Cipher object to RSA decryption of data encrypted with public key*/Cipher Cipher=cipher.getinstance (algorithm);        Cipher.init (Cipher.decrypt_mode, Privatekey); Base64decoder Decoder=NewBase64decoder (); byte[] B1 =Decoder.decodebuffer (cryptograph); /**perform a decryption operation*/        byte[] B =cipher.dofinal (B1); return NewString (b); }     Public Static voidMain (string[] args)throwsException {String source= "Congratulations on getting rich!";//the string to encryptSYSTEM.OUT.PRINTLN ("Prepare the string to be encrypted with the public key:" +source); String cryptograph= Encrypt (source);//generated ciphertextSystem.out.print ("The result of encrypting with public key is:" +cryptograph);        System.out.println (); String Target= Decrypt (cryptograph);//Decryption TextSystem.out.println ("The string after decrypting with the private key is:" +target);    System.out.println (); }}

Http://blog.sina.com.cn/s/blog_43b03c72010080t2.html
Http://topic.csdn.net/t/20040510/14/3049788.html
http://yuanliyin.iteye.com/blog/853334

Java generates RSA asymmetric cryptographic public and private keys (leveraging the Java API)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.