Home Java javaTutorial Common encryption and decryption algorithms implemented in Java

Common encryption and decryption algorithms implemented in Java

Jun 18, 2023 am 09:22 AM
java encryption and decryption algorithm

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.

  1. 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);
    }
}
Copy after login
  1. 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);
    }
}
Copy after login
  1. 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);
    }
}
Copy after login

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.

  1. 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);
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles