Java encryption algorithm-Asymmetric Encryption Algorithm (DH,RSA) detailed introduction _java

Source: Internet
Author: User
Tags decrypt first string asymmetric encryption

Asymmetric Cryptography Concepts

1, the main difference with the symmetric encryption algorithm is that encryption and decryption of the key is not the same, a public (public key), a secret (private key). This paper mainly solves the problem of key distribution management of symmetric encryption algorithm, and improves the security of the algorithm.

2, the asymmetric encryption algorithm encryption, decryption efficiency is low. In the algorithm design, the asymmetric encryption algorithm treats the encrypted data length to have the strict request. For example, the RSA algorithm requires that the data to be encrypted must not be greater than 53 bytes.

3, asymmetric encryption algorithm is mainly used to exchange symmetric encryption algorithm key, rather than data exchange

4. JAVA6 provides two kinds of algorithms for DH and RSA. The bouncy castle provides e1gamal algorithm support. In addition to the above three algorithms there is an ECC algorithm, there is no relevant open source components to provide support

Requires two keys for encryption or decryption, divided into public and private keys

Features: High safety, slow speed

Use

"Key Exchange (DH)"

In the absence of a common key, the two sides generate the key, do not provide encryption work, encryption and decryption need other symmetric encryption algorithm to achieve

DH Algorithm Sample

Import javax.crypto.KeyAgreement;
Import Javax.crypto.interfaces.DHPrivateKey;
Import Javax.crypto.interfaces.DHPublicKey;
Import Javax.crypto.spec.DHParameterSpec;
Import java.security.*;
Import Java.security.spec.PKCS8EncodedKeySpec;
Import Java.security.spec.X509EncodedKeySpec;
Import Java.util.HashMap;

Import Java.util.Map; 1 Generate source key//2 the source public key to the target, the target through the source public key, generate the target public key and private key//3 the target public key to the source//4 both sides use the other's public key and and their own private key, generate local key//5 if both sides generate the same local key to complete the key exchange
  til {public static final String Public_key = "Dh_public_key";

  public static final String Private_key = "Dh_private_key"; /** * Generate source Key pair * @return * @throws Exception/public static map<string,object> Initsourcekey () throws

    exception{//Create Keypairgenerator instance, select DH algorithm keypairgenerator keypairgenerator = keypairgenerator.getinstance ("dh");

    Initialization key length, default 1024, optional range 512-65536 & 64 multiples keypairgenerator.initialize (1024);
    Generate key pair KeyPair KeyPair = Keypairgenerator.generatekeypair (); DhpublickeY Dhpublickey = (dhpublickey) keypair.getpublic ();

    Dhprivatekey Dhprivatekey = (dhprivatekey) keypair.getprivate ();
    Place the key pair into the Map map<string,object> keymap = new hashmap<string, object> ();
    Keymap.put (Public_key, Dhpublickey);
    Keymap.put (Private_key, Dhprivatekey);
  return keymap; /** * Generates a target key pair through the source public key pairs * @param sourcepublickey * @return * @throws Exception * * (* * * * map< String,object> Inittargetkey (byte[] sourcepublickey) throws Exception {keyfactory keyfactory = Keyfactory.getinst

    ance ("DH"); Generate Keyspec from the source public key, use Keyfactory to generate source PublicKey related information x509encodedkeyspec keyspec = new X509encodedkeyspec (Sourcepublickey)
    ;

    Dhpublickey sourcepublic = (dhpublickey) keyfactory.generatepublic (KEYSPEC);

    Dhparameterspec dhpublickeyparams = Sourcepublic.getparams ();
    Keypairgenerator keypairgenerator = keypairgenerator.getinstance ("DH");

    Keypairgenerator.initialize (Dhpublickeyparams); KeyPair KeyPair = kEypairgenerator.generatekeypair ();
    Dhpublickey Dhpublickey = (dhpublickey) keypair.getpublic ();

    Dhprivatekey Dhprivatekey = (dhprivatekey) keypair.getprivate ();
    Place the key pair into the Map map<string,object> keymap = new hashmap<string, object> ();
    Keymap.put (Public_key, Dhpublickey);
    Keymap.put (Private_key, Dhprivatekey);
  return keymap; /** * uses a party's public key and the other party's private key to generate a local key * @return * * * (byte[) Generatelocalsecretkey (byte[) Apublickey by

    Te[] bprivatekey) throws exception{keyfactory keyfactory = keyfactory.getinstance ("DH");
    Generate Keyspec through a public key, generate a PublicKey related information using keyfactory x509encodedkeyspec keyspec = new X509encodedkeyspec (Apublickey);

    PublicKey PublicKey = Keyfactory.generatepublic (Keyspec);
    By B private key, generate B privatekey related information pkcs8encodedkeyspec pkcs8encodedkeyspec = new Pkcs8encodedkeyspec (Bprivatekey);

    Privatekey Privatekey = keyfactory.generateprivate (Pkcs8encodedkeyspec); Through Keyagreement to A's PublicKey and B's PrivaTekey to encrypt keyagreement keyagreement = keyagreement.getinstance ("DH");
    Keyagreement.init (Privatekey);


    Keyagreement.dophase (publickey,true); Return Keyagreement.generatesecret ("AES"). getencoded ()//The algorithm uses a symmetric encryption Algorithm (DES,DESEDE,AES)//return        Keyagreement.generatesecret (); You can also not select an algorithm, use the default method to calculate}//Get the public key byte array, byte[] Getpublickey (map<string,object> Map) {return (DHP
  Ublickey) Map.get (Public_key)). getencoded (); //Get private key byte array public static byte[] Getprivatekey (map<string,object> Map) {return (Dhprivatekey) Map.get (PRI
  Vate_key)). getencoded ();
    public static void Main (string[] args) throws Exception {byte[] source_public_key;
    Byte[] Source_private_key;

    Byte[] Source_local_key;
    Byte[] Target_public_key;
    Byte[] Target_private_key;

    Byte[] Target_local_key;
    map<string, object> Sourcekey = Initsourcekey ();
    Source_public_key = Getpublickey (Sourcekey); Source_private_key = GetprivatekEY (Sourcekey);
    SYSTEM.OUT.PRINTLN ("Source Public key:" +bytestohex.frombytestohex (Source_public_key));

    SYSTEM.OUT.PRINTLN ("Source private key:" +bytestohex.frombytestohex (Source_private_key));
    map<string, object> targetkey = Inittargetkey (Getpublickey (Sourcekey));
    Target_public_key = Getpublickey (Targetkey);

    Target_private_key = Getprivatekey (Targetkey);
    SYSTEM.OUT.PRINTLN ("Target public Key:" +bytestohex.frombytestohex (Target_public_key));

    SYSTEM.OUT.PRINTLN ("Target private key:" +bytestohex.frombytestohex (Target_private_key));
    Source_local_key = Generatelocalsecretkey (Target_public_key, Source_private_key);

    Target_local_key = Generatelocalsecretkey (Source_public_key, Target_private_key);
    System.out.println ("Source local key:" +bytestohex.frombytestohex (Source_local_key));
  SYSTEM.OUT.PRINTLN ("Target local key:" +bytestohex.frombytestohex (Target_local_key));

 }
}

Encryption/decryption (RSA) digital signature (RSA)

The RSA algorithm is later than the DH algorithm, and the five letters are all names first letters. The DH algorithm is the first asymmetric cipher system.

RSA algorithm is slow in operation, it is not suitable to encrypt large amount of data. One solution is to mix RSA with symmetric encryption, encrypt the data using symmetric encryption, and encrypt the symmetric key using the RSA algorithm, because the key is very short, so time won't cost much. In fact, The only disadvantage of symmetric encryption is that the key is not easy to pass, and symmetric encryption is difficult to crack.

Application Scenario One of RSA:

(1) The server generates a public key and a private key, exposing the public key.

(2) The client uses the public key to encrypt the data and turn it in to the server. Others cannot understand the encrypted data.

(3) The server decrypts the data using the private key to view the data submitted by the user.

In this scenario, the public key is like a mailbox, everyone can put a letter in the mailbox, but the letter in this mailbox only the person who has the key to the mailbox to open the box to see.

RSA Application Scenario Two:

(1) The emperor generates a public key and a key and exposes the public key.

(2) The emperor issued a royal edict, announcing the world. There are two numbers in the lower right corner of the edict, the first number is a random string, and the second number is the result of encrypting the first string of digits with the private key.

(3) Some people do not believe that this edict is the emperor wrote, the second string of numbers using the public key to decrypt, decrypted after the discovery of the same as the first series of numbers, that is really the emperor wrote, because the general people do not have the key, also can not encrypt those who are able to use the

In this scenario, the public key is used for decryption and the private key is used for encryption, which can be used to prove that the bulletin was actually sent by someone. The equivalent of a signature.

In fact, the signature is not necessarily very long, in general, the signature is fixed long, to be fixed long, you can use the messagedigest algorithm, such as MD5 and SHA series. So there are a variety of signature algorithms, such as Md5withrsa.

RSA Encryption/decryption Example

Import Javax.crypto.Cipher;
Import Java.security.KeyPair;
Import Java.security.KeyPairGenerator;
Import Java.security.PublicKey;
Import Java.security.interfaces.RSAPrivateKey;
Import Java.security.interfaces.RSAPublicKey;
Import Java.util.HashMap;

Import Java.util.Map;
  /** * RSA Encryption Tool */public class Rsautil {public static final String Public_key = "Rsa_public_key";

  public static final String Private_key = "Rsa_private_key"; /** * Initialization Key * @return * @throws Exception/public static map<string,object> Initkey () throws Excepti
    on{keypairgenerator keypairgenerator = keypairgenerator.getinstance ("RSA");
    Keypairgenerator.initialize (1024); multiples of//512-65536 & 64 KeyPair KeyPair = Keypairgenerator.generatekeypair ();
    Rsapublickey PublicKey = (rsapublickey) keypair.getpublic ();

    Rsaprivatekey Privatekey = (rsaprivatekey) keypair.getprivate ();
    map<string,object> keymap = new hashmap<string, object> (); Keymap.put (Public_key,PublicKey);
    Keymap.put (Private_key, Privatekey);
  return keymap; public static Rsapublickey Getpublickey (map<string,object> keymap) {return (Rsapublickey) Keymap.get (PUBLI
  C_key); public static Rsaprivatekey Getprivatekey (map<string,object> keymap) {return (Rsaprivatekey) Keymap.get (PRI
  Vate_key);  /** * Use public key to encrypt data * @param @param publickey * @return * @throws Exception
    Byte[] Encrypt (byte[] data, Rsapublickey publickey) throws exception{Cipher Cipher = cipher.getinstance ("RSA");
    Cipher.init (Cipher.encrypt_mode,publickey);
  return cipher.dofinal (data); /** * Using the private key to decrypt * @param data * @param privatekey * @return * @throws Exception/public static byt
    E[] Decrypt (byte[] data, Rsaprivatekey Privatekey) throws exception{Cipher Cipher = cipher.getinstance ("RSA");
    Cipher.init (Cipher.decrypt_mode,privatekey);
  return cipher.dofinal (data); } Public Static void Main (string[] args) throws Exception {String data = "Jay Chou-Dongfeng Break";

    map<string, object> keymap = Initkey ();
    byte[] Miwen = Encrypt (Data.getbytes (), Getpublickey (Keymap));

    SYSTEM.OUT.PRINTLN ("Encrypted content:" +bytestohex.frombytestohex (Miwen));
    Byte[] Plain = Decrypt (Miwen, Getprivatekey (keymap));

  SYSTEM.OUT.PRINTLN ("Decrypted content:" +new String (plain));

 }
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.