在Java中加密secret数据,你可以使用Java Cryptography Extension (JCE)提供的加密算法。以下是一个使用AES算法的简单示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public static SecretKey generateAESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // 设置密钥长度,可以是128, 192或256位
return keyGenerator.generateKey();
}
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
public static void main(String[] args) {
try {
SecretKey secretKey = generateAESKey();
String originalData = "This is a secret message";
String encryptedData = encrypt(originalData, secretKey);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = decrypt(encryptedData, secretKey);
System.out.println("Decrypted data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
注意:这个示例使用了AES算法和Base64编码。你可以根据需要选择其他加密算法。同时,确保在实际应用中使用安全的密钥管理和存储方法。