Common Encryption methods


The article directories


preface

For example, with the continuous development of artificial intelligence, machine learning is becoming more and more important. Many people have started to learn machine learning. This article introduces the basic content of machine learning.


Tip: The following is the body of this article, the following cases for reference

Symmetric encryption

  • In the encryption method of single-key cryptosystem, the same key can be used to encrypt and decrypt information at the same time. This encryption method is called symmetric encryption, also called single-key encryption.
  • Example We now have a text 3 to send to B. Set the key to 108, 3 * 108 = 324, and send 324 as ciphertext to B. After B gets the ciphertext 324, use 324/108 = 3 to get the text
  • Common Encryption Algorithms

    DES: Data Encryption Standard, also known as Data Encryption Standard, is a block algorithm that uses Encryption keys. In 1977, the National Bureau of Standards of the FEDERAL Government of the United States identified it as a Federal Data Processing Standard (FIPS) and authorized its use in unclassified government communications. Subsequently, the algorithm spread widely internationally.

    AESAdvanced Encryption Standard, also known as Rijndael in cryptography, is a block Encryption Standard adopted by the U.S. Federal government. This standard to replace the original DES, has been widely analyzed and used around the world.
  • Features 1. Fast encryption speed, large files can be encrypted 2. Ciphertext reversible, once the key file is leaked, data will be exposed 3. Garbled characters appear because the encoding table cannot find corresponding characters after encryption. 4

DES encryption

Example code DES encryption algorithm

Cipher: document

Docs.oracle.com/javase/8/do…

The code is as follows (example) :

package com.atguigu.desaes;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/ * * *@authorJsonHao 😋 *@dateSeptember 11, 2020 8:58:47 PM */
public class DesAesDemo {
	public static void main(String[] args) throws Exception{
        / / the original
        String input = "Silicon valley";
        // DES encryption must be 8 bits
        String key = "123456";
        / / algorithm
        String algorithm = "DES";

        String transformation = "DES";
        // Cipher: indicates the password to obtain the encryption object
        // transformation: What type of encryption is used
        Cipher cipher = Cipher.getInstance(transformation);
        // Specify the key rule
        // The first argument represents a byte array of keys
        // The second parameter indicates: algorithm
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        // Initialize the encryption
        // The first parameter: indicates the mode, including encryption mode and decryption mode
        // The second argument: indicates the key rule
        cipher.init(Cipher.ENCRYPT_MODE,sks);
        // Encrypt
        byte[] bytes = cipher.doFinal(input.getBytes());
        // Print bytes, because ASCII code has negative numbers, can not parse, so garbled
// for (byte b : bytes) {
// System.out.println(b);
/ /}
        // Prints ciphertext
        System.out.println(newString(bytes)); }}Copy the code



The key is 6 bytes. According to the DES encryption algorithm, the key must be 8 bytes. Therefore, change the key to “key= 12345678”.

Change the key to “12345678” and run it again. Garbled characters occur because the corresponding bytes are negative, but negative numbers do not appear in the ASCII code table. Therefore, garbled characters occur



usebase64coding

base64Guide package, need to pay attention to, do not guide the wrong, need to import apache package



Run the program:

DES decryption

Idea uses CTRL + Alt + M shortcut keys to extract code

package com.atguigu.desaes;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/ * * *@authorJsonHao 😋 *@dateSeptember 11, 2020 9:22:52 PM */
public class DesDemo {
    // DES encryption algorithm, the key size must be 8 bytes

    public static void main(String[] args) throws Exception {
        String input ="Silicon valley";
        // DES encryption algorithm, the key size must be 8 bytes
        String key = "12345678";

        String transformation = "DES"; // 9PQXVUIhaaQ=
        // Specify the algorithm to obtain the key
        String algorithm = "DES";
        String encryptDES = encryptDES(input, key, transformation, algorithm);
        System.out.println("Encryption:" + encryptDES);
        String s = decryptDES(encryptDES, key, transformation, algorithm);
        System.out.println("Decryption." + s);

    }

    /** * Use DES to encrypt data **@paramInput@paramKey: indicates the key (DES, the length of the key must be 8 bytes) *@paramTransformation: Obtains the algorithm of the Cipher object *@paramAlgorithm: algorithm to obtain the key *@return: cipher *@throws Exception
      */
    private static String encryptDES(String input, String key, String transformation, String algorithm) throws Exception {
        // Get the encrypted object
        Cipher cipher = Cipher.getInstance(transformation);
        // Create an encryption rule
        // The bytes of the first argument key
        // The second parameter indicates the encryption algorithm
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        // ENCRYPT_MODE: ENCRYPT_MODE
        // DECRYPT_MODE: decryption mode
        // Initialize the encryption mode and algorithm
        cipher.init(Cipher.ENCRYPT_MODE,sks);
        / / encryption
        byte[] bytes = cipher.doFinal(input.getBytes());

        // Outputs encrypted data
        String encode = Base64.encode(bytes);

         return encode;
     }

    /** * Use DES to decrypt **@paramInput: ciphertext *@paramKey: key *@paramTransformation: Obtains the algorithm of the Cipher object *@paramAlgorithm: algorithm to obtain the key *@throws Exception
     * @returnThe original: * /
    private static String decryptDES(String input, String key, String transformation, String algorithm) throws Exception {
        // 1 to obtain a Cipher object
        Cipher cipher = Cipher.getInstance(transformation);
        // Specify the key rule
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        // 3. Decrypt base64 encoding
        byte[] bytes = cipher.doFinal(Base64.decode(input));
        // It is plaintext, so it is returned directly
        return newString(bytes); }}Copy the code

Run the program:

Base64 algorithm introduction

Base64 is one of the most common readability encoding algorithms used to transmit 8Bit bytecode on the network. Readability encoding algorithm is not to protect the security of data, but to readability. Readability encoding does not change information content, but only the expression form of information content64Characters: uppercase A to Z, lowercase A to Z, and digits0to9, "+", and "/" Base58 is an encoding method used in Bitcoin, primarily to generate Bitcoin's wallet address. Base58 does not use numbers compared to Base64"0", uppercase"O", uppercase"I", and lowercase letters"i", as well as"+"and"/"symbolCopy the code

Principle of Base64 algorithm

Base64 is a set of three bytes, one byte is eight bits, a total of 24 bits, and then the three bytes are converted into four groups of six bits.

3 * 8 = 4 * 6 = 24, each group of 6 bits, missing 2 bits, will complement 0 in the high position, the advantage of this is that base is the last 6 bits, remove the high 2 bits, then the value of Base64 can be controlled in 0-63 bits, so it is called base64. 111 = 32 + 16 + 8 + 4 + 2 + 1

Base64 composition principles

â‘  Lowercase A-z = 26 letters

â‘¡ Capital A-Z = 26 letters

â‘¢ Numbers 0-9 = 10 numbers

â‘£ + / = 2 symbols

One problem you may notice is that our base64 has an = sign, but there is no = sign in the mapping table. This should be noted that the equal sign is very special, because base64 is a group of three bytes. If we run out of bits, we will use the equal sign to complement

4. Base64 equal sign test

package com.atguigu;
import com.sun.org.apache.xml.internal.security.utils.Base64;


/ * * *@authorJsonHao 😋 *@dateSeptember 11, 2020 9:30:20 PM */
public class TestBase64 {
	public static void main(String[] args) {
        // 1: MQ== indicates one byte, not three bytes, so it needs to be complemented with the == sign
        System.out.println(Base64.encode("1".getBytes()));
        System.out.println(Base64.encode("12".getBytes()));
        System.out.println(Base64.encode("123".getBytes()));
// // Silicon Valley: Chinese is 6 bytes, 6 * 8 = 48, just enough to be divisible, so there is no equal sign
        System.out.println(Base64.encode("Silicon valley".getBytes())); }}Copy the code

Run:

Five, AES encryption and decryption

AES encryption decryption and DES encryption decryption code, only need to modify the encryption algorithm, copy ESC code

package com.atguigu.desaes;
import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/ * * *@authorJsonHao 😋 *@dateSeptember 11, 2020 9:34:48 PM */
public class AesDemo {
    // DES encryption algorithm, the key size must be 8 bytes

    public static void main(String[] args) throws Exception {
        String input ="Silicon valley";
        // THE AES encryption algorithm is more advanced, so the key size must be 16 bytes
        String key = "1234567812345678";

        String transformation = "AES"; // 9PQXVUIhaaQ=
        // Specify the algorithm to obtain the key
        String algorithm = "AES";
        // Test encryption first, then test decryption
        String encryptDES = encryptDES(input, key, transformation, algorithm);
        System.out.println("Encryption:" + encryptDES);
        String s = dncryptDES(encryptDES, key, transformation, algorithm);
        System.out.println("Decryption." + s);

    }

    /** * Use DES to encrypt data **@paramInput@paramKey: indicates the key (DES, the length of the key must be 8 bytes) *@paramTransformation: Obtains the algorithm of the Cipher object *@paramAlgorithm: algorithm to obtain the key *@return: cipher *@throws Exception
     */
    private static String encryptDES(String input, String key, String transformation, String algorithm) throws Exception {
        // Get the encrypted object
        Cipher cipher = Cipher.getInstance(transformation);
        // Create an encryption rule
        // The bytes of the first argument key
        // The second parameter indicates the encryption algorithm
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        // ENCRYPT_MODE: ENCRYPT_MODE
        // DECRYPT_MODE: decryption mode
        // Initialize the encryption mode and algorithm
        cipher.init(Cipher.ENCRYPT_MODE,sks);
        / / encryption
        byte[] bytes = cipher.doFinal(input.getBytes());

        // Outputs encrypted data
        String encode = Base64.encode(bytes);

        return encode;
    }

    /** * Use DES to decrypt **@paramInput: ciphertext *@paramKey: key *@paramTransformation: Obtains the algorithm of the Cipher object *@paramAlgorithm: algorithm to obtain the key *@throws Exception
     * @returnThe original: * /
    private static String dncryptDES(String input, String key, String transformation, String algorithm) throws Exception {
        // 1 to obtain a Cipher object
        Cipher cipher = Cipher.getInstance(transformation);
        // Specify the key rule
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        / / 3. Decryption
        byte[] bytes = cipher.doFinal(Base64.decode(input));

        return newString(bytes); }}Copy the code

Run the program: AES encryption key, need to pass 16 bytes

ToString () and new String(

For example,

package com.atguigu;


import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


public class TestBase64 {
    public static void main(String[] args) {
        String str="TU0jV0xBTiNVYys5bEdiUjZlNU45aHJ0bTdDQStBPT0jNjQ2NDY1Njk4IzM5OTkwMDAwMzAwMA==";


        String rlt1=newString(Base64.decode(str)); String rlt2=Base64.decode(str).toString(); System.out.println(rlt1); System.out.println(rlt2); }}Copy the code

The results are as follows:

MM#WLAN#Uc+9lGbR6e5N9hrtm7CA+A==#646465698#399900003000

[B@1540e19d
Copy the code

Which one is correct? Why is that?

The new String() method should be used here, because Base64 encryption and decryption is a principle for converting encoding formats

ToString () differs from new String()

STR. ToString is the toString method of the class that calls this object. [class name]@[hashCode]

The new String(STR) is decoded into characters using the Java virtual machine’s default encoding format, based on the fact that parameter is an array of bytes. If the default ENCODING format of the VM is ISO-8859-1, the characters corresponding to the bytes can be obtained based on the ASCII encoding table.

And when and how?

New String() is generally used when character transcoding,byte[] array

The toString() object is used for printing


To be continued…