Java에서 데이터 암호화 및 암호 해독을 구현하려면 구체적인 코드 예제가 필요합니다.
요약:
데이터 암호화 및 암호 해독은 정보 보안 분야에서 중요한 역할을 합니다. 이 기사에서는 Java 프로그래밍 언어를 사용하여 데이터 암호화 및 암호 해독을 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 여기에는 대칭 암호화 알고리즘과 비대칭 암호화 알고리즘의 사용이 포함됩니다.
1. 대칭 암호화 알고리즘
대칭 암호화 알고리즘은 동일한 키를 사용하여 데이터를 암호화하고 복호화합니다. Java에서 일반적으로 사용되는 대칭 암호화 알고리즘에는 DES, 3DES 및 AES가 있습니다. 다음은 데이터 암호화 및 암호 해독을 위해 AES 알고리즘을 사용하는 샘플 코드입니다.
public class SymmetricEncryption {
private static final String ALGORITHM = "AES";
SecretKey secretKey = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(new DESKeySpec(key)); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return cipher.doFinal(plaintext);
SecretKey secretKey = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(new DESKeySpec(key)); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); return cipher.doFinal(ciphertext);
}
public class Main {
public static void main(String[] args) throws Exception {
byte[] key = "secretkey".getBytes(); // 密钥 byte[] plaintext = "Hello, world!".getBytes(); // 明文 byte[] ciphertext = SymmetricEncryption.encrypt(plaintext, key); // 加密 System.out.println("Ciphertext: " + new String(ciphertext)); byte[] decryptedText = SymmetricEncryption.decrypt(ciphertext, key); // 解密 System.out.println("Decrypted Text: " + new String(decryptedText));
}
비대칭 암호화 알고리즘은 서로 다른 키를 사용하여 데이터를 암호화하고 해독합니다. Java에서 일반적으로 사용되는 비대칭 암호화 알고리즘에는 RSA가 포함됩니다. 다음은 데이터 암호화 및 암호 해독을 위해 RSA 알고리즘을 사용하는 샘플 코드입니다.
private static final String ALGORITHM = "RSA";
public static byte[] encrypt( byte [] plaintext, PublicKey publicKey) 예외 발생 {
Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(plaintext);
}
public static byte[] decrypt(byte[] ciphertext, PrivateKey privateKey) 예외 발생 {
Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(ciphertext);
}
} public static void main(String[] args) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); byte[] plaintext = "Hello, world!".getBytes(); // 明文 byte[] ciphertext = AsymmetricEncryption.encrypt(plaintext, publicKey); // 加密 System.out.println("Ciphertext: " + new String(ciphertext)); byte[] decryptedText = AsymmetricEncryption.decrypt(ciphertext, privateKey); // 解密 System.out.println("Decrypted Text: " + new String(decryptedText));
위 내용은 Java에서 데이터 암호화 및 암호 해독을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!