Java encryption and decryption technology series of RSA detailed _java

Source: Internet
Author: User
Tags base64 decrypt generator asymmetric encryption

Distance to write a blog feeling has been a long time, first spit slot, this month, the company has been working overtime, but also issued a version, on-line, but also a new project is too tight, the specific will not say more. Today, the asymmetric encryption is really too important, in our daily life, are inseparable from asymmetric encryption.

Concept

Before talking about RSA, let's talk about what is asymmetric encryption. Symmetric encryption, said once, symmetric encryption algorithm in the encryption and decryption using the same secret key, encryption and decryption both sides must use the same key to normal communication. In the case of asymmetric encryption, the asymmetric encryption algorithm requires two keys for encryption and decryption, respectively, of the public and private keys.

It is important to note 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 used to decrypt it, and vice versa. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm.

Working process

In the following diagram, the data is transmitted between A and B using asymmetric encryption.

The main algorithms used in asymmetric encryption are: RSA, Elgamal, knapsack algorithm, Rabin, D-h, ECC (elliptic curve encryption algorithm) and so on. Today mainly introduces RSA, as for the other algorithms, the follow-up will select several to introduce.

Rsa

In fact, as early as 1978, RSA has appeared, it is the first to both data encryption can also be used for digital signature algorithm. It is easy to understand and operate, but also very popular. The principle is as described in the working process 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 factor the product, so you can expose the product as the encryption key.

Code implementation

Here's a look at the specific code implementation.

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 encryption and Decryption tool class/public class RSA {/** * define encryption Mode * * Private final static String Key_rsa = "RSA"; 
  /** * Define Signature Algorithm * * Private final static String key_rsa_signature = "Md5withrsa"; 
  /** * Defines the public key algorithm */private final static String Key_rsa_publickey = "Rsapublickey"; 
 
  /** * Defines the private key algorithm */private final static String Key_rsa_privatekey = "Rsaprivatekey"; /** * Initialization Key * @return/public static map<string, object> init () {map<string, object> ma 
    p = 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 (); 
      Encapsulates the key as a map map = Maps.newhashmap (); 
      Map.put (Key_rsa_publickey, PublicKey); 
    Map.put (Key_rsa_privatekey, Privatekey); 
    catch (NoSuchAlgorithmException e) {e.printstacktrace (); 
  } return map; /** * uses the private key to generate digital signatures for information * @param data encryption * @param privatekey private key * @return/public static Stri 
    Ng sign (byte[] data, String privatekey) {string str = ""; 
      try {//Decrypt the private key encoded by base64 byte[] bytes = decryptBase64 (Privatekey); 
      Construct Pkcs8encodedkeyspec Object Pkcs8encodedkeyspec PKCS = new Pkcs8encodedkeyspec (bytes); 
      The specified cryptographic algorithm keyfactory factory = keyfactory.getinstance (Key_rsa); Take the private keyObject Privatekey key = Factory.generateprivate (PKCS); 
      Digitally sign the 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 Checksum successfully returns true, lost 
    Defeat returns 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); 
      Construct X509encodedkeyspec Object X509encodedkeyspec keyspec = new X509encodedkeyspec (bytes); 
      The specified cryptographic algorithm keyfactory factory = keyfactory.getinstance (Key_rsa); 
      Take the public key object PublicKey key = Factory.generatepublic (KEYSPEC); Verifying digital signatures with 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[] Decryptbypri 
    Vatekey (byte[] data, String key) {byte[] result = NULL; 
      try {//decryption of the private key byte[] bytes = decryptBase64 (key); 
      Gets the private key pkcs8encodedkeyspec Keyspec = new Pkcs8encodedkeyspec (bytes); 
      Keyfactory factory = keyfactory.getinstance (Key_rsa); 
      Privatekey Privatekey = factory.generateprivate (Keyspec); 
      Decrypt the 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[] Decryptbypublickey (byte[] data, String key) {byte[] result = NULL 
    ; 
      try {//Public key decryption byte[] bytes = decryptBase64 (key); 
      Obtain 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 * * byte[) Encryptbypu 
    Blickey (byte[] data, String key) {byte[] result = NULL; 
      try {byte[] bytes = decryptBase64 (key); 
      Obtain 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[] Encryptbypr 
    Ivatekey (byte[] data, String key) {byte[] result = NULL; 
      try {byte[] bytes = decryptBase64 (key); 
      Gets 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 * * * Getpublickey (map<string, object> 
    MAP) {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&gt ; 
    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 needs to decrypt the string * @return byte array * @throws Exception/public static by 
  Te[] DecryptBase64 (String key) throws Exception {return (new Base64decoder ()). Decodebuffer (key); 
 } 
 
  /**  * BASE64 Encryption * @param key needs to encrypt the byte array * @return String * @throws Exception/public static string ENCRYPTB 
  Ase64 (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 private 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 encryption--------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" + "after decryption:" + 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:" + 中文版 + "\n\r" + "after decryption:" + decenglish); 
    SYSTEM.OUT.PRINTLN ("Private key signature--public key authentication signature"); 
    Generate signature String sign = sign (encenglish, Privatekey); 
    System.out.println ("signature: \ r" + sign); 
    Verify Signature Boolean status = Verify (Encenglish, PublicKey, sign); 
  System.out.println ("Status: \ r" + status);
 } 
}

Add and Decrypt results

Conclusion

In fact, seemingly very complex process, with a word can be described: the use of public key encryption, private key decryption, completed the party B to party a data transmission, through the private key encryption, public key decryption, at the same time through the private key signature, public key authentication signature, completed a party to party B data transmission and Two times 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 the encrypted data is very easy to attack. At the same time, it is precisely because of the emergence of asymmetric encryption algorithm, only after the digital signature, digital certificate and so on.

OK, today is the right, the next one continue to asymmetric encryption, as to which kind, the time will know, this is the first secret

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.