Common encryption and decryption algorithms implemented in Java
Java is a very popular programming language that is widely used in various fields. In practical applications, data encryption and decryption are very common requirements. Java provides many encryption and decryption algorithms. This article will briefly introduce several common algorithms.
1. Symmetric encryption algorithm
Symmetric encryption algorithm, also called private key encryption algorithm, uses the same key for encryption and decryption. Common symmetric encryption algorithms include DES, 3DES, AES, etc.
- DES algorithm
DES (Data Encryption Standard) is a classic symmetric encryption algorithm with a key length of 56 bits. When using the DES algorithm, you need to generate a key first, then use the key to encrypt the plaintext to obtain the ciphertext; then use the key to decrypt the ciphertext to obtain the plaintext. In Java, you can use the DES encryption and decryption function provided by JCE (Java Cryptography Extension). The sample code is as follows:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class DESUtil { private static final String ALGORITHM = "DES"; public static String encrypt(String content, String key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, String key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private 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); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; String key = "12345678"; String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
- 3DES algorithm
3DES (Triple DES) algorithm is an encryption algorithm enhanced on the basis of the DES algorithm. The key length is 168 Bit. The encryption and decryption process of the 3DES algorithm is similar to the DES algorithm and can be implemented using the JCE library provided by Java. The sample code is as follows:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class TripleDESUtil { private static final String ALGORITHM = "DESede"; private static byte[] initKey() throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM); kg.init(168); // 3DES的密钥长度为168位 SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded(); } public static String encrypt(String content, byte[] key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, byte[] key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private 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); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; byte[] key = initKey(); String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
- AES algorithm
The AES (Advanced Encryption Standard) algorithm is an advanced encryption standard and one of the most popular symmetric encryption algorithms currently. The key length of the AES algorithm is generally 128 bits, 192 bits or 256 bits. In Java, you can also use the AES encryption and decryption function provided by the JCE library. The sample code is as follows:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; public class AESUtil { private static final String ALGORITHM = "AES"; private static byte[] initKey() throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM); kg.init(128); // AES的密钥长度为128位、192位、256位 SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded(); } public static String encrypt(String content, byte[] key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); byte[] byteContent = content.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, byte[] key) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private 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); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; byte[] key = initKey(); String encrypt = encrypt(content, key); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, key); System.out.println("解密后:" + decrypt); } }
2. Asymmetric encryption algorithm
The asymmetric encryption algorithm is also called the public key encryption algorithm, which uses different keys for encryption and decryption. Common asymmetric encryption algorithms include the RSA algorithm.
- RSA algorithm
RSA algorithm is an asymmetric encryption algorithm and a number theory encryption algorithm based on large integers. The characteristic of the RSA algorithm is that the public key can be made public and the key is private, so it is highly secure. In Java, you can also use the RSA encryption and decryption functions provided by the JCE library. The sample code is as follows:
import javax.crypto.Cipher; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; public class RSAUtil { private static final String ALGORITHM = "RSA"; private static KeyPair getKeyPair(int keySize) throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); keyPairGenerator.initialize(keySize); return keyPairGenerator.generateKeyPair(); } public static String encrypt(String content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] byteContent = content.getBytes(); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } public static String decrypt(String content, PrivateKey privateKey) throws Exception { byte[] decryptFrom = parseHexStr2Byte(content); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] result = cipher.doFinal(decryptFrom); return new String(result); } private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (byte b : buf) { String hex = Integer.toHexString(b & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private 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); } return result; } public static void main(String[] args) throws Exception { String content = "Hello World!"; KeyPair keyPair = getKeyPair(1024); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); String encrypt = encrypt(content, publicKey); System.out.println("加密后:" + encrypt); String decrypt = decrypt(encrypt, privateKey); System.out.println("解密后:" + decrypt); } }
The above are several common encryption and decryption algorithms implemented in Java. In actual applications, it is necessary to choose the encryption and decryption algorithm that suits you according to the actual situation, and adjust and optimize it according to specific needs.
The above is the detailed content of Common encryption and decryption algorithms implemented in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.
