Analysis of symmetric encryption and asymmetric encryption

Source: Internet
Author: User
Tags asymmetric encryption

Symmetric encryption

Symmetric encryption is the fastest and simplest way to encrypt encryption (encryption) and decryption (decryption) with the same key (secret key). Symmetric encryption has many algorithms, and because of its high efficiency, it is widely used in the core of many cryptographic protocols.
Symmetric encryption typically uses a relatively small key, typically less than the size of a bit. The greater the key, the stronger the encryption, but the slower the encryption and decryption process. If you use only 1 bit to do this key, the hacker can first try to decrypt with the word, no, then use 1 solution, but if your key is 1 MB large, hackers may never crack, but the encryption and decryption process takes a long time. The size of the key is both to take care of the security, but also to take care of the efficiency, is a trade-off.
One of the big drawbacks of symmetric encryption is the management and allocation of keys, in other words, the question of how to send a key to someone who needs to decrypt your message. In the process of sending the key, there is a great risk that the key will be intercepted by hackers. The common practice in reality is to encrypt the symmetric encrypted key in an asymmetric manner and then pass it on to the person who needs it.

Asymmetric encryption

Asymmetric encryption provides a very secure way to encrypt and decrypt data, using a pair of keys, public key, and private key. The private key can only be safely kept by one party and cannot be compromised, while the public key may be sent to any person requesting it. Asymmetric encryption uses one of these keys to encrypt, while decryption requires another key. For example, you ask the bank for a public key, the bank sends you the public key, you encrypt the message using the public key, and only the holder of the private key – the bank can decrypt your message. Unlike symmetric encryption, the bank does not need to send the private key over the network, so security is greatly improved.
Currently the most commonly used asymmetric encryption algorithm is the RSA algorithm, which is Rivest, Shamir, and Adleman invented in 1978.
Although asymmetric encryption is secure, it is very slow compared to symmetric encryption, so we still use symmetric encryption to deliver the message, but the key we use for symmetric encryption can be sent out by asymmetric encryption. To explain this process, take a look at the following example:
(1) Alice needs to make a deal on the bank's website, and her browser first generates a random number as the symmetric key.
(2) Alice's browser requests the public key from the bank's website.
(3) The bank sends the public key to Alice.
(4) Alice's browser uses the bank's public key to encrypt its own symmetric key.
(5) Alice's browser sends the encrypted symmetric key to the bank.
(6) The bank uses the private key to decrypt the symmetric key from Alice's browser.
(7) Alice and the bank can use the symmetric key to encrypt and decrypt the content of the communication.

Summarize

(1) Symmetric encryption and decryption using the same key, so fast, but because the need to transfer the key in the network, so security is not high.
(2) Asymmetric encryption uses a pair of keys, public and private keys, so security is high, but encryption and decryption slow.
(3) The solution is to encrypt the symmetric encryption key using the asymmetric encryption of the public key, and then send it out, the receiver uses the private key to decrypt the symmetric encryption key, and then the two sides can use symmetric encryption to communicate.

Problem

Asymmetric encryption: Public key encryption, private key decryption, private key digital signature, public key authentication.
However, for private key encryption public key decryption, that is, authentication, the public key, since it has been exposed, it is possible to be known, and as long as there is a public key to unlock the private key, the private key to encrypt the content is not there is a high probability of disclosure?
Answer:
If you only use asymmetric encryption algorithm unilaterally, there are two ways to use it for different purposes.

    1. The first is signing, using private key encryption, public key decryption, which allows all public key owners to verify the identity of the private key owner and to prevent tampering with the content published by the private key owner. But not to ensure that the content is not available to others.
      C stands for Client,s on behalf of the server
      In C1,C2,C3, C1 uses its own private key key1 to send an encrypted message to s info. Because the public key is public, s uses the public key to decrypt the info, it can know that the info is from C1 (confirm C1 identity).
      At this time because the hacker also has a public key, through the public key decryption hacker can also get info, but can not tamper, because the hacker does not have C's private key, the hacker tampered with the content, s do not know.

    2. The second is encryption, public-key encryption, private-key decryption, which is used to publish information to the public key owner, which may be tampered with, but cannot be obtained by others.
      Because the private key decryption, the hacker does not have the private key, of course, it is impossible to decrypt to get info, but the hacker has a public key, you can encrypt the public key, assemble tamper info sent out.

If a want to give B a safe confidential data, then should a B each have a private key, a first with the public key of B to encrypt this piece of data, and then use their private key to encrypt the encrypted data. Finally, it is sent to B, which ensures that the content will not be read or tampered with.

Simple example: Asymmetric encryption algorithm-RSA algorithm

1. Overview

    • RSA is based on the problem of large number factor decomposition. At present, all kinds of mainstream computer language support the implementation of RSA algorithm;
    • JAVA6 supports RSA algorithm;
    • RSA algorithm can be used for data encryption and digital signature;
    • RSA algorithm, relative to Des/aes and other symmetric encryption algorithm, his speed is much slower;
    • General principles: Public key encryption, private key decryption/private key encryption, public key decryption.

2. Model Analysis
RSA algorithm building key pair simple, here we still send data as a model of both parties

    • Party a locally constructs a key pair (public key + private key) and publishes the public key to party B;
    • Party A will encrypt the data with the private key and send it to party B;
    • Party B decrypts the data with the public key provided by party A.

If party B transmits the data to party a:

    • Party B encrypts the data with the public key and transmits it to party A;
    • Party a decrypts the data with the private key.

3. RSA Simple code example

     PackageCom.ca.test;ImportJava.security.Key;ImportJava.security.KeyFactory;ImportJava.security.KeyPair;ImportJava.security.KeyPairGenerator;ImportJava.security.PrivateKey;ImportJava.security.PublicKey;ImportJava.security.interfaces.RSAPrivateKey;ImportJava.security.interfaces.RSAPublicKey;ImportJava.security.spec.PKCS8EncodedKeySpec;ImportJava.security.spec.X509EncodedKeySpec;ImportJava.util.HashMap;ImportJava.util.Map;ImportJavax.crypto.Cipher;ImportJavax.crypto.interfaces.DHPrivateKey;ImportJavax.crypto.interfaces.DHPublicKey;ImportOrg.apache.commons.codec.binary.Base64;/** * Asymmetric encryption algorithm RSA algorithm component * Asymmetric algorithm is generally used to transmit the symmetric encryption algorithm of the key to use, compared to the DH algorithm, the RSA algorithm only need one party to construct the key, do not need to make a lot of trouble to construct their own local key pair. The DH algorithm can only be implemented in the lower level of the asymmetric algorithm. The RSA algorithm is simpler to implement * @author KONGQZ * */       Public  class rsacoder {          //asymmetric key algorithm         Public Static FinalString key_algorithm="RSA";/** * Key length, the default key length for the DH algorithm is 1024 * The key length must be a multiple of 64, between 512 and 65,536 bits * */          Private Static Final intKey_size= +;//Public key        Private Static FinalString public_key="Rsapublickey";//private key        Private Static FinalString private_key="Rsaprivatekey";/** * Initialize key pair * @return Map Party Key map * */           Public StaticMap<string,object>Initkey()throwsexception{//Instantiate key generatorKeypairgenerator keypairgenerator=keypairgenerator.getinstance (Key_algorithm);//Initialize key generatorKeypairgenerator.initialize (key_size);//Generate key pairKeyPair Keypair=keypairgenerator.generatekeypair ();//Party a public keyRsapublickey publickey= (Rsapublickey) keypair.getpublic ();//Party a private keyRsaprivatekey privatekey= (Rsaprivatekey) keypair.getprivate ();//Store the key in mapMap<string,object> keymap=NewHashmap<string,object> ();              Keymap.put (Public_key, PublicKey); Keymap.put (Private_key, Privatekey);returnKeyMap; }/** * Private key encryption * @param data to be encrypted * @param key key * @return Byte[] Encrypt data * */           Public Static byte[]Encryptbyprivatekey(byte[] Data,byte[] key)throwsexception{//Get the private keyPkcs8encodedkeyspec pkcs8keyspec=NewPkcs8encodedkeyspec (key); Keyfactory keyfactory=keyfactory.getinstance (Key_algorithm);//Generate private keyPrivatekey privatekey=keyfactory.generateprivate (PKCS8KEYSPEC);//Data encryptionCipher cipher=cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, Privatekey);returnCipher.dofinal (data); }/** * Public key encryption * @param data to be encrypted * @param key key * @return Byte[] Encrypt data * */           Public Static byte[]Encryptbypublickey(byte[] Data,byte[] key)throwsexception{//Instantiate key factoryKeyfactory keyfactory=keyfactory.getinstance (Key_algorithm);//Initialize public key            //Key material conversionX509encodedkeyspec x509keyspec=NewX509encodedkeyspec (key);//Generate public keyPublicKey pubkey=keyfactory.generatepublic (X509KEYSPEC);//Data encryptionCipher cipher=cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.encrypt_mode, PubKey);returnCipher.dofinal (data); }/** * Private key decryption * @param data to be decrypted * @param key * @return  byte[] Decrypt data * */           Public Static byte[]Decryptbyprivatekey(byte[] Data,byte[] key)throwsexception{//Get the private keyPkcs8encodedkeyspec pkcs8keyspec=NewPkcs8encodedkeyspec (key); Keyfactory keyfactory=keyfactory.getinstance (Key_algorithm);//Generate private keyPrivatekey privatekey=keyfactory.generateprivate (PKCS8KEYSPEC);//Data decryptionCipher cipher=cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, Privatekey);returnCipher.dofinal (data); }/** * Public Key decryption * @param data to be decrypted * @param key key * @return  byte[] Decrypt data * */           Public Static byte[]Decryptbypublickey(byte[] Data,byte[] key)throwsexception{//Instantiate key factoryKeyfactory keyfactory=keyfactory.getinstance (Key_algorithm);//Initialize public key            //Key material conversionX509encodedkeyspec x509keyspec=NewX509encodedkeyspec (key);//Generate public keyPublicKey pubkey=keyfactory.generatepublic (X509KEYSPEC);//Data decryptionCipher cipher=cipher.getinstance (Keyfactory.getalgorithm ()); Cipher.init (Cipher.decrypt_mode, PubKey);returnCipher.dofinal (data); }/** * Get the private key * @param keyMap key map * @return byte[] Private key * */           Public Static byte[]Getprivatekey(map<string,object> KeyMap) {Key key= (key) Keymap.get (Private_key);returnKey.getencoded (); }/** * Get public key * @param keyMap key map * @return byte[] public key * */           Public Static byte[]Getpublickey(map<string,object> KeyMap)throwsexception{key key= (key) Keymap.get (Public_key);returnKey.getencoded (); }/** * @param args * @throws Exception */           Public Static void Main(string[] args)throwsException {//Initialize key            //Generate key pairMap<string,object> Keymap=rsacoder.initkey ();//Public key            byte[] Publickey=rsacoder.getpublickey (KEYMAP);//private key            byte[] Privatekey=rsacoder.getprivatekey (KEYMAP); System.out.println ("Public key:/n"+base64.encodebase64string (PublicKey)); System.out.println ("private key:/n"+base64.encodebase64string (Privatekey)); System.out.println ("================ key pair is constructed, party A will publish the public key to party B, start the transmission of encrypted data ============="); String str="RSA cipher Exchange Algorithm"; System.out.println ("/n=========== Party B to send encrypted data =============="); System.out.println ("Original:"+STR);//Data encryption by party a            byte[] Code1=rsacoder.encryptbyprivatekey (Str.getbytes (), Privatekey); System.out.println ("Encrypted data:"+base64.encodebase64string (Code1)); System.out.println ("=========== Party B uses the public key provided by party A to decrypt the data ==============");//Party B to decrypt the data            byte[] Decode1=rsacoder.decryptbypublickey (Code1, PublicKey); System.out.println ("Party B after the decryption of the data:"+NewString (DECODE1) +"/n/n"); System.out.println ("=========== reverse operation, Party B sends data to party a ==============/n/n"); Str="Party B sends data to party a RSA algorithm"; System.out.println ("Original:"+STR);//Party B encrypts the data using the public key            byte[] Code2=rsacoder.encryptbypublickey (Str.getbytes (), PublicKey); System.out.println ("=========== Party B uses public key to encrypt data =============="); System.out.println ("Encrypted data:"+base64.encodebase64string (Code2)); System.out.println ("============= Party b transmits the data to party a ======================"); System.out.println ("=========== party A uses the private key to decrypt the data ==============");//Party A uses the private key to decrypt the data            byte[] Decode2=rsacoder.decryptbyprivatekey (Code2, Privatekey); System.out.println ("Party A decrypted data:"+NewString (Decode2)); }} Console output: Public key: Mfwwdqyjkozihvcnaqebbqadswawsajbam0qc+evm4pybbcbum4jrxoysxwkyllxvklywp3jns71 B6vLV g2iwh6twpbpxbgwoi11rmlhe5bwlpdebqp4f4mcaweaaq== private key: miibvqibadanbgkqhkig9w0baqefaascat8wgge7ageaakeazspz55wbinif SIG4ZINHE5IZFATK Utdwsxjanck2zvuhq8twdyjchppa9uldszy4jxvewuf7lvaul14go/h/gwidaqabakbyhw3pksoh Zhoy6lYkCqEUGTptrG ybtuqg/2QBI12IQZENM7RKLASJDMER6Q8RX5RPGARZVHVLEPAPQPZ5LXJR aiea7vi8/9HHRZSBHQ4UP7XBY7BOULKNORJZY68HRMPRSXUCIQDBZWQFVRYNQLIAUTCNSG6EJCJW cxsclljupgwbbjyofwigvebwivipr/ zpgz9bi6o4ykoozknxg01ri/6O1qumtp0ciqdbc0xo73oj8Vt2bdza8/d884vhghoxfqcswc3otgz4twihangxz8ghxm0zuog8pds54s1arlrkuxfulocvz2ka ngFf ================ Key pair is constructed, party A will publish the public key To party B, start the transmission of encrypted data ============= =========== party A to party B to send encrypted data ============== original: RSA cipher Exchange Algorithm encrypted data: KF3VEKZ0DPJMLZWDRWJFZ lygbwskzfowm+8Im85kzr6qa49csvcl9kgsfjsvluxwgsprfoehkiqq0+vapr001a== =========== Party B uses the public key provided by party A to decrypt the data ============== the decrypted data: The RSA cipher Exchange algorithm =========== reverse operation, Party B sends data to party a ===== ========= Original: B direction to send data RSA algorithm =========== Party B uses the public key to encrypt the data ============== encrypted data: Xm1mb3dldkrwsozf9z8yqlftrwpkt8lka Bi17cn/zloekoo8jvlkvajpjsmwtjmcphtjntdkhkom s1v8xbh3og== ============= Party b transmits data to party a ====================== = = = ======= Party A uses the private key to decrypt the data ============== party a decrypted data: B direction to send data RSA algorithm
Reference reference
    • Symmetric and Asymmetric encryption
    • -RSA algorithm for asymmetric encryption algorithm
    • Introduction and distinction between symmetric and asymmetric cryptography

Analysis of symmetric encryption and asymmetric encryption

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.