将secretKey和IV存储在一个文件中,以便使用Java进行加密和解密,可以通过以下步骤实现:
以下是一个示例代码,演示如何读取存储在文件中的secretKey和IV,并使用Java进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class EncryptionExample {
public static void main(String[] args) {
String secretKey = "";
String iv = "";
try {
// 读取存储secretKey和IV的文件
BufferedReader reader = new BufferedReader(new FileReader("keys.txt"));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split("=");
if (parts.length == 2) {
if (parts[0].trim().equals("secretKey")) {
secretKey = parts[1].trim();
} else if (parts[0].trim().equals("IV")) {
iv = parts[1].trim();
}
}
}
reader.close();
// 加密
String plaintext = "Hello, World!";
String ciphertext = encrypt(plaintext, secretKey, iv);
System.out.println("Encrypted: " + ciphertext);
// 解密
String decryptedText = decrypt(ciphertext, secretKey, iv);
System.out.println("Decrypted: " + decryptedText);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String encrypt(String plaintext, String secretKey, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String ciphertext, String secretKey, String iv) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
请注意,上述示例代码仅用于演示如何将secretKey和IV存储在一个文件中,并使用Java进行加密和解密。在实际应用中,为了保证密钥的安全性,建议采用更加安全的方式来存储和管理密钥,例如使用密钥管理服务(KMS)等。
领取专属 10元无门槛券
手把手带您无忧上云