Examples of RSA asymmetric key and decryption using in Java

Source: Internet
Author: User
Tags base64 key string md5 encryption modulus asymmetric encryption

First, the introduction: RSA encryption algorithm is the most commonly used asymmetric encryption algorithm, CFCA in the certificate service cannot leave it. RSA is the first more sophisticated public key algorithm that can be used for both encryption and digital signatures. This algorithm has withstood many years of in-depth password analysis, although the password analyst can neither prove nor deny the security of RSA, but this just shows that the algorithm has some credibility, it has become the most popular public key algorithm.

Second, the RSA public key, the private key composition, as well as the encryption, the decryption formula can be seen in the following table

Third, the mode of use:

① assumes A, B machine to communicate, has a machine-based;

②a first needs to use its own private key to send the request data signature, and sends the public key together to B;

③b receive the data, you need to use a to send the public key to verify, has ensured that the received data is not tampered with;

④b after the verification pass, processing logic, and return the processing results, the return data needs to be sent by a public key to encrypt (public key encryption, only with the paired private key decryption);

⑤a receives the data returned by B, decrypts it with the private key, and completes the data interaction at this point.

Four, code example:

    1. The first step is to get the private key and prepare for the signature.
      /*** Read private key back Privatekey *@paramPath contains the certificate paths for the private key *@paramPassword private key Certificate password *@returnreturn private Key Privatekey *@throwsKeystoreexception *@throwsNoSuchAlgorithmException *@throwsCertificateexception *@throwsIOException *@throwsUnrecoverablekeyexception*/PrivateStaticPrivatekey getprivatekey (String path,string password)ThrowsKeystoreexception, NoSuchAlgorithmException, Certificateexception, IOException, unrecoverablekeyexception {KeyStore KS = Keystore.getinstance ("PKCS12"); FileInputStream FIS =NewFileInputStream (path);char[] Npassword =Nullif ((password = = null) | | Password.trim (). Equals ("" Span style= "color: #000000;" ) {Npassword = null;} else {Npassword = ks.aliases (); String Keyalias = nullif (En.hasmoreelements ()) {Keyalias = (String) en.nextelement (); } return (Privatekey) Ks.getkey (Keyalias, Npassword);}  

    2. The signature sample is signed using the private key obtained in the first step, which is the following code:
      /*** Private key Signature: The signature method is as follows: BASE64 (RSA (MD5 (SRC), privatekey)), where Src is a string that needs to be signed, Privatekey is the private key of the merchant's CFCA certificate. *@paramPlainText string to be signed *@paramPath signature private key Paths *@paramPassword signing private key password *@returnReturns the string after the signature *@throwsException*/PublicStaticString sign (string plaintext,string path,string password)ThrowsException {/** MD5 Encryption*/MessageDigest MD5 = messagedigest.getinstance ("MD5"); Md5.update (Plaintext.getbytes ("Utf-8")); Md5.digest (); /* * signing with the private key RSA * Cipher is responsible for completing the encryption or decryption work, based on the RSA */ Cipher Cipher = cipher.getinstance ("rsa/ecb/pkcs1padding" ); //encrypt_mode is represented as an encryption mode  Cipher.init (cipher.encrypt_ MODE, Getprivatekey (path, password)); // encrypt byte["Rsabytes =< Span style= "color: #000000;" > cipher.dofinal (digestbytes); //return Base64.bytearraytobase64 (rsabytes);  

    3. b After receiving the data, you need to use the public key information provided by a for verification, here using the public key of N, E for verification first by public key N, E to get the public key PublicKey, as follows:

      /*** Generate public key based on public key N, E *@paramModulus public key N String *@paramPublicexponent Public key E String *@returnReturn Public Key PublicKey * @throws  Exception */ Span style= "color: #0000ff;" >public static PublicKey Getpublickkey (String modulus, String publicexponent) throws Exception {KeySpec Publickeyspec = new Rsapublickeyspec (new BigInteger (modulus, +), new BigInteger (publicexponent, 16)); Keyfactory factory = keyfactory.getinstance ("RSA" ); PublicKey publickey = Factory.generatepublic (PUBLICKEYSPEC); return PublicKey;}      

      After getting the public key publickey, then verify the signature, the code is as follows:

      /*** Check with a public key certificate *@paramText before message signature *@paramCiphertext Signature *@paramPubkeyn public Key N String *@paramPubkeye Public key E String *@returnBoolean verification succeeds to true, failure is false *@throwsException*/PublicStaticBooleanVerify (String message, String ciphertext,string Pubkeyn, String pubkeye)ThrowsException {Cipher C4 = cipher.getinstance ("rsa/ecb/pkcs1padding");//Initializes the cipher object according to the key, Decrypt_mode represents the decryption modeC4.init (Cipher.decrypt_mode, Getpublickkey (Pubkeyn,pubkeye));//Decryptbyte[] Desdectextbytes =C4.dofinal (Base64.base64tobytearray (ciphertext));//Gets the MD5 String Md5digest1 of the predecessor to the original text =Base64.bytearraytobase64 (desdectextbytes); MessageDigest MD5 = messagedigest.getinstance ("MD5"); Md5.update (Message.getbytes ("Utf-8")); byte[] digestbytes = md5.digest (); // MD5 String md5digest2 = base64.bytearraytobase64 (digestbytes) from the merchant to the original text; // Verify signature if (Md5digest1.equals (md5digest2)) { return true;} else { return false;}}            

      So far, signature verification is complete.

    4. Provides a way to read a public key from a. cer file:
      /*** Read Public key CER *@paramPath. cer file paths such as: C:/abc.cer *@returnBase64 after the public key string *@throwsIOException *@throwsCertificateexception*/Publicstatic string Getpublickey (string path) throws IOException, certificateexception{inputstream instream = new FileInputStream (path); Bytearrayoutputstream out = new Bytearrayoutputstream ( ); int ch; String res = "" ; while ((ch = instream.read ())! = -1) {out.write (ch);} Span style= "color: #0000ff;" >byte[] result = Out.tobytearray (); Res =return res;}       

    5. Enclosed All code: http://pan.baidu.com/share/link?shareid=23044&uk=2986731784
      This article transferred from: http://www.huosen.net/archives/124.html

Examples of RSA asymmetric key and decryption using in Java

Related Article

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.