Javaでテキストを暗号化する方法は何ですか?
Javaを使用してテキストを暗号化するには、Javaの暗号化標準ライブラリ内の暗号化クラスを使用することができます。以下は、AESアルゴリズムを使用してテキストを暗号化する例です:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class TextEncryptionExample {
public static void main(String[] args) {
try {
// 生成AES密钥
SecretKey secretKey = generateAESKey();
// 明文
String plaintext = "Hello, World!";
// 加密
String ciphertext = encrypt(plaintext, secretKey);
System.out.println("密文: " + ciphertext);
// 解密
String decryptedText = decrypt(ciphertext, secretKey);
System.out.println("解密后的明文: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
// 生成AES密钥
public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
}
// 加密
public static String encrypt(String plaintext, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密
public static String decrypt(String ciphertext, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
この例では、AESアルゴリズムを使用してテキストを暗号化および復号化しています。最初に、generateAESKey()メソッドを使用してAES鍵を生成します。次に、encrypt()メソッドを使用して平文を暗号化し、暗号化された暗号文をBase64エンコード形式で返します。最後に、decrypt()メソッドを使用して暗号文を復号化し、元の平文を取得します。
この例はデモ用に作成されたものであり、セキュリティに関する問題は考慮されていません。実際の運用では、要件に応じて適切な暗号化アルゴリズムと鍵長を選択し、適切なセキュリティ対策を取る必要があります。