5
头图
WeChat search: Code Farm StayUp
Homepage address: https://gozhuyinglong.github.io
Source sharing: https://github.com/gozhuyinglong/blog-demos

The previous article introduced " one-way hash encryption ", which is a message digest algorithm. This algorithm has many important application scenarios in the field of information security, such as: user password protection, digital signature, file integrity verification, cloud disk magic transmission, etc.

One-way hash encryption can only encrypt messages (strictly speaking, calculate the digest of the message). If you want to decrypt the ciphertext, you need to use other encryption methods. Today we introduce a more important encryption method in the field of information security-symmetric encryption.

The following is the content of this article:
目录

Encryption, decryption and keys

encryption (Encrypt) is a step to generate ciphertext from plaintext, decryption (Decrypt) is a step to restore plaintext from ciphertext, and both steps require key (Key). This is the same as in our reality, locking and unlocking with a key.

加密、解密和密钥

What is symmetric encryption

Symmetric encryption (Symmetric Cryptography) is a type of encryption algorithm in cryptography. This type of algorithm uses the same key for encryption and decryption.

Symmetric encryption is also called shared key encryption . Its biggest disadvantage is that the security of symmetric encryption relies on the key. Once it is leaked, it means that anyone can decrypt the message.

The advantage of symmetric encryption is that the encryption speed is fast, so it is used in many occasions.

Common algorithms

This section introduces some common algorithms for symmetric encryption, including DES, 3DES, and AES.

DES algorithm

DES (Data Encryption Standard, Chinese: Data Encryption Standard), is a symmetric encryption algorithm. The algorithm was determined as the Federal Data Processing Standard (FIPS) by the National Bureau of Standards of the United States Federal Government in 1976, and was released in 1977, and has since been widely circulated internationally. However, with the advancement of computers, DES has been able to be cracked by brute force, so the algorithm is no longer secure.

DES is a block cipher (Block Cipher, or ), that is, the plaintext is encrypted in blocks of 64 bits, and each group generates a 64-bit ciphertext. Its key length is 56 bits (in terms of specifications, the key length is 64 bits, but since every 7 bits is set for error checking, the actual length is 56 bits).

DES算法

3DES algorithm

(Triple Data Encryption Algorithm, abbreviated as TDEA), abbreviated as 3DES (Triple-DES), is an enhanced version of DES, which is equivalent to applying the DES algorithm three times to each group of data.

Because the key length of the DES algorithm is too short, it is easy to be cracked by brute force. In order to solve this problem, the algorithm was designed. It uses a simple method to avoid similar attacks by increasing the length of the DES key, rather than a brand new cryptographic algorithm.

This algorithm uses different keys each time DES is applied, so there are three independent keys. These three keys are composed of a key with a length of 168 (56 + 56 + 56) bits, so the total key length of the 3DES algorithm is 168 bits.

3DES encryption, not DES encryption three times (encrypted encryption → → encryption), but in key 1, key 2, key. 3 sequence, for encrypted decryption encryption the process of.

3DES加密

3DES encryption and decryption process on the contrary, is key 3, key 2, key. 1 sequence, for decrypting encryption decryption operation.

3DES解密

AES algorithm

AES (Advanced Encryption Standard), the Advanced Encryption Standard, is a new symmetric encryption algorithm that replaces the DES algorithm. The AES algorithm was contested from the symmetric encryption algorithms submitted by companies and cryptographers all over the world. In the end, the Rijndael encryption algorithm won, so AES is also called Rijndael encryption algorithm.

AES is also a block cipher, its block length is 128 bits, and the key length can be 128 bits, 192 bits, or 256 bits.

AES算法

Block cipher mode

The DES, 3DES, and AES described above are all block ciphers, and they can only encrypt a fixed-length plaintext. If you need to encrypt a longer plaintext, you need to iterate the block cipher, and the iterative method of the block cipher is called the mode of the (Model). In short: the mode of block cipher is the iterative method of block cipher.

There are many types of block ciphers, here are the following: ECB, CBC, CFB, OFB, CTR.

Plaintext grouping and ciphertext grouping

In the following introduction to the mode, two terms will be used. Here is an introduction:

In the block cipher, we call the plaintext of each group plaintext group , and the ciphertext generated by each group is called ciphertext group .

If all the plaintext groups are combined to form a complete plaintext (ignore the padding first), all the ciphertext groups are combined to form a complete ciphertext.

ECB mode

ECB (Electronic CodeBook) mode, namely electronic codebook mode. This mode is to group the plaintext into ciphertext groups directly after encryption, and there is no relationship between the groups.

ECB模式

The ECB mode is the simplest of all modes. The plaintext grouping and ciphertext grouping of this mode have a one-to-one correspondence. If the plaintext grouping is the same, the ciphertext grouping must be the same. Therefore, ECB mode is also the least secure mode.

CBC mode

CBC (Cipher Block Chaining) mode, namely cipher block chaining mode. This mode first performs XOR operation between the plaintext group and the previous ciphertext group, and then performs encryption. Only the first plaintext packet is special, and a bit sequence with the same length as the packet needs to be generated in advance for XOR operation. This bit sequence is called initialization vector (Initialization Vector), referred to as IV .

CBC模式

CFB mode

CFB (Cipher FeedBack) mode, namely cipher text feedback mode. This mode first encrypts the previous ciphertext group, and then performs an XOR operation with the current plaintext group to generate the ciphertext group. The CFB mode also requires an IV.

CFB模式

OFB mode

OFB (Output FeedBack) mode, that is, output feedback mode. This mode will generate a key stream, that is, the previous output value of the cryptographic algorithm as the input value of the current cryptographic algorithm. The input value is then XOR run with the plaintext grouping, and the ciphertext grouping is calculated. This mode requires an IV, which is encrypted as the input of the first packet.

OFB模式

CTR mode

CTR (CounTeR) mode, that is, counter mode. This mode also generates a key stream, which generates a continuous key stream by incrementing a counter. The counter is encrypted, and then XOR operation is performed with the plaintext group to calculate the ciphertext group.

CTR模式

Block cipher padding

In the block cipher, when the data length does not meet the block length, the tail plaintext needs to be filled in a certain way. This method of filling the tail group data is called padding (Padding).

No Padding

That is, no padding is required, and the length of the plaintext must be an integer multiple of the packet length of the encryption algorithm.

... | DD DD DD DD DD DD DD DD | DD DD DD DD DD DD DD DD |

ANSI X9.23

In the stuffing byte sequence, last byte filled require padding byte length , the remaining bytes of padding 0 .

... | DD DD DD DD DD DD DD DD | DD DD DD DD 00 00 00 04 |

ISO 10126

In the stuffing byte sequence, last byte filled require padding byte length , the remaining bytes of padding random number .

... | DD DD DD DD DD DD DD DD | DD DD DD DD 81 A6 23 04 |

PKCS#5 and PKCS#7

In the stuffing byte sequence, each byte filled require padding byte length .

... | DD DD DD DD DD DD DD DD | DD DD DD DD 04 04 04 04 |

ISO/IEC 7816-4

In the stuffing byte sequence, first byte fill a fixed value 80 , the remaining bytes of padding 0 . If only one byte needs to be filled, directly fill 80 .

... | DD DD DD DD DD DD DD DD | DD DD DD DD 80 00 00 00 |

... | DD DD DD DD DD DD DD DD | DD DD DD DD DD DD DD 80 |

Zero Padding

In the stuffing byte sequence, each byte filled 0 .

... | DD DD DD DD DD DD DD DD | DD DD DD DD 00 00 00 00 |

Java code implementation

Java has already encapsulated the implementation of symmetric encryption at the bottom, we just need to use it. Now introduce a few important classes:

SecureRandom class

The SecureRandom class is a strong and secure random number generator (Random Number Generator, referred to as: RNG), which is recommended for encryption related.

We can generate an instance through the constructor, or pass a seed to the constructor to create an instance.

SecureRandom random = new SecureRandom();

KeyGenerator class

The KeyGenerator class is the key generator for symmetric cryptography. It is necessary to specify the encryption algorithm to generate the corresponding key.

Algorithms supported in Java:

  • AES (128)
  • DES (56)
  • DESede (168)
  • HmacSHA1
  • HmacSHA256

The following is an introduction to some standard algorithms:

标准算法

The generated key code is as follows:

/**
 * 通过密码和算法获取 Key 对象
 *
 * @param key       密钥
 * @param algorithm 算法,例如:AES (128)、DES (56)、DESede (168)、HmacSHA1、HmacSHA256
 * @return 密钥 Key
 * @throws Exception
 */
private static Key getKey(byte[] key, String algorithm) throws Exception {
    // 通过算法获取 KeyGenerator 对象
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
    // 使用密钥做为随机数,初始化 KeyGenerator 对象
    keyGenerator.init(new SecureRandom(key));
    // 生成 Key
    return keyGenerator.generateKey();
}

Cipher class

The Cipher class provides encryption and decryption functions. This class needs to specify a transformation (Transformation) to create an instance. The naming method of the transformation is: algorithm name/working mode/filling method .

The following are the conversions supported by Java:

  • AES/CBC/NoPadding (128)
  • AES/CBC/PKCS5Padding (128)
  • AES/ECB/NoPadding (128)
  • AES/ECB/PKCS5Padding (128)
  • DES/CBC/NoPadding (56)
  • DES/CBC/PKCS5Padding (56)
  • DES/ECB/NoPadding (56)
  • DES/ECB/PKCS5Padding (56)
  • DESede/CBC/NoPadding (168)
  • DESede/CBC/PKCS5Padding (168)
  • DESede/ECB/NoPadding (168)
  • DESede/ECB/PKCS5Padding (168)
  • RSA/ECB/PKCS1Padding (1024, 2048)
  • RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
  • RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)

Here are some standard patterns:

标准模式

Here are some standard padding:

标准填充

The encryption code is as follows:

private static final String DES_ALGORITHM = "DES";
private static final String DES_TRANSFORMATION = "DES/ECB/PKCS5Padding";

/**
 * DES 加密
 *
 * @param data 原始数据
 * @param key  密钥
 * @return 密文
 */
private static byte[] encryptDES(byte[] data, byte[] key) throws Exception {
    // 获取 DES Key
    Key secretKey = getKey(key, DES_ALGORITHM);

    // 通过标准转换获取 Cipher 对象, 由该对象完成实际的加密操作
    Cipher cipher = Cipher.getInstance(DES_TRANSFORMATION);
    // 通过加密模式、密钥,初始化 Cipher 对象
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    // 生成密文
    return cipher.doFinal(data);
}

The decryption code is as follows:

private static final String DES_ALGORITHM = "DES";
private static final String DES_TRANSFORMATION = "DES/ECB/PKCS5Padding";

/**
 * DES 解密
 *
 * @param data 密文
 * @param key  密钥
 * @return 原始数据
 */
private static byte[] decryptDES(byte[] data, byte[] key) throws Exception {
    // 获取 DES Key
    Key secretKey = getKey(key, DES_ALGORITHM);
    // 通过标准转换获取 Cipher 对象, 由该对象完成实际的加密操作
    Cipher cipher = Cipher.getInstance(DES_TRANSFORMATION);
    // 通过解密模式、密钥,初始化 Cipher 对象
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    // 生成原始数据
    return cipher.doFinal(data);
}

Complete code

For the complete code, please visit my Github, if it is helpful to you, welcome to give me ⭐, thanks~~🌹🌹🌹

https://github.com/gozhuyinglong/blog-demos/blob/main/java-source-analysis/src/main/java/io/github/gozhuyinglong/utils/SymmetricKeyUtil.java

Recommended reading

扫码关注,不迷路


码农StayUp
66 声望11 粉丝

人生就是一个不断学习的过程,通过学习来充实自己的头脑,让自己更有智慧的生活下去,去探索那未知领域的神秘,去享受成长带来的快乐和惬意。