Java RSA Public key cryptography, private key decryption algorithm example

Source: Internet
Author: User
Tags asymmetric encryption


"Asymmetric Encryption Algorithm".
(1) Party B generates two keys (public key and private key). The public key is public and available to anyone, and the private key is kept secret.
(2) Party A obtains Party B's public key, and then uses it to encrypt the information.
(3) Party B obtains the encrypted information and decrypts it with the private key.
If the information encrypted by the public key can only be unlocked by the private key, as long as the private key is not leaked, communication is secure. The public key is used for encryption, and the private key is used for decryption.

RSA is an asymmetric encryption algorithm that is generally difficult to crack, so some systems with higher requirements usually use the RSA encryption algorithm. Generally speaking, RSA encryption has the following steps.
1. Generate public and private keys
2. Use the public key to encrypt the character string that needs to be encrypted, etc.
3. Where needed, use the private key for decryption
The following sections post the code.

1. Generate public and private keys



Java code Copy code Favorite code
1.package com.rsa;
2.import java.io.FileOutputStream;
3.import java.security.KeyPair;
4.import java.security.KeyPairGenerator;
5.import java.security.SecureRandom;
6.import java.util.Date;
7.
8.public class GenKeys {
9. public static void main (String [] args) throws Exception {
10. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance ("RSA");
11. SecureRandom secureRandom = new SecureRandom (new Date (). ToString (). GetBytes ());
KeyPairGenerator.initialize (1024, secureRandom);
13. KeyPair keyPair = keyPairGenerator.genKeyPair ();
14. String publicKeyFilename = "D: / publicKeyFile";
15. byte [] publicKeyBytes = keyPair.getPublic (). GetEncoded ();
16. FileOutputStream fos = new FileOutputStream (publicKeyFilename);
17.fos.write (publicKeyBytes);
18. fos.close ();
19. String privateKeyFilename = "D: / privateKeyFile";
20. byte [] privateKeyBytes = keyPair.getPrivate (). GetEncoded ();
21.fos = new FileOutputStream (privateKeyFilename);
22.fos.write (privateKeyBytes);
23. fos.close ();
twenty four.    }  
25.}





2. Read public key method



Java code Copy code Favorite code
1.package com.rsa;
2.  
3.import java.io.DataInputStream;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.security.PublicKey;
7.import java.security.spec.X509EncodedKeySpec;
8.import java.security.KeyFactory;
9.  
10.public class PublicKeyReader {
11. public static PublicKey get (String filename) throws Exception {
12. File f = new File (filename);
13. FileInputStream fis = new FileInputStream (f);
14. DataInputStream dis = new DataInputStream (fis);
15. byte [] keyBytes = new byte [(int) f.length ()];
16. dis.readFully (keyBytes);
17. dis.close ();
18. X509EncodedKeySpec spec = new X509EncodedKeySpec (keyBytes);
19. KeyFactory kf = KeyFactory.getInstance ("RSA");
20. return kf.generatePublic (spec);
twenty one.    }  
twenty two.  
twenty three.  
twenty four.}  






3. Read private key method



Java code Copy code Favorite code
1.package com.rsa;
2.  
3.import java.io.DataInputStream;
4.import java.io.File;
5.import java.io.FileInputStream;
6.import java.io.IOException;
7.import java.security.KeyFactory;
8.import java.security.PrivateKey;
9.import java.security.spec.InvalidKeySpecException;
10.import java.security.spec.PKCS8EncodedKeySpec;
11.public class PrivateKeyReader {
12. public static PrivateKey get (String filename) throws Exception {
13. File f = new File (filename);
14. FileInputStream fis = new FileInputStream (f);
15. DataInputStream dis = new DataInputStream (fis);
16. byte [] keyBytes = new byte [(int) f.length ()];
17. dis.readFully (keyBytes);
18. dis.close ();
19. PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec (keyBytes);
20. KeyFactory kf = KeyFactory.getInstance ("RSA");
21. return kf.generatePrivate (spec);
twenty two.      }  
twenty three.  
twenty four.      
25. public static void main (String [] args) throws Exception, InvalidKeySpecException, IOException {
26. PrivateKeyReader.get ("d: / privateKeyFile");
27.}
28.}






4. Test public key encryption and private key decryption




Java code Copy code Favorite code
1.package com.rsa;
2.  
3.import java.security.interfaces.RSAPrivateKey;
4.import java.security.interfaces.RSAPublicKey;
5.import javax.crypto.Cipher;
6.
7.public class TestEncryptAndDecrypt {
8. public static void main (String [] args) throws Exception {
9. String input = "thisIsMyPassword $ 7788";
10. Cipher cipher = Cipher.getInstance ("RSA");
11. RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get ("d: / publicKeyFile");
12. RSAPrivateKey privKey = (RSAPrivateKey) PrivateKeyReader.get ("d: / privateKeyFile");
13. cipher.init (Cipher.ENCRYPT_MODE, pubKey);
14. byte [] cipherText = cipher.doFinal (input.getBytes ());
15. // Encrypted stuff
16. System.out.println ("cipher:" + new String (cipherText));
17. // Start decryption
18. cipher.init (Cipher.DECRYPT_MODE, privKey);
19. byte [] plainText = cipher.doFinal (cipherText);
20. System.out.println ("plain:" + new String (plainText));
twenty one.    }  
twenty two.  
twenty three.}  






View Results: 

Program code program code


cipher: J ???
? nE?? J? b9 ?? CO?? I ??? g [B {? w ?? u0 ????}? r6
? Q?? X a ??????? N} n?]? @ ?? _ 9! D?? _? | K ?? & g? ^ ???? XTa $? 7 ?? *? {7? R ??? v? S
plain: thisIsMyPassword $ 7788




The encryption and decryption are successful.

Remarks, only the test method is recorded here. Of course, in actual use, you may need to use base64 encoding for the encrypted byte [] and convert it to a string for storage. When decrypting, first restore it to byte through base64, and then In decryption, this would be better. Detailed method, 


get "" Java background Framework SPRINGMVC Integration MyBatis Framework source bootstrap HTML5 MySQL Oracle



Java RSA Public key cryptography, private key decryption algorithm example


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.