Software encryption and decryption is a fascinating field of study, which can be closely combined with almost any computer technology — cryptography, programming languages, operating systems, data structures. For one reason or another, interest in this area has been low.

The following key points should be paid attention to in network security:

  • Integrity: Ensure that information is not tampered with during transmission.

  • Confidentiality: Encryption is used to ensure that only trusted entities can see the information.

  • Source authentication: Ensures that a trusted source is sending these messages, not a masquerading source.

  • Nonrepudiation: You cannot later deny sending this message.

Today we are talking about the privacy of data transmission. Encryption technology is the most commonly used security means, the use of technical means to turn important data into garbled (encryption) transmission, after arriving at the destination with the same or different means to restore (decryption).

Encryption consists of two elements: the algorithm and the key.

Use xOR encryption and decryption

Let’s look at a simple example of encryption and decryption.

package com.wuxiaolong.EncrypteDecrypt;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * Description:
 *
 * @authorZhuge little Ape *@dateThe 2020-07-22 * /
public class Test1 {

    public static void main(String[] args) {
        String content = "I love you.";
        Integer key = 1000;

        // Before sending A message, user A encrypts it in some way
        String encryptStr = xor(content,key);
        System.out.println(encryptStr);

        // The ciphertext is transmitted over the network

        // User B decrypts the ciphertext in the same manner after receiving it
        String decryptStr = xor(encryptStr,key);
        System.out.println(decryptStr);
    }

    /** * Encryption algorithm and key *@param content
     * @return* /
    public static String  xor(String content, Integer key){
        char[] chars = content.toCharArray();
        for(int i=0; i<chars.length; i++){
            chars[i] = (char)  (chars[i]^key) ;
        }
        return newString(chars); }}Copy the code

Here is a custom encryption and decryption method xor, this method takes two parameters, one is the original content, a secret key. So you have an encryption algorithm, you have a secret key, you can encrypt.

Results of the run:

Iron 懹 䲈// Encrypt the resultI love you// Decrypt the result
Copy the code

Ii. Interpretation of xOR encryption and decryption principle

Before sending a message, use the algorithm and the secret key to encrypt the message (plain text). After the message is encrypted, use the ciphertext to transmit the message over the network. After the message is transmitted to the destination, use the same algorithm and the secret key to translate the ciphertext into plain text.

In this encryption and decryption process, the same algorithm + secret key is used.

Here it can be seen that a plaintext using the same algorithm + secret key to do two consecutive encryption, you can get the original plaintext.

This is similar to the exclusive-or operation (^) in computers, exclusive OR, abbreviated xOR, has two characteristics:

  • The two binary digits are the same and the different digits are 1.

  • When a number is xor twice, you get the original number itself.

The following uses a character a as an example, and performs two xOR operations with the number three to see that the final result is still A.

Since it is a bit operation, the parameters involved in the operation must be converted to binary before they can be involved in the operation. Public static String xOR (String content, Integer key); public static String xOR (String content, Integer key); Converts the new character array to a new string.

Why can’t I use the content string to differentiate or operate directly with the key? Because strings cannot operate directly with numbers, but characters can operate with numbers, strings are converted to character arrays.

The underlying encryption and decryption methods described below use binary, so the encryption and decryption parameters are eventually converted to binary byte arrays for processing.

In this method, encryption and decryption use the same key, which is often referred to as symmetric encryption. If encryption and decryption use different secret keys, it is called asymmetric encryption.

Three, symmetric encryption

With symmetric encryption, both parties need to know the same key and algorithm before they can communicate, and then the data is encrypted and decrypted.

Here we introduce several common symmetric encryption algorithms: DES and AES.

3.1 the DES

Data Encryption Standard (DES) is an Encryption method used by the U.S. government to protect computer Data during information processing. It is a common Encryption algorithm used in the current password system. The algorithm inputs 64 bits of plaintext and generates 64 bits of ciphertext under the control of 64 bits of key. On the other hand, input 64 bits of ciphertext and output 64 bits of plaintext. The 64-bit key contains eight parity bits, so the actual effective key length is 56 bits. Use a 56-bit key with additional 8-bit parity bits to produce a maximum packet size of 64 bits. This is an iterative block cipher using a technique called Feistel, in which a block of encrypted text is split in half. Apply a loop to half of them using a subkey, and then “xor” the output to the other half; And then we swap these two halves, and the process will continue, but the last loop doesn’t swap. DES uses 16 cycles, using xor, substitution, substitution, shift operation four basic operations.

Here is sample code for encryption using the JDK:

package com.wuxiaolong.EncrypteDecrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.util.Base64;

/**
 * Description:
 *
 * @authorZhuge little Ape *@dateThe 2020-07-23 * /
public class DESUtil {
    /** * offset variable, fixed to occupy 8 bytes */
    private final static String IV_PARAMETER = "12345678";
    /** * Encryption algorithm */
    private static final String ALGORITHM = "DES";
    /** * Encryption/decryption algorithm - working mode - Fill mode */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
    /** * Default encoding */
    private static final String CHARSET = "utf-8";
    /** * key */
    private static final String KEY = "key12345678";


    public static void main(String[] args) {
        String content = "I love you.";

        String encptStr = encrypt(KEY,content);
        System.out.println(encptStr);

        String decptStr = decrypt(KEY,encptStr);
        System.out.println(decptStr);
    }

    /** * generates key **@param password
     * @return
     * @throws Exception
     */
    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }


    /** * DES Encryption character string **@paramPassword Encryption password. The value cannot be less than 8 *@paramData Character string * to be encrypted@returnEncrypted content */
    public static String encrypt(String password, String data) {
        if (password== null || password.length() < 8) {
            throw new RuntimeException("Encryption failed. Key cannot be less than 8 bits");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

            / / encryption
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));

            // Base64 encoder can be used directly in JDK1.8 or above, and BASE64Encoder can be used in JDK1.7 or below
            byte[] encode = Base64.getEncoder().encode(bytes);

            return new String(encode);

        } catch (Exception e) {
            e.printStackTrace();
            returndata; }}/** * DES decrypts the string **@paramPassword Indicates the decryption password. The value cannot be less than 8 *@paramData Character string * to be decrypted@returnDecrypted content */
    public static String decrypt(String password, String data) {
        if (password== null || password.length() < 8) {
            throw new RuntimeException("Encryption failed. Key cannot be less than 8 bits");
        }
        if (data == null)
            return null;
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

            / / base64 decoding
            byte[] decode = Base64.getDecoder().decode(data.getBytes(CHARSET));

            / / decryption
            byte[] decrypt = cipher.doFinal(decode);

            return new String(decrypt, CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
            returndata; }}}Copy the code

The result of the above code run:

Xii999DE7LPx5io0awfOFw==        // Encrypt the resultI love you// Decrypt the result
Copy the code

DES is a block data encryption technology that divides data into small data blocks of fixed length and encrypts data later. DES is fast and applies to mass data encryption, such as file encryption. File encryption code, you can follow my public number, enter the keyword “java-summary” to obtain.

In 1997, RSA Data Security company launched a “DES Challenge”, in which volunteers broke the ciphertext encrypted with 56bit DES algorithm for four months, 41 days, 56 hours and 22 hours respectively. The DES encryption algorithm is considered unsafe today after computer speeds have increased. Therefore, asymmetric encryption algorithms are recommended for data with high security levels.

3.2 the AES

Advanced Encryption Standard (AES) is a block Encryption Standard. This standard to replace the original DES, has been widely analyzed and used around the world.

DES uses 56-bit key, which is easy to be broken, while AES can use 128, 192, and 256-bit key, and encrypt and decrypt data with 128-bit group, which is relatively secure. A complete encryption algorithm is theoretically impossible to break jie unless using the exhaustive method. It is not practical to use exhaustive method to break encrypted data with jie key length above 128 bits, and it is only theoretically possible. Statistics show that even with the fastest computer in the world, it would take billions of years to exhaust the 128-bit key, let alone break the AES algorithm that uses 256-bit key length.

Here is the source code of AES:

package com.wuxiaolong.EncrypteDecrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * Description:
 *
 * @authorZhuge little Ape *@dateThe 2020-07-23 * /
public class AESUtil {

    /** * Encryption algorithm */
    private static final String ALGORITHM = "AES";
    /** * Key length */
    private static final Integer KEY_LENGTH = 128;
    /** * Default encoding */
    private static final String CHARSET = "utf-8";
    /** * key */
    private static final String KEY = "key12345678";


    public static void main(String[] args) throws Exception {
        String content = "I love you.";

        String encrypt = encrypt(content, KEY);
        System.out.println(encrypt);

        String decrypt = decrypt(encrypt, KEY);
        System.out.println(decrypt);
    }

    /** * generates key **@param password
     * @return
     * @throws Exception
     */
    private static SecretKeySpec generateKey(String password) throws Exception {
        // Create the AES Key producer
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
        // Initialize the user password as a random number
        Password.getbytes () is the seed. As long as the seed is the same, the sequence is the same, so decryption only needs to have password
        kgen.init(KEY_LENGTH, new SecureRandom(password.getBytes()));
        // Generate a key based on the user password
        SecretKey secretKey = kgen.generateKey();
        // Returns the key in the basic encoding format, or if the key does not support encoding
        byte[] enCodeFormat = secretKey.getEncoded();
        // Convert to AES private key
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, ALGORITHM);

        return key;
    }

    /** * AES Encryption string **@paramContent Specifies the string * to be encrypted@paramPassword Specifies the password for encryption. *@returnCipher * /
    public static String encrypt(String content, String password) {
        try {
            SecretKeySpec key = generateKey(password);
            // Create a password
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            byte[] byteContent = content.getBytes(CHARSET);
            // Initialize the cipher to encrypted mode
            cipher.init(Cipher.ENCRYPT_MODE, key);
            / / encryption
            byte[] result = cipher.doFinal(byteContent);
            // Convert binary to hexadecimal string
            String hexStr = parseByte2HexStr(result);

            return hexStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** * Decrypts AES encrypted string **@paramContent Indicates the content encrypted by AES@paramPassword Indicates the encryption password *@returnClear * /
    public static String decrypt(String content, String password) {
        try {
            // A hexadecimal string is converted to a binary byte array
            byte[] byteArr = parseHexStr2Byte(content);

            SecretKeySpec key = generateKey(password);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            / / decryption
            byte[] result = cipher.doFinal(byteArr);

            return new String(result,CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** Convert binary to hexadecimal *@param buf
     * @return* /
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /** Convert hexadecimal to binary *@param hexStr
     * @return* /
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0; i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        returnresult; }}Copy the code

The result of the above code run:

765B2080D288F81355CB2A235AD7938C        // Encrypt the resultI love you// Decrypt the result
Copy the code

Compared with DES, AES algorithm has higher speed and resource utilization efficiency, and higher security level. It is called the next generation encryption Standard. At present, there are organizations in the world to study how to break AES this thick wall, but because the jie time is too long, AES is guaranteed, but the time used is shrinking. As computers get faster and new algorithms emerge, the attacks on AES are only going to get worse and worse.

AES, currently widely used in financial accounting, online transactions, wireless communications, digital storage and other fields, has undergone the most rigorous test, but it may one day go the way of DES.

3.3 Features of symmetric encryption

Advantages:

  • Speed is fast. Compared with asymmetric encryption, symmetric encryption has better performance and faster encryption and decryption speed.
  • Security. It’s relatively safe.
  • Compact. The length of the encrypted content basically doesn’t change much.

Disadvantages:

  • If a shared key is transmitted in plaintext during communication, hijacking and eavesdropping may occur.
  • As the number of participants increases, the number of keys expands rapidly ((n×(n-1))/2).
  • Because the number of keys is too much, the management and storage of keys is a big problem (I will talk about secret key management and system design in a special issue later).
  • Digital signatures and non-repudiation are not supported.

Four, asymmetric encryption

For asymmetric algorithms, both parties need to generate a pair of keys (public key and private key) before communication, and then both parties exchange public keys. RAS algorithms are often used for asymmetric encryption.

Before using asymmetric key technology, all participants, whether users or network devices such as routers, need to generate a pair of keys, including a public key and a private key, using an asymmetric key algorithm (such as RSA) in advance. The public key can be shared on a server with all users and devices belonging to the key system, while the private key must be strictly protected by the owner to ensure that only the owner can have it.

Asymmetric encryption has many advantages, such as security, public key transmission over network and so on. However, the encryption speed is very slow and will not be used to encrypt the KB data.

About RAS algorithm, can say too much content, such as the mathematical principle of RSR, public key encryption private key decryption, private key signature public key check, public and private key generation, how to encrypt large files, how to manage the secret key and so on. I’ll cover this in more detail in other articles in this security series. This installment will focus on the code presentation, but I won’t talk more about it here.

4.1 RSA

Note that encryption uses the public key of the other party and decryption uses the corresponding private key.

package com.wuxiaolong.EncrypteDecrypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @authorZhuge little Ape *@dateThe 2020-07-24 * /
public class RSAEncrypt {

    // Encapsulates randomly generated public and private keys
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();

    public static void main(String[] args) throws Exception {
        // Generate public and private keys
        genKeyPair();
        // Encrypt the character string
        String message = "I love you.";
        System.out.println("The randomly generated public key is :" + keyMap.get(0));
        System.out.println("Randomly generated private key is :" + keyMap.get(1));
        String messageEn = encrypt(message,keyMap.get(0));
        System.out.println(message + "\t Encrypted string :" + messageEn);
        String messageDe = decrypt(messageEn,keyMap.get(1));
        System.out.println("Restored string :" + messageDe);
    }

    /** * Randomly generates a key pair *@throws Exception
     */
    public static void genKeyPair(a) throws Exception {

        The KeyPairGenerator class is used to generate public and private key pairs based on the RSA algorithm to generate objects
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

        // Initialize the key pair generator with the key size of
        keyPairGen.initialize(2048.new SecureRandom());

        // generate a keyPair, stored in keyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // Get the private key and public key
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        // Get the private key string
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));

        // Save the public and private keys to Map 0: public key 1: private key
        keyMap.put(0,publicKeyString);
        keyMap.put(1,privateKeyString);
    }
    /** * RSA public key encryption *@paramSTR Encryption character string *@paramPublicKey public key *@returnCipher *@throwsException Indicates the Exception information during encryption */
    public static String encrypt( String str, String publicKey ) throws Exception{
        // Base64 encoded public key
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        / / RSA encryption
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /** * RSA private key decryption *@paramSTR Encryption character string *@paramPrivateKey private key *@returnClear *@throwsException Exception information during decryption */
    public static String decrypt(String str, String privateKey) throws Exception{
        // 64-bit decoded encrypted string
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        // Base64 encoded private key
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        / / RSA decryption
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        returnoutStr; }}Copy the code

The result of the code run:

The randomly generated public key is: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgJW1vVhZWd8NDiTIrAJK5N4EipP5jWw8WIsWiX3SzZGpzRuz5duRjhubxS2kOoGP6GnOI8KMAHwc FCjtgQNLfvoufHG9OiRaKQEkPhypF1vsuEC0rzeOcWbzIAsWk7B6wboGd6Or4L2MAHsIrluISgICq6BU1cVb/XSPX9tbIOfrjRNsbX5DnNd39XZ4yUlqIDoc CQtV3rmQlG4e4nlsJTw073/7/eNCkp7FMJVTch+rQspUPlks9V1ic9TmBhW7dszAGWz4BmIe1elar5bapivBtnVpRX+yEGZSQWkchTqSQTOeYfuh3GFDAYoWlGEx+OeUX8SsRK1V3zeiwv6l PQIDAQAB randomly generates the following private key: MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAlbW9WFlZ3w0OJMisAkrk3gSKk/mNbDxYixaJfdLNkanNG7Pl25GOG5vFLaQ6gY/oac4j wowAfBwUKO2BA0t++i58cb06JFopASQ+HKkXW+y4QLSvN45xZvMgCxaTsHrBugZ3o6vgvYwAewiuW4hKAgKroFTVxVv9dI9f21sg5+uNE2xtfkOc13f1dnjJ SWogOhwJC1XeuZCUbh7ieWwlPDTvf/v940KSnsUwlVNyH6tCylQ+WSz1XWJz1OYGFbt2zMAZbPgGYh7V6VqvltqmK8G2dWlFf7IQZlJBaRyFOpJBM55h+6HcYUMBihaUYTH455RfxKxErVXfN6LC/qWlAgMBAAECggEAe+FAFWpfsuDcsAqqNmWDCBoJoATOAP0M6nUdwlqxVBGI2K1e1Q2Dnrhki0Pcm+0k2tHMotEUlob7ekSwBIJLIssfLA9cMf7Byg1qgFiWY4XRevYD3WcV2ZVImE92cdUtfySchHjv53ZVwkTGaUyP8lUbg4PVF5qrdHTuiHhJxFmqLwB6DC7HM9X 2jleYJaNSZ2UwiloqkHAMDhqAu9212qZ4ISjbOg/iHDeTRKG3wIX989rsxAVSsruQm3DMZ/jeXzx8MpNjiLaT448dDSOhjhb1tOycMI7CWhYsuT7fOSFmtCt b9E3L8AVarKD2eiOqMaXj28wiuoST7lxa26hHoQKBgQDSmLPYHLXgOfJPIjuYv3IrBv9wr6H9N5FnSKYfISo8gQZJj4YWVFsc9/9vQyOOk0VvtSd28z0dixo1P4axEFe84vwVUsbgo7797nFLZWFm6tZZLgDiSgcxLhz9/5cjnY7irZMdPqKWQKkcFMm4Km8JX8BipwKVwuDiZ74enE1viQKBgQCcTpi0IxOaQQXWaDjG50MBBUIU0F1vM69apsJKeIY8XgE9Vsz/4yqwW7enIZHY15yx4btmZ/1ieOTqRI3x6SwFcgRZQD8OiKf/6WpHp7hXmTE34QJd9CPq+c8MgImd9BAX4rsdKp9pOGsTjFcAvLkU1crk/JQdht+p6VErJUwCPQKBgHLcFjqobgn9kMrYQOjugbY1+tva7t7Mj+FlHjWcQQz+0g8M2HUVTRxfplForNv2NsjWZM/bmlmipIimPTAVWcULh7GZlB6xMFoO0nvsr1MSghXhoVnKRmHsZKOj4yrppCS9xp8MqmCIo7NNIzfu7OCP+L3VmPNVdpIFQ wwu840BAoGAUJx8RpK8flZAc3YmqfYE6VbT4LYhKcOHEQJlu1BzMljs3LySVvnKP0/d5FT8yc9Q4bBgHI1O8WUV8ffPGM6/REOsGHd4zb8OnX28sR2/hXXdG 0txFBFgIMQa0wDLeGmxjxAAnicoNXTCTD+Zcyjhbuxfij71CFFRsmhA0zaV/6UCgYEAua9INHaJQ5VIFEyAWMHhfwQOU00BynQP0MugNwPypH9qejEzzBJ2fq8j69fxfeG2EENIiDymZMPwHybpYcipKT1aksCPu95HF1+yR6lNrSFDzn/kQu 06bgB3V61wsgsKeDuDh++z381m1BONfK3MS1+BlxR/pJ59ikBLyB15tiQ= I love you encrypted string is: Qo2qkCPF27rfbfAV8k3uLH4ogVA8BlnhtKEvL77KH6wZQKmzrq3z794TuWU9PbJpkYLD2tALt6t0y+Rr9rpPHCqtAGXkzDddu7get/8eNs4N3i8yoOYW2ui7yny7v5cVd8ZsxSHcszmaSV+wb+5AJcMzQhOvWaRwx1WVEOkDp/qBENGFdfPJ8gecbL7YgnqzUtccaJQomQWIlXk88mAU8nAALHO/goEI2CK1HRtb+9qyQgjHU1zFhBsli5yA8NDcqiczFb/nV90yKLMhn5DpIm3gU/qquQltfnkflSk+KXe5BFThIVxcu2FBIovOaX+s82L4DJXtRZS+aCSrHOPfSg== The restored string is: I love youCopy the code

The key used for encryption and decryption is not the same as the key used for signature verification. See other articles in this series.

4.2 Features of asymmetric encryption

Job Characteristics:

  • Data encrypted with one key (public key) can only be decrypted with another key (private key).
  • One key (private key) is used for signature and one key (public key) is used for signature verification.

Advantages:

  • Asymmetric key distribution is more secure because there is no fear of the exchanged public key being hijacked.
  • The number of keys is the same as the number of participants.
  • There is no need to establish a trust relationship before exchanging public keys.
  • Supports digital signature and non-repudiation.

Disadvantages:

  • Encryption is slow. Instead of encrypting the KB data, you can encrypt the key, which has a small amount of data.
  • After encryption, the ciphertext becomes longer.

Pay attention to the public number, input “Java-summary” to get the source code.

Done, done!

[spread knowledge, share value], thank small partners attention and support, I am [Zhuge small ape], a hesitation in the struggle of the Internet migrant workers!!