Home  >  Article  >  Java  >  Java-based data encryption method and implementation

Java-based data encryption method and implementation

WBOY
WBOYOriginal
2023-06-18 21:22:131572browse

With the development of information technology, people pay more and more attention to the security of data encryption. Data encryption is an important means to ensure data security. During the data encryption process, applications need to use an encryption algorithm to ensure that sensitive data is not illegally stolen, tampered with, or leaked during transmission and storage. This article will introduce a Java-based data encryption method and implementation to provide guarantee for data security.

What is an encryption algorithm?

Encryption algorithm is a process of calculating ciphertext from data using a specific method. Ciphertext is an incomprehensible form of data that can only be converted back into the original data using a decryption algorithm using a specific key. Encryption algorithm is a process of converting plain text into cipher text. Cipher text can only be converted into plain text with a specific key.

Java's encryption tool class

Java provides many standard encryption and hashing algorithms, such as AES, DES, MD5, SHA, HMAC, etc. These algorithms are accessible in Java through the Java.security package. Many encryption tool classes are provided in Java, such as Cipher, MessageDigest and Mac classes. Below we will introduce how to use these tool classes.

  1. Cipher class

Cipher is a class used for encryption and decryption in Java. Both encryption and decryption require the use of the same Cipher object. If the Cipher object is initialized in encryption mode, then it can only be used for encryption; similarly, if the Cipher object is initialized in decryption mode, then it can only be used for decryption.

// 加密示例
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class DESUtil {
    private static final String DEFAULT_ENCODING = "utf-8";
    private static final String ALGORITHM = "DES";

    public static byte[] encrypt(String data, String key) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(DEFAULT_ENCODING));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return cipher.doFinal(data.getBytes(DEFAULT_ENCODING));
    }

    public static String decrypt(byte[] data, String key) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(DEFAULT_ENCODING));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        return new String(cipher.doFinal(data), DEFAULT_ENCODING);
    }
}
  1. MessageDigest class

MessageDigest is a class in Java used to calculate hash values. It supports multiple hashing algorithms such as MD5, SHA-1, SHA-256, etc. The basic steps for calculating hash values ​​using the MessageDigest class are as follows:

import java.security.MessageDigest;

public class DigestUtil {
    private static final String DEFAULT_ENCODING = "utf-8";

    public static String md5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data.getBytes(DEFAULT_ENCODING));
        byte[] digest = md.digest();

        return HexUtil.toHexString(digest);
    }

    public static String sha1(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(data.getBytes(DEFAULT_ENCODING));
        byte[] digest = md.digest();

        return HexUtil.toHexString(digest);
    }

    public static String sha256(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data.getBytes(DEFAULT_ENCODING));
        byte[] digest = md.digest();

        return HexUtil.toHexString(digest);
    }
}
  1. Mac class

The Mac class is a class used to calculate message verification codes. It supports HmacMD5, HmacSHA1 and other algorithms. The basic steps of using the Mac class to calculate the message verification code are as follows:

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class HmacUtil {
    private static final String DEFAULT_ENCODING = "utf-8";
    private static final String ALGORITHM = "HmacSHA256";

    public static String hmac(String data, String key) throws Exception {
        byte[] keyBytes = key.getBytes(DEFAULT_ENCODING);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(secretKeySpec);

        byte[] dataBytes = data.getBytes(DEFAULT_ENCODING);
        byte[] digest = mac.doFinal(dataBytes);

        return HexUtil.toHexString(digest);
    }
}

Data encryption process

The data encryption process can be divided into three basic steps: key generation, encryption and decryption. Below we will introduce the detailed process of these three steps.

  1. Key generation

Key generation is the first step in data encryption. We can generate supported key types using the KeyGenerator class provided by Java. For example, the sample code we can generate an AES encryption key is as follows:

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;

public class KeyUtil {
    private static final String ALGORITHM = "AES";

    public static SecretKey generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = new SecureRandom();
        keyGenerator.init(256, secureRandom); // 256是AES密钥长度

        return keyGenerator.generateKey();
    }
}
  1. Encryption

Encryption is the second step of data encryption. We can use Cipher class for data encryption. Before encryption, we need to obtain the encryption key and determine the encryption algorithm and encryption mode.

public class AESEncryptUtil {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String DEFAULT_ENCODING = "utf-8";

    public static byte[] encrypt(String data, SecretKey key) throws Exception {
        IvParameterSpec iv = generateIV();

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        byte[] encryptedData = cipher.doFinal(data.getBytes(DEFAULT_ENCODING));

        return encryptedData;
    }

    private static IvParameterSpec generateIV() {
        byte[] ivBytes = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivBytes);
        return new IvParameterSpec(ivBytes);
    }
}
  1. Decryption

Decryption is the third step in data encryption. We can use Cipher class for data decryption. Before decryption, we need to obtain the decryption key and determine the encryption algorithm and encryption mode.

public class AESDecryptUtil {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String DEFAULT_ENCODING = "utf-8";

    public static String decrypt(byte[] encryptedData, SecretKey key, IvParameterSpec iv) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);

        byte[] decryptedData = cipher.doFinal(encryptedData);

        return new String(decryptedData, DEFAULT_ENCODING);
    }
}

Summary

This article mainly introduces the Java-based data encryption method and implementation. First, it introduces the concept of encryption algorithms and some encryption and hash algorithms provided in Java, and then explains the use of encryption tool classes provided in Java, including Cipher, MessageDigest and Mac classes. Finally, we introduce the data encryption process, including three steps: key generation, encryption, and decryption. Through the introduction of this article, readers can have an in-depth understanding of the principles and implementation methods of data encryption, which provides a foundation for ensuring data security.

The above is the detailed content of Java-based data encryption method and implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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