Summary of basic knowledge of cryptography

Fundamentals of Cryptography (National Security Without Cybersecurity)

1. Five Questions of the Soul

1. What is a password?

​Secret refers to technologies, products and services that use specific transformation methods to encrypt, protect and authenticate information, etc.

2. What is cryptography?

​Cryptography is the technology and science of studying codes and deciphering them.

3. What is face coding?

The study of the objective laws of cipher changes and the application of ciphers to protect communication secrets has become cryptography.

4. Cryptanalysis and deciphering?

Applied to deciphering codes to obtain communication intelligence, it has become cryptanalysis and cracking medicine.

Cryptography mainly solves: confidentiality, integrity, message source authentication, authentication of communication entities, and non-repudiation

5. What is the basic idea of ​​cipher?

Masquerading to conceal information so that unauthorized persons cannot understand its true meaning.

3. Overview

1. The basic composition of password physique

(1) Plaintext space M: the collection of all plaintexts

(2) Ciphertext space C: the collection of all ciphertexts

(3) Key space K: the set of all keys, k=<Ke,Kd>, Ke encrypts, Kd decrypts

(4) Encryption algorithm E: a cluster of encrypted transformations from M—>C

(5) Decryption algorithm D: a cluster of decryption transformations from C—>M

2. Classification of cryptosystems

1. Divide from whether the encryption key and the decryption key are equal

(1) Traditional passwords (Ke=kd): DES, AES, SMS4, RC4

(2) Public key cryptography (Ke != Kd)

​ Ke != kd, and since Ke cannot calculate Kd, Ke can be made public, which will not harm Kd

​ Typical ciphers: RSA, EIGaMAL, ECC

2. Divided from the way the key is used

(1) Serial password

​ Plaintext, ciphertext, and key are encrypted and decrypted in bit (character) units

​ The mainstream of core passwords

​ Typical passwords: RC4, Zu Chongzhi's password

(2) block cipher

​ Ciphertext, ciphertext, and key are encrypted and decrypted in groups

​ Commercial ciphers are mainstream

​ Typical ciphers: DES, AES, SMS4

3. Whether the cryptographic algorithm changes or not

​ The algorithm of the password is fixed during the working process, and the key is variable

​ The vast majority of ciphers to date are fixed algorithms

​ Typical ciphers: AES, DES, SMS4, RC4, RSA, EIGAMAL, ECC

3. Classification of Cryptanalysis

1. Mathematics-based analysis

The so-called mathematical analysis means that the cryptanalyst deciphers the password through mathematical analysis for the mathematical sentence of the encryption algorithm.

Statistical analysis attack: Deciphering passwords by analyzing the statistical laws of ciphertext and plaintext

2. Based on non-mathematical analysis

The so-called non-mathematical-based analysis means that cryptanalysts obtain and analyze the physical parameters of the chip (such as power, current, sound, execution time, etc.) to decipher the code. This attack is also known as a side channel attack.

The principle of side channel attack is that

(1) The power, current, time, and sound produced by the cryptographic chip are different when executing different instructions

(2) The power, current, time, and sound that the encryption chip consumes when processing different data are different

3. Classification according to the occupied data resources

(1) The attacker can always obtain the ciphertext

(2) The attacker can always know the cryptographic algorithm, but not the key

(3) The attacker has sufficient computing resources

4. What are the algorithms used to solve different problems?

Masquerading to conceal information so that unauthorized persons cannot understand its true meaning.

To solve confidentiality: symmetric key encryption (stream cipher, block cipher), public key and encryption

Addressing integrity: hash functions, message digest functions

Solve authentication: digital signature, identity authentication protocol

Addressing Non-Repudiation: Digital Signatures

5. Introduction of symmetric encryption, asymmetric encryption, and Hash

1. Symmetric key encryption algorithm

The characteristics of the symmetric key encryption algorithm: the encryption and decryption keys are the same, and the speed of encryption and decryption is fast

Common algorithms: Zu Chongzhi algorithm (ZUC), DES, AES, SM4, etc.

2. Asymmetric key encryption algorithm (public key cryptosystem)

insert image description here

The characteristics of asymmetric encryption: the encryption and decryption keys are different, and the encryption and decryption speed is slow

Application: short message encryption, digital signature, identity authentication

Common algorithms: RSA, ECC, SM2

3. Hash algorithm

Features: ①Arbitrarily long input is mapped to fixed-length output; ②When the input changes, the output changes unpredictablely; ③The output cannot be derived from the input;

Application: Integrity Check

Common algorithms: MD5, SM3

4. The Timeline of Cryptography Development

insert image description here

Ancient cryptography: From the beginning of human beings to 1800, it was previously regarded as an art, and there was no reasoning to prove that it was designed and analyzed purely by intuition. There are 500B.C (before 500 AD) ancient Spartan "Book of Heaven" cipher (replacement cipher), 205-123BC ancient Greek chess cipher (replacement cipher); 50BC, ancient Roman Caesar encryption (replacement cipher); 16th century , Virginia Cipher (instead of Cipher)

5. Classical Cryptography

5.1 Replace password

1. Rearrange the letters in the plaintext. The letters themselves remain unchanged, but their positions are changed. The passwords arranged in this way are called permutation passwords.

#例如:把明文中的字母颠倒过来,然后截取固定长度的字母组作为密文

#明文:明晨五点行动
MING CHNEG WU DIAN XING DONG

#密文:
GNODG NIXNA IDUWG ENHCG NIM

2. Arrange the plaintext into a matrix in a certain order, then select the letters in the matrix in another order to form the ciphertext, and finally cut it into fixed-length letter groups as the ciphertext.

#例如:明晨五点反攻

#明文:
MING CHENG WU DIAN FAN GONG

#矩阵:

MINGCH

ENWUDI

ANFANG

ONG###

#选出顺序:按列

#密文:
MEAO INNN  NWFG GUA# CDN# HIG#

Theoretically, the encryption key of the permutation cipher is the permutation matrix P, and the decryption key is the inverse of the permutation proof p

Permutation ciphers cannot withstand known plaintext attacks

5.2 Substitution of passwords

First construct one or more ciphertext alphabets, and then replace plaintext letters or letter groups with letters or letter groups in secret alphabets. The relative position of each letter or letter group remains unchanged, but itself changes.

5.2.1 Single table replacement: mainly appearing in English letters

1. The concept of single table replacement: use fixed information to replace the original text with cipher text. For example: bee, replace b with w, e with p, the word becomes wpp

2. Classification of single-table substitution ciphers: additive ciphers, multiplicative ciphers, and affine ciphers

3. Unable to withstand exhaustive attacks

5.2.1.1 Additive ciphers

insert image description here

1. Caesar encryption: know the decryption rules, Caesar encryption is an encryption method (k=3)
insert image description here
principle: shift 26 letters, move to the left or to the right, and pay attention to only moving 25 digits at most when moving

For example: abcd moves backward two cdef

package com.liping.ascii;

/**
 *凯撒加密
 */
public class AsciiDemo {
    
    

    public static  void main(String [] args){
    
    
        //定义原文
        String input = "Hello world";
        //字母向后移动位数
        int key = 3;
        //凯撒加密
        String s =encryptKaiser(input,key);
        System.out.println("密文是:"+ s);

        //解密
        String s1=decryptKasier(s,key);
        System.out.println("明文是:"+ s1);

    }

    /**
     *解密
     * @param s
     * @param key
     * @return
     */
    private static String decryptKasier(String s, int key) {
    
    
        char [] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char aChar : chars) {
    
    
            int b = aChar;
            b = b - key;
            char newb = (char)b;
            sb.append(newb);
        }
        return sb.toString();
    }


    /**
     * 加密
     * @param input
     * @return
     */
    private static String  encryptKaiser(String input,int key) {
    
    
        //把字符串转换成数组
        char [] chars = input.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char achar:chars){
    
    
            int b = achar;
            b = b + key;
            char newc = (char)b;
            sb.append(newc);
        }
//        System.out.println("密文是:"+sb.toString());
        return sb.toString();
    }
}


5.2.1.2 Multiplication cipher (k has 12 choices)

It is required that k are mutually prime numbers
insert image description here

5.2.1.3 Affine ciphers (k has 12 choices, b has 26 choices)

insert image description here
insert image description here

5.2.2 Multi-table replacement

Indicates that there are multiple tables, the original text and the cipher text are compared, and the typical password is the Virginia password (Vigenere)
insert image description here

Virginia example
insert image description here

Explanation of mathematical language:

5.3 Algebraic ciphers

Vernam cipher: plaintext, ciphertext, and key all represent binary bits

M=m1,m2,m3,m4...mn

K=k1,k2,k3,k4…kn

C=C1,C2,C3,C4…Cn

Encryption and decryption are all modulo 2 operations

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-4Oi6jieE-1661609172341) (D:\MD note\pictures\vernam)]
Vernam ciphers cannot withstand known plaintext attacks. If the key sequence is repeated, Vernam ciphers are insecure.

One-time pad in extreme cases, but not practical

5.3 Cracking method: frequency analysis method, without knowing the cracking rules

​ Frequency analysis method: probability theory, without knowing the cracking rules, sort in the order of frequency

6. Modern Cryptography

1. The core of the Enigma cipher machine
is also the shift and substitution method, which was cracked by Turing

2. Zu Chongzhi sequence cipher algorithm

​ Meaning: The ZUC algorithm is a word-based synchronous sequence cipher algorithm, the length of the seed key SK and the initial vector IV are both 128 bits.

​ ZUC algorithm structure

​ The first layer: linear feedback shift register layer

​ The second layer: bit storage layer

​ The third layer: linear function

2.1 Symbol meaning of Zu Chongzhi's password
insert image description here
2.2 Algorithm structure of Zu Chongzhi's password
insert image description here

7. Modern Cryptography

1. Hash function

​ Hash function is also called hash function

​ Common encryption methods: MD5, SHA-1, SHA256

MD5 can generate a 128-bit (16-byte) hash value from an original text of any length

​ SHA-1 can generate a 160-bit (20-byte) hash value from an original text of any length

2. Symmetric encryption

Symmetric encryption uses the same key for encryption and decryption

3. Asymmetric encryption

①Asymmetric encryption: also known as modern encryption algorithm

②Asymmetric encryption algorithm requires two secret keys, one public key and one private key

③The public key and the private key are a pair, called a secret key pair; if the public key is used to encrypt, the private key must be used to decrypt; if the private key is used to encrypt, the public key must be used to decrypt

(Asymmetric encryption, there are two secret keys, use the public key to encrypt, must use the private key to decrypt; or private key encryption must use the public key to decrypt)

Common asymmetric encryption algorithm:​RSA algorithm

4. How to set a password to be safe

1. Passwords should not be too common

2. The password settings in each application software are different, otherwise there may be a crash

3. Add some special marks when setting the password, an application + password

5. The relationship between Byte and bit

1. If UTF-8 encoding format is used, a Chinese character corresponds to 3 bytes

2. If the GBK encoding format is used, a Chinese character corresponds to 2 bytes

3. If the format corresponds to English, there is no encoding concept, and all correspond to one byte

package com.liping.bytebit;
import java.io.UnsupportedEncodingException;
import java.sql.SQLOutput;

public class ByteBitDemo {
    
    

    /**
     * 编码方式是utf-8一个中文对应三个bit'
     *
     * 如果是jbk一个中文对应两个字节
     * @param args
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
    
    
        String a = "李";
        //现在默认是utf-8
//        byte [] bytes =a.getBytes();
        //现在设置为GBK,同时需要抛出异常
        byte [] bytes = a.getBytes("GBK");
        for (byte aByte : bytes) {
    
    
            System.out.println(aByte);
            String s = Integer.toBinaryString(aByte);
            System.out.println(s);
        }
    }
}

Eight, modern encryption (symmetric encryption)

8.1 Stream encryption: encrypt one by one

1. Golomb pseudo-random postulate

Three postulates of randomness:

(1) In one cycle of the sequence, the difference between the number of 0 and 1 is as much as 1. (It shows that the probability of occurrence of 0 and 1 is basically the same)

(2) In one cycle of the sequence, the length of the run of i accounts for 1/(2^i) of the total number of runs, and the number of runs of 0 and the number of runs of 1 are equal in the runs of equal length. (Indicating that 0 and 1 have the same probability of appearing in each position in the sequence)

(3) Out-of-phase autocorrelation function is a constant function. (No other information can be given by comparing the sequence with the translated sequence)

8.2 Block Encryption: Block Encryption

1. Security Design Principle: Confusion Principle

​ The principle of confusion is to make the sibling relationship and algebraic relationship between ciphertext, plaintext, and key as complicated as possible. Even if the adversary obtains the ciphertext and plaintext, he cannot find any information about the key; even if he obtains the statistical laws of the Mi Wen and plaintext, he cannot find new information about the plaintext.

2. Meet the requirements

(1) The packet length n must be large enough to prevent exhaustive plaintext attacks from working

(2) The amount of keys should be large enough to eliminate weak keys as much as possible to prevent key exhaustion attacks from working

(3) The algorithm for permutation determined by the key should be complex enough

(4) Encryption and decryption operations are simple, easy to implement at high speed by software and hardware

(5) The error propagation should be as small as possible, and one ciphertext block will affect the decryption of other ciphertext blocks as little as possible.

3. SP network (proposed by Shannon)

Overview of substitution: If the block lengths of plaintext and ciphertext are both nbit, then each block of plaintext has 2^n possibilities. Each block of plaintext generates a unique block of ciphertext, and such transformation is reversible, which is called the reversible transformation of plaintext to ciphertext block as substitution.

(1) alternative

(2) replacement
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-8HqfGIsD-1661609172342) (D:\MD notes\pictures\wheel function)]

4. Feistel password

4.1 Design thinking

A product cipher refers to the sequential execution of two or more basic cryptosystems such that the final result is cryptographically stronger than the result produced by each basic cryptosystem

Parameters of the Feistel network implementation

(1) Group size: the larger the group, the higher the security and the slower the encryption speed

(2) Key size: the longer the key, the higher the security and the slower the encryption speed

(3) Number of rounds: A single-wheel structure is not enough to ensure safety, and a multi-wheel structure can ensure safety. The typical number of rounds is sixteen.

(5) Sub-key generation algorithm: The greater the complexity of the algorithm, the greater the difficulty of cryptanalysis.

(6) Round function: The greater the complexity of the round function, the greater the difficulty of cryptanalysis

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-eDg6fFQm-1661609172343) (D:\MD note\pictures\Feistel structure)]

4.2 Encryption structureinsert image description here

Feistal decryption process:
insert image description here

5. Typical of Feistal cipher: DES algorithm (Data Encryptography Standard)

5.1 DES development history

(1) In 1937, the US National Bureau of Standards publicly solicited encryption algorithms from the public to specify encryption algorithm standards.

(2) The second solicitation in 1974

(3) IBM's algorithm was selected in 1975 and published for comments

(4) Officially promulgated on January 15, 1977

(5) The encryption was disabled after the end of 1998

(6) 3DES was promulgated in 1999, and it is also compatible with the previous encryption methods

5.2 Overview of DES algorithm (16 rounds of feistal)

1. Main purpose

(1) Encryption protects non-confidential sensitive data of government agencies and commercial sectors

(2) Encryption protects static storage and then transmits data in the channel.

2. Features of DES cipher

(1) The packet length is 64bit

(2) The ciphertext block length is 64bit

(3) The key length is 64bit, with 8bit parity, and the effective number of bits is 56bit

(4) Inversion operation

The involution operation in mathematics refers to f(f(x))=x.

In DES, it means that encryption and decryption can share the same operation.

(5) Mainly included algorithms: initial permutation IP, product transformation of 16 rounds of iterations , inverse of inverse initial permutation IP and 16 subkey generators

5.3DES encryption process

1. The 64-bit key generates 16 sub-keys K1, K2, K3...K16 through the sub-key generation algorithm, each of which provides an encryption iteration

2. The 64-bit plaintext is replaced by the IP after the initial test, and the data is scrambled and rearranged and divided into left and right halves. Left L0, Right R0

3. Start encryption iteration

First encryption iteration:

L1=R0

R1=L0 and upper f(R0,K1)

second to fifteenth

The right side has never done any calculation, and it is directly assigned to the next left side Li=R(i-1)

The next time the right side passes Li=L(i-1) and the upper f(R i-1,K1)

insert image description here

5.4 Subkey generation process

insert image description here

The role of 1 permutation selection in the process of subkey generation

1. Remove the 8 parity checks in the key

2. Shuffle rearrangement to form left 28 bits, right 28 bits (64-8)/2

form a new matrix

insert image description here

insert image description here

4. After the sixteenth encryption iteration, a 64-bit data group is generated, with the left 32 bits as R16 and the right 32 bits as L16.

5. Merge R16L16, do the inverse of the inverse initial permutation IP, rearrange the data, and get 64-bit ciphertext

6. Encryption function: the core of DES secrecy

Substitute function group S (S box)

General properties of S-boxes

(1) The S-box is the nonlinear transformation of the displacement in DES, and it is the key to the safety of DES.

(2) Confusing in terms of confidentiality

(3) There are 8 S boxes in total, acting in parallel

(4) Each S-box has 6 inputs and 4 outputs, which is a nonlinear compression transformation

(5) Let the input be b1b2b3b4b5b6, then b1b6 forms the row number in binary form, b2b3b4b4 forms the column number of the binary number, and the intersection point is the output (binary)

insert image description here

5.5 Multiple DES algorithm

Double DES, by Diffie and Hellman

6.AES

1. The background of AES generation

(1) In December 1984, President Reagan ordered the National Security Agency (NSA) to develop a standard to replace DES

(2) In 1991, the new password began to solicit opinions, and the algorithm was not disclosed, only the chip was provided

(3) The new encryption standard EES was promulgated in 1994

(4) In May 1995, M.Blaze, a doctoral student at Bell Labs, successfully attacked legal fields on a computer for 45 minutes

(5) In July 1995, EES data encryption was abandoned

(6) In 1997, the U.S. government publicly collected AES from the public

2. AES design requirements

(1) Security: Can resist all known attacks

(2) Practicality: adapt to various application environments, and the speed of encryption and decryption is fast

(3) Scalability: The block length and key length can be extended to adapt to the increasing demands of the society on confidentiality

3. AES design requirements

(1) Block cipher: both ciphertext and plaintext are 128 bits long, and the key length can be changed (128/192/256, now choose 128 bits)

(2) Binary-oriented cryptographic algorithm: can encrypt any form of computer data

(3) You are an involution operation: the algorithms for encryption and decryption are different

(5) Comprehensive use of multiple cryptographic techniques: permutation, substitution, algebra

(6) Overall structure: SP structure, basic round function iteration, variable discussion of iteration

4. Mathematical basis of AES

(1) The basic domain of AES is the finite field GF(2^8)

(2) All 256 values ​​of a byte form a GF(2^8)

(3) An 8-degree polynomial on GF(2) can generate a GF(2^8)

(4) All the elements of GF(2^8) can also add commutative groups and linear spaces

(5) The non-zero elements of GF(2^8) form a multiplicative cyclic group

(6) The elements in GF(2^8) have multiple representations

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-26mMzktT-1661609172345) (D:\MD note\pictures\GF multiple representations.png)]

5. GF (2^8) representation of AES

addition:

insert image description here

multiplication
insert image description here

xtime
insert image description here

6. Sub-representation and operation of AES

  1. The unit of AES data processing is byte and word

  2. One word = 4 bytes = 32 bits

  3. A word can be expressed as a polynomial whose coefficients are taken from GF(2^8) with a degree lower than 4

  4. Word addition: two polynomial coefficients are added modulo 2

  5. Word multiplication: Let a and c be two words, a(x) and c(x) are their word polynomials, AES defines the score b of a and c as b(x)=a(x)c(x)modx^ 4+1

7. Basic transformation of AES
insert image description here
1. Encryption process
(1) Preliminary transformation
insert image description here

(2) Nine-round cycle
1) Byte substitution
insert image description here
2) Row shift
insert image description here3) Column mixing
insert image description here
4) Round key addition
insert image description here

5) Expansion of the round key
insert image description here

2. S box transformation

(1) S-box transformation is the only nonlinear transformation of AES, which is the key to AES security

(2) AES uses 16 identical S boxes, and DES uses 8 different S boxes

(3) The S box of AES has 8-bit input and 8-bit output, which is a nonlinear permutation

​ The S box of DES has 6-bit input and 4-bit output, which is a non-linear compression

3. Row shift transformation

(1) The row shift transformation performs a circular shift on the state

(2) The zeroth line does not shift, the first line moves C1 bytes, the second line moves C2 bytes, and the third line moves C3 bytes

(3) Row transformation belongs to permutation and linear transformation, and its essence is to scramble and rearrange the data and play a role of diffusion.

6.3 Characteristics of Symmetric Encryption

1. Fast encryption speed

2. The ciphertext is irreversible and the secret key cannot be revealed

3. If the corresponding character cannot be found on the code table, garbled characters will appear

4. Generally need to be used in combination with Base64

Nine, block cipher

Working mode of block cipher

1. Electronic codebook mode (ECB)

​ Directly use the block cipher to encrypt each block of the sensitive text
insert image description here

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-KITtJFx2-1661609172345) (D:\MD notes\pictures\codebook lost)]

insert image description here

The codebook method is the basic working mode of the block cipher

shortcoming:

Shortages may occur, which require special handling

The key K is fixed, if Mi=Mj, then Ci=Cj, thus exposing the plaintext data mode

2. Ciphertext Feedback Chaining Mode (CBC)

2.1 Ciphertext Feedback Connection Mode
In the CBC mode, each cipher block to be encrypted will be XORed with the ciphertext of the previous cipher block before being encrypted, and then encrypted with an encryptor. The first block of plaintext is XORed with a block of data called an initialization vector

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-z1CxmWEp-1661609172346) (D:\MD notes\pictures\ciphertext feedback connection mode)]
insert image description here

Advantages: It can cover up the plaintext structure information and ensure that the same ciphertext can get different plaintext, so it is not easy to actively attack, and the security is better than ECB, suitable for

The transmission of long-length packets is the standard of SSL and lPSec.

Disadvantages:
(1) Not conducive to parallel computing;

(2) Transmission error - if the previous one is wrong, the subsequent ones will be all wrong;

(3) The first plaintext block needs to be compared with an initialization vector IV, and the selection of the initialization vector Iv is more complicated

Encryption: Unbounded error propagation: Mi or Ci-1 errors will affect Ci and all subsequent ciphertext errors

Deciphering: Bounded Error Propagation

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hi5LcRjA-1661609172346) (D:\MD note\pictures\cipher text link method)]

3. Output Feedback Mode (OFB)

That is how to implement the use of block ciphers to implement sequence ciphers

Converts a block cipher into a key sequence generator. In this way, block ciphers can be used for encryption and decryption in the manner of stream ciphers

A shift register is used, and R0 is the initial content, called the seed.

If the block cipher is secure, the resulting key sequence is also secure

There is no error propagation in encryption and decryption.
OFB first uses a block cipher to generate a key stream (Keystream), and then XORs the key stream with the plaintext stream to obtain a ciphertext stream. Decryption uses a block cipher first.

Generate the key stream, and then XOR the key stream and the ciphertext stream to obtain the plaintext. Due to the symmetry of the XOR operation, the encryption and decryption processes are exactly the same.

Do you think it is very similar to CFB encryption?

Like CFB, OFB is very suitable for encrypting streaming data. Since OFB encryption and decryption depend on the previous data, encryption and decryption cannot be performed in parallel.

Advantages: hides the plaintext mode; combines block encryption and stream cipher (block cipher is converted to stream mode); can encrypt and transmit data smaller than the block in time.

Disadvantages: not conducive to parallel computing; need to generate key stream; active attack on plaintext is possible.

insert image description here

4. Cipher Feedback Mode (CFB)

When different from OFB, feed back the ciphertext to the shift register

Encryption: Encryption means that if the plaintext is wrong by one bit, it will affect the corresponding ciphertext error. After this error is fed back to the shift register, it will affect the subsequent key sequence to be wrong, resulting in all subsequent ciphertext errors.

Decryption: When decrypting, if the ciphertext is wrong by one bit, it will not only affect the corresponding plaintext error, but also the error feedback of the ciphertext will affect the subsequent honeymoon sequence error after being sent to the shift register, resulting in all subsequent plaintext errors

Error Propagation Unbounded
insert image description here

5.X CBC

It is an extension of CBC, recommended as the working mode of AES

The main solution of XCBC is that CBC requires that the length of plaintext data is an integer multiple of the length of the cipher block, and can handle data of any length.
insert image description here

The difference between X CBC and CBC

CBC requires that the last data block is a standard block, not a short block

The last block of data is encrypted differently than CBC

Because there is padding, the padding length information needs to be transmitted

X CBC allows the last data block to be either a standard block or a short block

Main advantages of X CBC mode

Can handle data of any length.

It is suitable for calculating and generating a message authentication code MAC for detecting data integrity.

The main disadvantages of X CBC mode:

With padding, not suitable for file and database encryption.

Using 3 keys requires the transmission padding length, which is complicated to control.

6. CTR mode
Calculator mode is not common. In CTR mode, there is an auto-increment operator. The output of this operator encrypted with the key and the plaintext XOR result are obtained

To the ciphertext, it is equivalent to a one-time pad. This encryption method is simple, fast, safe and reliable, and can be encrypted in parallel, but it cannot be maintained for a long time in the computer.

In this case, the key can only be used once.

Advantages: no disclosure of plaintext; only need to implement encryption function; no padding; parallel computing. Disadvantages: The instantaneous value IV is required, and it is difficult to guarantee the uniqueness of lIVv

CTR encryption process

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-r331jdLY-1661609172347) (D:\MD note\pictures\CTR)]

CTR decryption process

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-XT3jTx1O-1661609172347) (D:\MD note\pictures\CTR1)]
insert image description here

Advantages of CTR working mode:

The advantages of CTR mode are safe, efficient, parallelizable, and suitable for data of any length;

The calculation of 0i can be pre-processed at high speed;

Since the encryption is implemented by adding touch 2, it is an inversion operation, and the decryption operation is the same as the encryption operation.

Suitable for decryption of randomly stored data.

Disadvantages of CTR mode:

There is no error propagation, so data integrity cannot be easily ensured.

short block encryption

A block cipher can only encrypt one fixed-length block of plaintext at a time

A data block whose length is less than the packet length is a short block

Reasonable techniques must be employed to solve the short block encryption problem

Short block processing technology:

1. Filling technology

Fill short blocks with useless data to make them standard blocks. The padding is random and may cause memory overflow, so it is not suitable for file and database encryption

2. Ciphertext Misappropriation Technology

3. Serial encryption

3.1 Classification of sequence ciphers

The key sequence generation algorithm has nothing to do with the plaintext, and the generated key sequence has nothing to do with the plaintext.

(1) Synchronous sequence password

There is no error propagation. When some ciphertext characters in the communication generate errors, only the decryption of the corresponding characters is affected, and other characters are not affected.

(2) Self-synchronizing serial cipher

Assuming that the key sequence generator has n bits of storage, a ciphertext error during encryption will affect subsequent n consecutive ciphertext errors. Reverted correctly after this.

A single ciphertext error during decryption will also affect subsequent n consecutive plaintext errors.

Encryption will cause error propagation, but the error propagation is bounded, and the correctness will be restored after the error has passed

Linear Shift Register

3.2 Linear Shift Register

m sequence has good randomness

1. Run length: It is said that the i consecutive 1-bit lengths in the sequence are equal to the 1 run length of i

For the itinerary, see Extended Knowledge

2. Autocorrelation function

Let {ki} be a sequence with period p, and k0, k1,..., kp-1 be one of the periodic sub-segments, then k0+τ, k1+τ,..., kp-1+τ are also a periodic sub-segment. Note that the same number of digits in these two sub-sections is A, and the different number of digits is D, then the autocorrelation function is defined as:

R(j)=( A-D)/ P

The autocorrelation function reflects the degree to which the average bit is the same over a period

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-2x2SBN9O-1661609172347) (D:\MD notes\pictures\autocorrelation function)]

10. Overview of commercial block cipher SM4

1. my country's commercial encryption

(1) Adhere to the open design principles of passwords

(2) Open the original design

(3) Commercial ciphers should disclose their algorithms

2. Block Cipher

(1) Data grouping, plaintext, ciphertext length = 128 bits, key length = 128 bits

(2) Data processing unit: byte (8 bits), word (32 bits)

3. Cryptographic algorithm characteristics

Involution operation: the decryption algorithm is the same as the encryption algorithm

The subkey generation algorithm is similar to the encryption algorithm structure

4. Password structure

It is not an SP structure, nor a Feisel structure, but a new structure: the sliding window structure

SMS4 password algorithm structure
insert image description here

5. SMS4 password algorithm

1. Basic operations

​ Modulo 2 plus: 32-bit XOR operation

​ Cyclic shift: <<<i, 32-bit words rotate left by i bits

2. Basic password components

(1) Non-linear byte transformation component S-box:

​ 8-bit input, 8-bit output, essentially 8-bit non-linear permutation

​ Let the input be a, the output be b, and the S box operation is expressed as: b=S_Box(a)

S box data sheet:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-6W14nSW1-1661609172348) (S box in D:\MD notes\pictures\SMS4)]

The replacement rule of the S box: the first nibble of the input is the row number, the last nibble is the column number, and the data divided by the intersection of the row and column is the output. (For example: input "ef", e is the row number, f is the column number, the output value of S box is the value of the intersection point of row e, column f in the table, Sbox('ef')='84')

​ (2) Nonlinear word transformation τ: Nonlinear transformation of 32-bit words

​ Parallel replacement of 4 S boxes

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NMzn2h3g-1661609172348) (D:\MD notes\pictures\SMS4 nonlinear word transformationτ)]

​ (3) Word linear component L transformation: 32-bit input, 32-bit output. Let the input be B and the output be C, expressed as: C=L(B)

​ (4) Word synthesis transformation T: It is also formed by the addition of nonlinear transformation τ and linear transformation L

insert image description here

3. Round function F

​ Input data: (X0, X1, X2, X3), 128 bits, four 32-bit words

​ Input round key: rk, 32-bit word

​ Output data: 32-bit word

​ Round function F:

insert image description here

Eleven, the basic idea of ​​public key cryptography

1. Basic idea of ​​public key cryptography

1. Divide the key K into two: Ke and Kd. Ke is dedicated to encryption, Kd is dedicated to decryption, Ke is not equal to Kd, and it is more convenient to realize digital signature

2. Ke cannot calculate Kd, so Ke can be made public to make key Ke distribution simple

2. Basic conditions for public key

Confidentiality condition: E and D are reciprocal D(E(M))=M

Safety condition: Ke is not equal to Kd, Ke cannot calculate Kd

Practicality: Both E and D are efficient

Fidelity condition: D(E(M))=M

The first three conditions are used for confidentiality, the last three are used for fidelity, and all four conditions are met for confidentiality and fidelity

Sender: A checks PKDB first, and finds B's public encryption key Keb. Then use Keb to encrypt M to get the ciphertext C=E(M, Keb), and finally send C to B.

Receiver: B accepts C, and B decrypts with his own Kdb to get the plaintext M=D(C,Kdb)=D(E(M,Keb),Kdb)

3. RSA public key cryptography

Encryption algorithm
1. Randomly select two different large prime numbers p and q, and calculate n=pq; φ(n)=(p-1)(q-1); 2. Select an e(1<e<p(
n )), and is relatively prime to p(n), that is, gcd(e,φ(n))=1;
3. Calculate the inverse element d of e and φ(n), (de) mod φ(n)= 1 ;
4. Public key: KU=(e,n);
5. Private key KR=(d,n)

The modulo inversion operation
gcd(e, φ(n))=1, then an integer d can be found, so that ed-1 is divisible by φ(n), or the remainder obtained by ed divisible by φ(n) is 1 ed-1
= kφ(n)
(ed) modφ(n)=1
insert image description here

12. Hash

1. Features:

(1) Irreversibility

(2) Strong anti-collision (different data Hash values ​​are different, and the same data Hash values ​​are the same)

(3) There are slight changes in the original data, but the changes in the hash value are very large

(4) Operate the original data through the hash function, and the length of the obtained hash value is fixed

(5) The original hash value is a fixed-length binary string

2. Hash algorithm

2.1MD5

​ Hash value: 16b

2.2SHA2

2.2.1sha1

​ Hash value: 20byte

2.2.2sha224

​ Hash value: 28byte

2.2.3sha256

​ Hash value: 32byte

2.2.4sha384

​ Hash value: 48byte

2.2.5sha512

​ Hash value: 64byte

13. Digital signature

It is not the only thing that cannot be digitally signed, so the digital signature uses asymmetric encryption

1. Three conditions that digital signatures meet

1. The signer cannot deny his signature afterwards

2. No one else can forge the signature

3. If there is a dispute between the two parties about the authenticity of the signature, they can confirm its authenticity through verification in front of a notarized arbitrator

2. Types of digital signatures

Universal signature, quorum signature, blind signature, group signature, threshold signature, proxy signature

3. A digital signature constitution includes two aspects of processing

1. Apply signature

The algorithm to apply the signature is SIG, the key to generate the signature is K, the signed data is M, and the signature information generated is S

S=SIG(M,k)

2. Verify the signature

The algorithm for verifying the signature is VER, which can be used to verify the signature to identify the authenticity of S

Fourteen, SM1, SM2, SM3, SM4, SM7, SM8, SM9 SMSMSM

1. SM1

SM1 is a block cipher, the block length and key are both 128 bits

2. SM2

The SM2 algorithm is an ECC elliptic curve cryptographic mechanism

Properties of Elliptic Curves

(1) The elliptic curve is combined with point addition operations on the finite field to form a finite commutative group, and the order at this time is similar to the size of the base field

(2) Do multiple point operations on the elliptic curve to form a one-way function

3. SM3

SM3 hash algorithm

4.SM4

5. SM7

SM7 is a block encryption algorithm with block length and key length of 128

6. SM8

7. SM9

Identity-based cryptography algorithm IBC (Identity-Based Cryptography) includes the following modules

​ Digital signature

​ Key exchange

​ Key wrapping

​ Public key encryption

Identification: Information that uniquely identifies an entity. Identification should consist of information that cannot be repudiated by the entity. For example, ID number, phone number, etc.

The identification of SM9 is the public key, no public key certificate is required, and the link of the validity of the public key certificate becomes a simple confirmation identification

6.Base64

​ 1. Base64 is not an encryption algorithm, but a readability algorithm. The purpose is not to protect our data but for readable data

​ 2. The composition of base64: uppercase AZ, lowercase az, numbers: 0-9, two special symbols: + and /

3. Base64 is a group of three bytes, one byte is 8 bits, a total of 24 bits; convert three bytes into four groups, each group is 6 bits, and each group lacks two bits, because one byte It is 8 bits, with 0 in the high position

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

import javax.sound.midi.Soundbank;
import java.net.SocketTimeoutException;

public class Base64Test {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Base64.encode("李".getBytes()));
         /**
         * 1 表示 一个字节,不够3个字节,进行编码的时候用 = 不起
         * 12 表示两个字节,就补齐一个=
         */
        System.out.println(Base64.encode("1".getBytes()));
        System.out.println(Base64.encode("12".getBytes()));
        System.out.println(Base64.encode("123".getBytes()));
        System.out.println(Base64.encode("a".getBytes()));
    }
}

7.Base58 is an encoding method in Bitcoin

​ In base58 there is no number 0 and no letter o, no uppercase letter I and lowercase letter i, no + and /

9. Encryption mode

1.ECB: Split and encrypt a piece of text, use the same key to encrypt separately, and then combine them together.

2. CBC: When encrypting, it will depend on the previous vector, XOR the previous vector, and the following plaintext will always depend on the previous encryption key when encrypting.

10. Message Digest (SHA-1, SHA-256)

​ Message digests are also known as digital digests. It is generated by a single-item Hash encryption function acting on the message. Digital values ​​cannot be tampered with, in order to ensure the security of files or values.

Expand knowledge points:

1. Tour

In a cycle, 0 and 1 occur nearly equal times.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-majLWq6C-1661609172351) (D:\MD note\pictures\youcheng)]

2Arranging a cycle of a clockwise on the circumference once, with all 1s or 0s in the middle is called a run of 1 or a run of 0. The length of the run is the number of 1s or 0s in the middle.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-hp6l4ODZ-1661609172352) (D:\MD notes\pictures\youcheng.png)]

2. Strong pseudo primes

Using the Miller Rabin primality test method is a probabilistic method to detect whether a number is a strong pseudo-prime

Definition of Strong Pseudoprimes

insert image description here

3. The difference between symmetric encryption and asymmetric encryption

1. Symmetric encryption

Symmetric: Encryption and decryption use the same key

Advantages: fast speed and high efficiency

Disadvantages: It is difficult to exchange secret keys, it is difficult to exchange keys, there are many keys to manage, and there is no way to confirm the source of data

2. Asymmetric encryption

Asymmetric: public key encryption private key decryption

Advantages: The source of the data can be confirmed (confirmation of the source: encryption with the private key, and decryption with the corresponding public key can be realized)

Disadvantages: relatively low efficiency

3. For example: the process of visiting a website

1. The client sends a request, I want to communicate with you securely

2. The certificate of the web server is sent to the client (the composition of the certificate: Sca(PuWebSrv+CA+validity period)) (the web server will pass its own public key to the user)

3. The client usually trusts the CA, that is, the client obtains the public key of the web server

4. After getting the public key, generate a sessionkey on the client server, encrypt the sessionkey with the public key of the server just now, and then send it to the web server

5. The web server unlocks with its own private key to get the sessionkey

CA

/etc/pki/tls/openssl.cnf

Generate a private key: umask 077;openssl genrsa -out /etc/pki/CA/private/cakey.pem

openssl req -new -x509 -key /etc/pki/CA/private/cakey.pem -out /etc/pki/CA/cacert.pem -days 3650

touch /etc/pki/CA/index.txt

echo 01 > /etc/pki/CA/serial

openssl ca -in /tmp/test.csr -out /etc/pki/CA/certs/test.crt -days 200

client

umask 077;openssl genrsa -out /app/testkey.pem

openssl req -new -key /app/testkey.pem -out /app/test.csr

CN

Guess you like

Origin blog.csdn.net/qq_41977843/article/details/126563238