SoFunction
Updated on 2025-04-13

Examples of five common encryption algorithm usage methods in Java

1. BCrypt encryption

1.1 Brief description of BCrypt

BCrypt is a password hash function, that is, a one-way function, and cannot decrypt BCrypt hash.
It is a strong hashing algorithm that combines SHA-256, random salts and keys to enhance security

Features:
Uniqueness: The salt generated by each encryption is different, so the value of the password is also different;
Irreversible: Only verify that the two BCrypt hashes are the same, thereby verifying that the provided password matches the original password

Applicable scenarios: Encryption of user password

Encrypted characters consist of 4 parts:

$2a$10$N9qo8uLOickxx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZmL17lhWy

Identifier: The identifier of the BCrypt algorithm usually starts with $2a or $2b, and 2a is the encrypted version number;

Cost factor: where 10 represents the cost factor, here is the power of 2 to the 10th, which is 1024 rounds;

Salt: The following is 22-bit salt; the salt value is a 16-byte (128-bit) random value, which becomes a 22-character string after Base64 encoding;

Hash: The last 31-bit string is the hash value; it is usually a 24-byte (192-bit) original hash value, which becomes a 31-character string after Base64 encoding.

If you modify your password, you can send a one-time password reset link to the user, use secret questions or some other methods to confirm the user's identity information, and let them set a new password.

1.2 Code Example

BCryptPasswordEncoder is a method to encrypt passwords using BCrypt encryption algorithm

The main purpose is to prevent passwords from being stored in the database in plain text;

It is a class used in Spring Security to encrypt user passwords

When using the springBoot project, you need to introduce dependencies:

<dependency>
      <groupId></groupId>
      <artifactId>spring‐boot‐starter‐security</artifactId>
</dependency>

Code example:

BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
// Encryption; return the encrypted string(password)
// Compare; return true or false// rawPassword password; encodedPassword encrypted characters(rawPassword,encodedPassword)

2. MD5 encryption

2.1 Brief description of MD5

MD5 (Message-Digest Algorithm 5) is a widely used hashing algorithm that converts inputs of any length into a 128-bit binary number

MD5 encryption features:

Irreversible

The same string content is encrypted and the same result is the same

MD5 applications:

MD5 is vulnerable to collision attacks and is not suitable for security authentication;

There is a collision that means: when using the MD5 algorithm to operate on two different contents, it is possible to obtain a pair of the same result values.

Can be used for integrity verification of messages or files

2.2 Code Example

Use the MessageDigest class built in Java

import ;
import ;
 
public class TestMD5 {
    public static String encryptMD5(String input) {
        try {
            // Create MD5 encrypted object            MessageDigest md = ("MD5");
            // Perform encryption            byte[] messageDigest = (());
            // Convert byte array to hexadecimal string            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = (0xff &amp; b);
                if (() == 1) {
                    ('0');
                }
                (hex);
            }
            // Return the encrypted string            return ();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
 
  	/**
      * test
      */
    public static void main(String[] args) {
        String str = "test1";
        String encrypted = encryptMD5(str);
        ("Encrypted string: " + encrypted);
    }
}

3. RSA encryption

3.1 RSA brief description

RSA encryption is asymmetric encryption. Decryption can be completed without directly passing the key; using a pair of public and private keys, the public key can be disclosed to the public and the private key is kept confidential

Encryption is to prevent information leakage and ensure secure communication

Signature is to prevent information from being tampered with, ensure the integrity of the message and the source authentication.

​Public key encryption, private key decryption, private key signature, public key verification;

In actual use, encryption and signature verification are used at the same time

RSA encryption process:

A and B have their own public and private keys; give the public keys to each other's system

1. When A wants to send a message to B, first use B's public key to encrypt the message, and then use A's private key to sign the encrypted string.

2. A passes the encrypted string and the signed string to B as parameters

3. B first uses A's public key to verify the signature, and then use B's private key to decrypt it.

4. After B is processed, the returned parameters are encrypted with the public key of A.

5. A uses A's private key to decrypt and return parameters

3.2 Code Example

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .PKCS8EncodedKeySpec;
import .X509EncodedKeySpec;
import ;
import .Base64;

public class TestRSA {

    /**
      * RSA maximum encrypted plaintext size
      */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
      * RSA maximum decrypted ciphertext size
      */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
      * Get the key pair
      *
      * @return key pair
      */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = ("RSA");
        (1024);
        return ();
    }

    /**
      * Get the private key
      *
      * @param privateKey private key string
      * @return
      */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = ("RSA");
        byte[] decodedKey = Base64.decodeBase64(());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return (keySpec);
    }

    /**
      * Get the public key
      *
      * @param publicKey public key string
      * @return
      */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = ("RSA");
        byte[] decodedKey = Base64.decodeBase64(());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return (keySpec);
    }
    
    /**
      * RSA encryption
      *
      * @param data to be encrypted
      * @param publicKey public key
      * @return
      */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = ("RSA");
        (Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = ().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // Encrypt data segmentation        while (inputLen - offset &gt; 0) {
            if (inputLen - offset &gt; MAX_ENCRYPT_BLOCK) {
                cache = ((), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = ((), offset, inputLen - offset);
            }
            (cache, 0, );
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = ();
        ();
        // Use base64 to obtain encrypted content and convert it into strings using UTF-8 as standard        // Encrypted string        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
      * RSA decryption
      *
      * @param data to be decrypted
      * @param privateKey private key
      * @return
      */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = ("RSA");
        (Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = ;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // Decrypt the data in segments        while (inputLen - offset &gt; 0) {
            if (inputLen - offset &gt; MAX_DECRYPT_BLOCK) {
                cache = (dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = (dataBytes, offset, inputLen - offset);
            }
            (cache, 0, );
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = ();
        ();
        // Decrypted content        return new String(decryptedData, "UTF-8");
    }

    /**
      * sign
      *
      * @param data to be signed
      * @param privateKey private key
      * @return Signature
      */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = ();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = ("RSA");
        PrivateKey key = (keySpec);
        Signature signature = ("MD5withRSA");
        (key);
        (());
        return new String(Base64.encodeBase64(()));
    }

    /**
      * Sign-in verification
      *
      * @param srcData Original string
      * @param publicKey public key
      * @param sign Signature
      * @return Whether the visa verification is passed
      */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = ();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = ("RSA");
        PublicKey key = (keySpec);
        Signature signature = ("MD5withRSA");
        (key);
        (());
        return (Base64.decodeBase64(()));
    }

    public static void main(String[] args) {
        try {
            // Generate key pair            KeyPair keyPair = getKeyPair();
            String privateKey = new String(Base64.encodeBase64(().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(().getEncoded()));
            ("Private Key:" + privateKey);
            ("Public Key:" + publicKey);
            // RSA encryption            String data = "Text content to be encrypted";
            String encryptData = encrypt(data, getPublicKey(publicKey));
            ("Encrypted content:" + encryptData);
            // RSA decryption            String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
            ("Decrypted content:" + decryptData);
            
            // RSA signature            String sign = sign(data, getPrivateKey(privateKey));
            // RSA visa verification            boolean result = verify(data, getPublicKey(publicKey), sign);
            ("Visit verification result:" + result);
        } catch (Exception e) {
            ();
            ("Encryption and decryption exception");
        }
    }
}

// This part of the code is reproduced from /p/

4. AES encryption

4.1 AES brief description

It belongs to symmetric encryption; in symmetric encryption algorithm, the encryption and decryption keys are the same, and the key is generated by negotiation between the receiver and the sender.

The AES standard supports three different key lengths: 128-bit, 192-bit and 256-bit

AES encryption is grouped with 16 bytes, and requires that the length of the plain text must be an integer multiple of 16 bytes. If it is not enough for multiples of 16 bytes, it needs to be filled in accordance with the padding mode.

Common fill modes include NoPadding, ZeroPadding, PKCS#7

Encryption mode: ECB, CBC

The most widely used CBC working mode

The encryption of each piece depends on the ciphertext of the previous piece, providing good confidentiality and resistance to replay attacks.

Random numbers are used as IV parameters. For the same plain text, the ciphertext generated is different each time.

4.2 Code Example

Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.26</version>
</dependency>

Implement code

@Test
public static void testAes(String data) {
    // The key must be 16, 24 or 32 in length    byte[] key = "1234567898765432".getBytes();
    // Initialize the vector, the CBC mode length must be 16    byte[] iv = "1234567898765432".getBytes();

    // Create an AES object, specify the key and initialize vector    SymmetricCrypto aes = new AES(, Padding.PKCS5Padding, key, iv);

    // Encrypt and base transcoding    String encrypt = aes.encryptBase64(data);
    (encrypt);
    
    // Decrypt as a string    String decrypt = (encrypt);
    (decrypt);
}

5. Commercial password algorithm

5.1 Algorithm classification

A series of commercial cryptographic algorithms such as SM1, SM2, SM3, SM4, SM9, and ZUC constitute the complete cryptographic algorithm system in my country.
SM1 Symmetry E-government, hardware and other encryption
SM2 Asymmetric Digital signature, key exchange
SM3 digest algorithm digital signature, integrity verification
SM4 Symmetry E-government, Wireless LAN encryption
SM9 asymmetric data encryption, identity authentication

5.2 SM4 encryption algorithm

5.2.1 Brief description of SM4

The characteristics of the SM4 algorithm are:

(1) It belongs to a symmetric cryptographic algorithm, and the encryption and decryption keys are the same;

(2) Both the ciphertext and the key are 128 bits, and the packet length is 128 bits;

(3) The number of rounds of the SM4 cipher algorithm encryption and decryption algorithm is 32 rounds, and the wheel structure of each round is the same, but the wheel key is used in the opposite direction.

The domestic general standard in the financial industry is SM4, corresponding to the international standard SM4

There are two modes of ECB and CBC

The difference is that the former only needs a key, while the latter only needs a key but also an iv value.

The CBC mode of SM4 is similar to that of AES; the security is basically the same as that of AES-128, but the implementation is simpler and more efficient.

SM4's CBC mode improves security by introducing chain dependencies. It encrypts each plaintext block with the previous ciphertext block. In this approach, each ciphertext block depends on all the plaintext blocks before it. At the same time, in order to ensure the uniqueness of each message, the initialization vector IV is required in the first block

5.2.2 Code Example

Use tool classes to implement CBC mode

Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.26</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>

Code implementation

public class TestSm4 {
 	/**
      * The key length must be 16
      */
    private static String SECRET_KEY = "";
    /**
      * IV is the initial vector, and its function is to make the ciphertext obtained by encrypting the same plaintext differently.  The length must be 16
      */
    private static String IV= "";
 
 	/**
      * Encrypted into base64/byte array
      */
    public static String encrypt(String plainTxt){
        String cipherTxt = "";
        SymmetricCrypto sm4Cbc = new SM4(, Padding.PKCS5Padding, SECRET_KEY.getBytes(CharsetUtil.CHARSET_UTF_8), (CharsetUtil.CHARSET_UTF_8));
        byte[] encrypHex = (plainTxt);
        cipherTxt = (encrypHex);
        return cipherTxt;
    }
 
 	/**
      * Decryption
      */
    public static String decrypt(String cipherTxt){
    	String plainTxt = "";
        try {
	        SymmetricCrypto sm4 = new SM4(, Padding.PKCS5Padding, SECRET_KEY.getBytes(CharsetUtil.CHARSET_UTF_8), (CharsetUtil.CHARSET_UTF_8));
	        byte[] cipherHex = (cipherTxt);
	        plainTxt = (cipherHex, CharsetUtil.CHARSET_UTF_8);
        } catch(Exception e) {
        	(());
        }
        return plainTxt;
    }
 
 	/**
      * test
      */
    public static void main(String[] argc){
        String originTxt = "Encryption testing";
        String cipherTxt = encrypt(originTxt);
        ("Encrypted ciphertext: " + cipherTxt);
        String plainTxt = decrypt(cipherTxt);
        ("Decrypted result: " + plainTxt);
    }
}

Implementation using SmUtil

 public void testSm4(String text) {
    SymmetricCrypto sm4 = SmUtil.sm4();
	
	// Encrypted ciphertext    String encryptHex = (text);
    // Decryption result    String decryptStr = (encryptHex, CharsetUtil.CHARSET_UTF_8);
}

5.2 SM2 signature algorithm

5.2.1 Brief description of SM2

The SM2 algorithm is an asymmetric encryption algorithm, which is mainly used for digital signature, key exchange and data encryption. When using the SM2 algorithm, a private key and a public key need to be generated. Private keys are used for signature and decryption, and public keys are used for verification of signature and encryption. It is a more advanced and safe algorithm

5.2.2 Code implementation

Introducing dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.26</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>

accomplish:

// Encryptionpublic static String encrypt(String data, String publicKey,String privateKey) {
    SM2 sm2 = SmUtil.sm2(publicKey,privateKey);
    return ((data, ));
}

// Decryptpublic static String decrypt(String data, String publicKey,String privateKey) {
    SM2 sm2 = SmUtil.sm2(publicKey,privateKey);
    return (data, );
}

public static void main(String[] args) {
    String data = "text";
    // Public key; the length of the public key is 64 bytes (512 bits)    String publicKey = "";
    // Private key; the length of the private key is 32 bytes (256 bits)    String privateKey = "";

    // Encryption    String encryptedData = encrypt(data, publicKey,privateKey);
    // Decrypt    String decryptedData = decrypt(encryptedData,publicKey, privateKey);
}

5.3 SM3 digest algorithm

5.3.1 Brief description of SM3

The SM3 algorithm is a message digest algorithm issued by the China State Crypto Administration, which is used to generate the hash value of the message.

The SM3 algorithm adopts the Merkle-Damgård structure, with the message packet length of 512 bits and the digest value length is 256 bits (i.e. 32 bytes). Its input can be data of any length, but the encryption result is always 256-bit data.

Application scenarios:

Digital signature: Use the hash value generated by the SM3 algorithm as part of the signature to ensure the authenticity and integrity of the signature.

Message integrity verification: Verify whether the message has been tampered with during transmission by comparing the hash value of the message.

Process brief description:

‌1. Message filling:

Fill the input message to a multiple of 512 bits in length.

2. Message grouping:

Group the filled messages by 512 bits (64 bytes)

3. Message extension:

Each 512-bit packet is expanded, each packet is called a message block, and each message block is expanded to form an extended message of 132 words (each word is 32 bits)

4. Iterative compression:

132 message words are calculated through 64 rounds of iterative compression, and finally a 256-bit hash value is obtained.

In each iteration, 8 32-bit registers (A, B, C, D, E, F, G, H) are used, which are initialized to fixed constant values ​​at the beginning of the iteration.

The values ​​of these registers are updated through a series of operations.

After completing 64 rounds of iterations, the values ​​of 8 registers are XORed to obtain the final 256-bit hash value.

5.3.2 Code implementation

public static void main(String[] args) {
    String input = "Hello";
    String output = sm3Encrypt(input);
    ("SM3 Result: " + output);
}

public static String sm3Encrypt(String input) {
    try {
        MessageDigest md = ("SM3");
        byte[] digest = (());
        return bytesToHex(digest);
    } catch (Exception e) {
        ();
        return null;
    }
}

// Convert to hexadecimal stringpublic static String bytesToHex(byte[] bytes) {
    StringBuilder result = new StringBuilder();
    for (byte b : bytes) {
        (("%02x", b));
    }
    return ();
}

5.4 HMAC-SM3

5.4.1 Brief description of HMAC-SM3

HMAC-SM3 is a hash algorithm authentication technology based on SM3. It uses SM3 algorithm to generate hash values ​​and introduces keys to enhance security.

Application scenarios:

Message Authentication: Verify the authenticity and integrity of the message by comparing the message authentication codes generated by the sender and the receiver.

Data integrity protection: During data transmission and storage, the HMAC-SM3 algorithm is used to ensure that the data is not tampered with.

5.4.2 Code implementation

Introduce dependencies

&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;bcprov-jdk15on&lt;/artifactId&gt;
    &lt;version&gt;1.69&lt;/version&gt; &lt;!-- Use the latest version --&gt;
&lt;/dependency&gt;

Code implementation

public static String hmacSM3(byte[] key, byte[] data) {
    // Create an SM3Digest object for SM3 hashing    SM3Digest sm3Digest = new SM3Digest();
    // Create an HMac object, using SM3Digest as the underlying hashing algorithm    HMac hmac = new HMac(sm3Digest);
    // Initialize the HMac object with a key    (new KeyParameter(key));
    // Update the data of HMac objects    (data, 0, );
    // Calculate the HMAC-SM3 value and store the result in the result array    byte[] result = new byte[()];
    // Perform the final hash operation and fill the result into the result array    (result, 0);
    return bytesToHex(result);
}

public static void main(String[] args) {
    // Sample key    byte[] key = "123456789".getBytes();
    byte[] data = "Hello".getBytes();
    // Calculate the HMAC-SM3 value    String hmac = hmacSM3(key, data);
    ("HMAC-SM3: " + hmac);
}

// Convert to hexadecimal stringpublic static String bytesToHex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        // Convert each byte to a hexadecimal string and splice it into a StringBuilder        (("%02x", b));
    }
    return ();
}

Summarize

This is the end of this article about the five common encryption algorithm usage methods of Java. For more related content on Java encryption algorithms, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!