温馨提示×

如何在Java中加密和解密Properties文件

小樊
97
2024-08-20 14:06:30
栏目: 编程语言

在Java中加密和解密Properties文件可以通过使用Java的加密库实现。以下是一个示例代码,演示如何使用AES加密算法加密和解密Properties文件:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesEncryption {

    private static final String SECRET_KEY = "ThisIsASecretKey";

    public static void encryptPropertiesFile(String inputFilePath, String outputFilePath) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream(inputFilePath));

        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        FileOutputStream outputStream = new FileOutputStream(outputFilePath);
        properties.storeToXML(outputStream, "Encrypted Properties");
        outputStream.close();
    }

    public static void decryptPropertiesFile(String inputFilePath, String outputFilePath) throws Exception {
        Properties properties = new Properties();
        FileInputStream inputStream = new FileInputStream(inputFilePath);
        properties.loadFromXML(inputStream);
        inputStream.close();

        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        FileOutputStream outputStream = new FileOutputStream(outputFilePath);
        properties.store(outputStream, "Decrypted Properties");
        outputStream.close();
    }

    public static void main(String[] args) {
        try {
            encryptPropertiesFile("input.properties", "encrypted.properties");
            decryptPropertiesFile("encrypted.properties", "decrypted.properties");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我们使用AES加密算法来加密和解密Properties文件。您可以将SECRET_KEY更改为自己的密钥。您可以使用properties.storeToXML()方法将Properties对象保存到XML文件中,以便在加密和解密时保留属性的结构。您可以根据需要更改加密和解密的文件路径和名称。

0