在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編碼。你可以根據需要選擇其他加密算法。同時,確保在實際應用中使用安全的密鑰管理和存儲方法。