在Java中,可以使用多種方法對字符進行加密。這里,我將向您展示如何使用Java內置的Cipher
類進行加密和解密操作。我們將使用AES(Advanced Encryption Standard)算法作為示例。
首先,確保導入以下所需的庫:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
接下來,我們將創建一個名為encryptText
的方法來加密文本:
public static String encryptText(String text, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
現在,我們將創建一個名為decryptText
的方法來解密文本:
public static String decryptText(String encryptedText, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
接下來,我們需要生成一個SecretKey
對象。我們將在main
方法中執行此操作:
public static void main(String[] args) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // 設置密鑰長度,可以是128、192或256位
SecretKey secretKey = keyGenerator.generateKey();
String originalText = "Hello, World!";
String encryptedText = encryptText(originalText, secretKey);
String decryptedText = decryptText(encryptedText, secretKey);
System.out.println("Original Text: " + originalText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
這個示例將使用AES加密算法對文本進行加密和解密。請注意,為了安全起見,您應該使用一個安全的密鑰生成方法,而不是在代碼中硬編碼密鑰。此外,您可以根據需要調整密鑰長度。