RSA bidirectional encryption

Source: Internet
Author: User

RSA is a two-way encryption algorithm, which is the first algorithm that can be used for both data encryption and digital signature. It is easy to understand and operate, and very popular. The name of the algorithm is named after the inventor: Ron Rivest, Adi Shamir and Leonard Adleman. However, the security of RSA has not been proved theoretically. It has gone through various attacks and has not been completely compromised so far.

The example code for this algorithm is as follows:

First, generate public and private keys

The public key can be publicly disclosed for other people to encrypt, and the private key is kept secret for decryption. The following program generates the public and private keys and stores them separately in the file.

Importjava.io.*;Importjava.security.*;Importjavax.crypto.*;Importjavax.crypto.spec.*; Public  class skey_rsa{    Public Static void Main(String args[])throwsexception{//Create key pair generator, specify encryption and decryption algorithm for RSAKeypairgenerator Kpg=keypairgenerator.getinstance ("RSA");//Specify the length of the key, initialize the key pair generatorKpg.initialize (1024x768);//Generate key pairKeyPair Kp=kpg.genkeypair ();//Get public keyPublicKey pbkey=kp.getpublic ();//Get private keyPrivatekey prkey=kp.getprivate ();//Save public key to fileFileOutputStream f1=NewFileOutputStream ("Skey_rsa_pub.dat"); ObjectOutputStream b1=NewObjectOutputStream (F1); B1.writeobject (Pbkey);//Save private key to fileFileOutputStream f2=NewFileOutputStream ("Skey_rsa_priv.dat"); ObjectOutputStream b2=NewObjectOutputStream (F2);   B2.writeobject (Prkey); }}

Second, using the RSA algorithm, with the public key to the plaintext encryption

 import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import java.security.interfaces.*; import java.math.*; import java.io.*; Public  class enc_rsa{    Public Static voidMain (String args[]) throws exception{//Clear text string that needs to be encryptedString s="Hello world!";//Read the public key from the fileFileInputStream f=NewFileInputStream ("Skey_rsa_pub.dat"); ObjectInputStream b=NewObjectInputStream (f); Rsapublickey pbk= (Rsapublickey) b.readobject ();The //RSA algorithm is encrypted using integers and contains two integer information in the RSA public key: E and N. For the clear-text number m, the formula for calculating ciphertext is M's e-quadratic and N-modulo. BigInteger e=pbk.getpublicexponent ();        BigInteger N=pbk.getmodulus (); System.out.println ("E="+E); System.out.println ("n="+N);//Get large integers in clear textByte Ptext[]=s.getbytes ("UTF8"); BigInteger m=NewBigInteger (Ptext);//Encrypt plaintextBigInteger C=m.modpow (e,n);//Print ciphertext CSystem.out.println ("c="+C);//Save ciphertext in a file as a stringString cs=c.tostring (); BufferedWriter out=NewBufferedWriter (NewOutputStreamWriter (NewFileOutputStream ("Enc_rsa.dat"))); Out.write (CS,0, Cs.length ());   Out.close (); }}

Third, using the RSA algorithm, with the private key to decrypt the ciphertext

 import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; import java.security.interfaces.*; import java.math.*; import java.io.*; Public  class dec_rsa{    Public Static voidMain (String args[]) throws exception{//Read ciphertextBufferedReaderinch=NewBufferedReader (NewInputStreamReader (NewFileInputStream ("Enc_rsa.dat"))); String ctext=inch. ReadLine (); BigInteger c=NewBigInteger (Ctext);//Get private keyFileInputStream f=NewFileInputStream ("Skey_rsa_priv.dat"); ObjectInputStream b=NewObjectInputStream (f); Rsaprivatekey prk= (Rsaprivatekey) b.readobject ();//Get the parameter of the private key D,nBigInteger d=prk.getprivateexponent ();        BigInteger N=prk.getmodulus (); System.out.println ("d="+D); System.out.println ("n="+N);//Decrypt plaintextBigInteger M=c.modpow (d,n); System.out.println ("m="+M);//Calculate the text corresponding to the string and output. Byte[] Mt=m.tobytearray (); System.out.println ("PlainText is"); for(int i=0; i<mt.length;i++) {System.out.print ((char) mt[i]); }   }}

The RSA algorithm is the first algorithm that can be used for both encryption and digital signature, and it is easy to understand and manipulate. RSA is the most widely researched public-key algorithm, from the proposed to now nearly 20 years, experienced a variety of attacks, gradually accepted by people, generally considered to be one of the best public key scheme at present. RSA's security relies on the factorization of large number of factors, but it does not theoretically prove that the difficulty of deciphering RSA is equivalent to the difficulty of large number decomposition. The major flaw of RSA is that it can't theoretically grasp its secrecy performance, and the majority of cryptography scholars tend to factor decomposition is not NPC problem. The disadvantages of RSA mainly include: a) it is troublesome to generate the key, which is limited by the technology of the prime number, so it is difficult to do it once. B) packet length is too large, in order to ensure security, n at least more than bits, so that the computational cost is very high, especially slow, more than symmetric cipher algorithm several orders of magnitude, and with the development of large number decomposition technology, this length is still increasing, not conducive to the standardization of data format. Currently, the SET (Secure Electronic Transaction) protocol requires a CA to use a key that is more than a strong key, and other entities using the bit's keys.

RSA bidirectional encryption

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.