Java implementation of symmetric encryption (DES, AES) quick start example

Symmetric encryption uses the same password for encryption and decryption. Symmetric encryption is simple to implement, and its security is weaker than asymmetric encryption. Commonly used symmetric encryption algorithms include DES, AES, and PDE. For related concepts of symmetric encryption, refer to: Symmetric encryption
, In-depth analysis of asymmetric encryption

This article introduces the encryption and decryption of DES and AES in Java. For the implementation of encryption and decryption of the PDE algorithm, you can refer to:
Java uses the PBE algorithm for symmetric encryption and decryption and examples

DES encryption and decryption

In the Java language, the DES algorithm uses a key for encryption and decryption, and uses a cipher specification (DESKeySpec) and a key factory (SecretKeyFactory) to generate a key. The encryption and decryption operations are performed through the Cipher class, and "DES/ECB/PKCS5Padding" is used as the encryption algorithm and padding mode.

DES encryption sample code:

	/**
	 * DES 对称加密
	 */
	@Test
	public void desEncrypt() throws Exception {
		String plainText = "需要加密的内容";
		String secretKey = "this is password";
		DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes(StandardCharsets.UTF_8));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(desKeySpec);

		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);

		byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
		String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
		System.out.println("DES加密后的内容=" + encryptedText);
	}

DES decryption sample code:

	
	@Test
	public void desDecrypt() throws Exception {
		String encryptedText = "HAyFHQXRKmihGtxFsrZlAJwla4FE3aqS";
		String secretKey = "this is password";
		DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes(StandardCharsets.UTF_8));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(desKeySpec);

		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);

		byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
		String plainText = new String(decryptedBytes, StandardCharsets.UTF_8);
		System.out.println("DES解密的内容=" + plainText);
	}

Why is DES/ECB/PKCS5Padding here instead of DES directly?

DES/ECB/PKCS5Padding is a specification of encryption algorithm and mode, which is often used to encrypt and decrypt data.

Specifically:

  • DES (Data Encryption Standard) is a symmetric encryption algorithm that uses the same key (usually 56 bits long) for encryption and decryption operations.
  • ECB (Electronic Codebook) is an encryption mode that divides the input data into blocks, and each block performs encryption operations independently.
  • PKCS5Padding is a padding mode, which uses a specific padding method to fill when the length of the data block is insufficient, so that the length of each data block reaches the specified length.

Compared with other encryption algorithms and modes, DES/ECB/PKCS5Padding has the following advantages and disadvantages:

advantage:

  • The operation speed is relatively fast, which is suitable for encrypting and decrypting large data streams;

  • The implementation is relatively simple and can be implemented on a variety of programming languages ​​and platforms;

  • The encrypted data size will not increase.

shortcoming:

  • The ECB mode does not have randomness and repetition rate, and adjacent data blocks may generate the same ciphertext, which is vulnerable to attack;

  • The key length is short, the security is relatively low, and it is vulnerable to brute force cracking and cryptanalysis attacks;

Encrypting the same data with the same key, the ciphertext is always the same, making replay attacks and password attacks easy.

Therefore, for scenarios with high encryption performance requirements and relatively low security requirements, you can choose to use DES/ECB/PKCS5Padding for encryption and decryption operations. For scenarios with high security requirements, you should consider using more secure and reliable encryption algorithms and modes, such as AES, RSA, CBC, GCM, etc.

AES encryption and decryption

The encryption and decryption of AES is very similar to DES, just look at the code:

AES encryption code example:

	@Test
	public void encryptAES() throws Exception {
		String plainText = "需要加密的内容";
		String secretKey = "this is password";
		SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        String encryptedText =  Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("AES加密后的内容=" + encryptedText);
	}

AES decryption code example:

	@Test
	public void decryptAES() throws Exception {
		String encryptedText = "oL2b5xULTtAmfi4ujnpw/jPamo0nTNCgRC9Bo+SBz7k=";
		String secretKey = "this is password";
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
		String plainText = new String(decryptedBytes, StandardCharsets.UTF_8);
		System.out.println("AES解密的内容=" + plainText);
	}

AES (Advanced Encryption Standard) uses the same key for encryption and decryption operations. In this example, an AES key specification (SecretKeySpec) is constructed using the key string, and the encryption and decryption operations are performed through the Cipher class, and "AES/ECB/PKCS5Padding" is used as the encryption algorithm and padding mode.

It should be noted that AES is a block cipher algorithm, which is different from block ciphers such as DES, and it supports different key lengths, such as AES-128, AES-192, and AES-256.

In practical applications, in order to ensure security, the key should be long enough, and at the same time, it is necessary to ensure the safe generation, storage and transmission of the key.

Java 8 cannot find javax.crypto.spec.SecretKeySpec problem solving

In Java 11 and Java 17 versions, the above example works normally, but in Java 8, it will prompt that javax.crypto.spec.SecretKeySpec cannot be found. In the development based on Eclipse, although SecretKeySpec is imported, it will prompt that it cannot be found This class:

The import javax.crypto.spec.SecretKeySpec cannot be resolved

Here you need to download the jce extension package, download address:
https://www.oracle.com/java/technologies/javase-jce8-downloads.html

Unzip after downloading,
insert image description here

Put local_policy.jar and US_export_policy.jar into the security directory of JRE, for example C:\Program Files\Java\jdk1.8.0_361\jre\lib\security\policy\unlimited, overwrite the files with the same name in this directory:
insert image description here

Then import these two files in the Eclipse project.

online code



Guess you like

Origin blog.csdn.net/oscar999/article/details/132254062