Java密码加密解密设置固定秘钥

在日常开发中,我们经常需要对敏感信息如密码进行加密存储,以保护用户的隐私安全。为了确保加密的安全性,我们需要使用一个固定的秘钥进行加密和解密操作。本文将介绍如何使用Java语言进行密码加密解密,并设置固定的秘钥。

密码加密解密算法

常见的密码加密解密算法有很多种,如DES、AES等。在本文中,我们将使用AES算法作为示例。AES是一种对称加密算法,通过相同的秘钥进行加密和解密操作。

AES加密解密示例代码

下面是使用Java语言实现AES加密解密的示例代码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AESUtils {

    private static final String AES_ALGORITHM = "AES";
    private static final String SECRET_KEY = "ThisIsASecretKey";

    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        try {
            String plainText = "Hello World!";
            String encryptedText = encrypt(plainText);
            String decryptedText = decrypt(encryptedText);
            
            System.out.println("Plain Text: " + plainText);
            System.out.println("Encrypted Text: " + encryptedText);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上述代码中,我们定义了一个AESUtils类,其中包含了encryptdecrypt两个静态方法用于加密和解密操作。我们使用了一个固定的秘钥ThisIsASecretKey进行加密解密操作,你可以根据实际需求设置不同的秘钥。

类图

下面是AESUtils类的类图:

classDiagram
    AESUtils -- Cipher
    Cipher -- SecretKeySpec
    AESUtils -- StandardCharsets
    AESUtils -- Base64

关系图

下面是AESUtils类的关系图:

erDiagram
    AESUtils }--|> Cipher
    Cipher }--|> SecretKeySpec
    AESUtils }--|> StandardCharsets
    AESUtils }--|> Base64

总结

通过使用AES算法和固定的秘钥,我们可以实现对敏感信息的安全加密和解密。在实际应用中,我们应该注意保护好秘钥的安全性,并避免将秘钥硬编码在代码中。希望本文能帮助到你理解和应用密码加密解密的相关知识!