RSA in the Java encryption and decryption technology series

Source: Internet
Author: User


Order
The distance from the last blog feel has been a long time, first spit groove, this month, the company has been working overtime, but also hair version, on-line, but also the new project is too tight, the specific will not say, want to listen to my little friend spit groove, you can send me a private messages (*^__^*). In the previous article, the symmetric encryption algorithm has been finished. From today onwards, we have to say asymmetric encryption. Because, asymmetric encryption is really too important, our daily life, can not be separated from asymmetric encryption.
Concept
Before you talk about RSA, first talk about what is asymmetric encryption. When it comes to symmetric encryption, it has been said that symmetric encryption algorithms use the same secret key when encrypting and decrypting, and that both parties must use the same key for normal communication. Instead of symmetric encryption, an asymmetric encryption algorithm requires two keys for encryption and decryption, respectively, public and private.
It should be noted that this public and private key must be a pair, and if the data is encrypted with the public key, then only the corresponding private key can be decrypted, and vice versa. Because encryption and decryption use two different keys, the algorithm is called an asymmetric encryption algorithm.

Work process
For example, the transmission of data between A and B using asymmetric encryption.
    • Party B generates a pair of keys (public and private) and exposes the public key to other parties;
    • The party that obtains the public key uses the key to encrypt the confidential information and sends it to party B;
    • Party B then use the other private key (private key) to decrypt the encrypted information;
    • Party B can only use its private key (private key) to decrypt the information encrypted by the corresponding public key;
    • In the transmission process, even if the attacker intercepts the transmitted ciphertext and obtains the public key of B, the ciphertext cannot be cracked, because only the private key of B can decrypt the text.



The main algorithms used in asymmetric cryptography are: RSA, Elgamal, knapsack algorithm, Rabin, D-h, ECC (elliptic curve encryption algorithm), etc. Today is mainly about RSA, as for other algorithms, follow-up will choose a few to introduce.

Rsa
In fact, in the early 1978, RSA has emerged, it is the first one can be used for both data encryption and digital Signature algorithm. It is easy to understand and operate, and very popular. The principle is as described in the working procedure above.
The RSA algorithm is based on a very simple number theory fact: it is easy to multiply two large primes, but it is extremely difficult to factorization the product, so you can expose the product as an encryption key.

Code implementation
Here's a look at the specific code implementation.
<span style= "Font-family:comic Sans ms;font-size:12px;" >package Com.test.rsa;import Com.google.common.collect.maps;import Sun.misc.base64decoder;import Sun.misc.base64encoder;import Javax.crypto.cipher;import Java.security.*;import Java.security.interfaces.rsaprivatekey;import Java.security.interfaces.rsapublickey;import Java.security.spec.pkcs8encodedkeyspec;import Java.security.spec.x509encodedkeyspec;import java.util.Map;/** * Created by Xiang.li on 2015/3/3.    * RSA decryption Tool Class */public class RSA {/** * defines the encryption method */Private final static String Key_rsa = "RSA";    /** * Define Signature Algorithm */private final static String key_rsa_signature = "Md5withrsa";    /** * Define public key algorithm */private final static String Key_rsa_publickey = "Rsapublickey";    /** * Defines the private key algorithm */private final static String Key_rsa_privatekey = "Rsaprivatekey"; /** * Initialize key * @return */public static map<string, object> init () {map<string, object> Map = null;        try {keypairgenerator generator = keypairgenerator.getinstance (KEY_RSA);            Generator.initialize (1024);            KeyPair KeyPair = Generator.generatekeypair ();            Public key Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();            Private key Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();            Encapsulate the key as map map = Maps.newhashmap ();            Map.put (Key_rsa_publickey, PublicKey);        Map.put (Key_rsa_privatekey, Privatekey);        } catch (NoSuchAlgorithmException e) {e.printstacktrace ();    } return map;  /** * Digitally sign information with the private key * @param data encryption * @param privatekey private key * @return */public static String        Sign (byte[] data, String privatekey) {string str = "";            try {//Decrypt the private key encoded by base64 byte[] bytes = decryptBase64 (Privatekey); Constructs a Pkcs8encodedkeyspec object Pkcs8encodedkeyspec PKCS =New Pkcs8encodedkeyspec (bytes);            The specified cryptographic algorithm keyfactory factory = keyfactory.getinstance (Key_rsa);            Take the private key object Privatekey key = Factory.generateprivate (PKCS);            Generate digital signatures for information with the private key Signature Signature = Signature.getinstance (key_rsa_signature);            Signature.initsign (key);            Signature.update (data);        str = encryptBase64 (Signature.sign ());        } catch (Exception e) {e.printstacktrace ();    } return str; }/** * Verify digital signature * @param data encryption * @param publickey Public key * @param sign Digital signature * @return Verify Success Returns True, failed to return        False */public static Boolean verify (byte[] data, string publickey, String sign) {Boolean flag = false;            try {//Decrypt the public key encoded by base64 byte[] bytes = decryptBase64 (PublicKey);            Constructs the X509encodedkeyspec object X509encodedkeyspec keySpec = new X509encodedkeyspec (bytes); The specified cryptographic algorithm keyfactOry factory = keyfactory.getinstance (Key_rsa);            Take public Key object PublicKey key = Factory.generatepublic (KEYSPEC);            Verify the digital signature with the public key Signature Signature = Signature.getinstance (key_rsa_signature);            Signature.initverify (key);            Signature.update (data);        Flag = signature.verify (decryptBase64 (sign));        } catch (Exception e) {e.printstacktrace ();    } return flag; /** * Private Key decryption * @param data encryption * @param key Private key * @return */public static byte[] Decryptbypriva        Tekey (byte[] data, String key) {byte[] result = NULL;            try {//Decrypt the private key byte[] bytes = decryptBase64 (key);            Obtain the private key pkcs8encodedkeyspec KeySpec = new Pkcs8encodedkeyspec (bytes);            Keyfactory factory = keyfactory.getinstance (Key_rsa);            Privatekey Privatekey = factory.generateprivate (KeySpec); Decryption of data Cipher Cipher = Cipher.getinsTance (Factory.getalgorithm ());            Cipher.init (Cipher.decrypt_mode, Privatekey);        result = cipher.dofinal (data);        } catch (Exception e) {e.printstacktrace ();    } return result; }/** * Private key decryption * @param data encryption * @param key Public key * @return * * byte[] Decryptbypubli        Ckey (byte[] data, String key) {byte[] result = NULL;            try {//Decrypt the public key byte[] bytes = decryptBase64 (key);            Get the public key x509encodedkeyspec KeySpec = new X509encodedkeyspec (bytes);            Keyfactory factory = keyfactory.getinstance (Key_rsa);            PublicKey PublicKey = Factory.generatepublic (KeySpec);            Decrypt the data Cipher Cipher = Cipher.getinstance (Factory.getalgorithm ());            Cipher.init (Cipher.decrypt_mode, PublicKey);        result = cipher.dofinal (data);        } catch (Exception e) {e.printstacktrace ();    } return result;   } /** * Public Key encryption * @param data to be encrypted * @param key Public key * @return */publicly static byte[] Encryptbypublicke        Y (byte[] data, String key) {byte[] result = NULL;            try {byte[] bytes = decryptBase64 (key);            Get the public key x509encodedkeyspec KeySpec = new X509encodedkeyspec (bytes);            Keyfactory factory = keyfactory.getinstance (Key_rsa);            PublicKey PublicKey = Factory.generatepublic (KeySpec);            Encrypt the data Cipher Cipher = Cipher.getinstance (Factory.getalgorithm ());            Cipher.init (Cipher.encrypt_mode, PublicKey);        result = cipher.dofinal (data);        } catch (Exception e) {e.printstacktrace ();    } return result; /** * Private key encryption * @param data to be encrypted * @param key Private key * @return */public static byte[] Encryptbypriv        Atekey (byte[] data, String key) {byte[] result = NULL;           try {byte[] bytes = decryptBase64 (key); Obtain the private key pkcs8encodedkeyspec KeySpec = new Pkcs8encodedkeyspec (bytes);            Keyfactory factory = keyfactory.getinstance (Key_rsa);            Privatekey Privatekey = factory.generateprivate (KeySpec);            Encrypt the data Cipher Cipher = Cipher.getinstance (Factory.getalgorithm ());            Cipher.init (Cipher.encrypt_mode, Privatekey);        result = cipher.dofinal (data);        } catch (Exception e) {e.printstacktrace ();    } return result; }/** * Gets the public key * @param map * @return * * * static String Getpublickey (map<string, object> m        AP) {String str = "";            try {Key key = (Key) map.get (Key_rsa_publickey);        str = encryptBase64 (key.getencoded ());        } catch (Exception e) {e.printstacktrace ();    } return str; /** * Get private key * @param map * @return */public static String Getprivatekey (map<string, object>     MAP) {   String str = "";            try {Key key = (Key) map.get (Key_rsa_privatekey);        str = encryptBase64 (key.getencoded ());        } catch (Exception e) {e.printstacktrace ();    } return str; }/** * BASE64 decryption * @param key The string to decrypt * @return byte array * @throws Exception */public static Byte    [] decryptBase64 (String key) throws Exception {return (new Base64decoder ()). Decodebuffer (key); }/** * BASE64 encryption * @param key required to encrypt byte array * @return String * @throws Exception */public static Stri    Ng EncryptBase64 (byte[] key) throws Exception {return (new Base64encoder ()). Encodebuffer (key);        }/** * Test method * @param args */public static void main (string[] args) {String privatekey = "";        String PublicKey = "";        Generate public key map<string, object> Map = init ();        PublicKey = Getpublickey (map);        Privatekey = Getprivatekey (map); System.out.pRINTLN ("Public key: \n\r" + publickey);        SYSTEM.OUT.PRINTLN ("Private key: \n\r" + privatekey);        SYSTEM.OUT.PRINTLN ("Public Key cryptography--------private Key Decryption"); String word = "Hello, world!"        ";        byte[] Encword = Encryptbypublickey (Word.getbytes (), PublicKey);        String Decword = new String (Decryptbyprivatekey (Encword, Privatekey));        System.out.println ("Before encryption:" + Word + "\n\r" + "decrypted after:" + Decword);        SYSTEM.OUT.PRINTLN ("Private key encryption--------public key decryption");        String 中文版 = "Hello, world!";        byte[] Encenglish = Encryptbyprivatekey (English.getbytes (), Privatekey);        String decenglish = new String (Decryptbypublickey (Encenglish, PublicKey));        System.out.println ("Before encryption:" + English + "\n\r" + "after decryption:" + decenglish);        SYSTEM.OUT.PRINTLN ("Private key signature--public key verification signature");        Generates a signature String sign (encenglish, Privatekey);        System.out.println ("signature: \ r" + sign);        Verify that the signature is Boolean status = Verify (Encenglish, PublicKey, sign);    System.out.println ("Status: \ r" + status); }}</span&Gt 

Add decryption Results



Conclusion
In fact, seemingly complex process, with a sentence can be described: the use of public key encryption, the private key decryption, the completion of party B to party a data transfer, through the private key encryption, public key decryption, at the same time through the private key signature, public key verification signature, completed a party to party B data transmission and verification, Two data transfer completes a complete set of data interactions.
The appearance of asymmetric encryption algorithm is to solve only one key encryption and decryption, as long as the key is lost or exposed, then encrypted data is vulnerable to attack. At the same time, it is due to the emergence of asymmetric encryption algorithm, only the following digital signature, digital certificate and so on.
OK, this is it today, the next one continues asymmetric encryption, as for which, when the time to know, here first secrecy, (*^__^*) hehe.

RSA in the Java encryption and decryption technology series

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.