在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文件中,以便在加密和解密時保留屬性的結構。您可以根據需要更改加密和解密的文件路徑和名稱。