카테고리 없음
ASE 암호화, 복호화
OJR
2023. 3. 27. 22:01
sample code :
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESEncryptionExample {
private static final String ALGORITHM = "AES";
private static final String KEY = "my-secure-key-123";
public static String encrypt(String input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String input) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = Base64.getDecoder().decode(input);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String plainText = "This is a secret message!";
String encryptedText = encrypt(plainText);
String decryptedText = decrypt(encryptedText);
System.out.println("Plain Text: " + plainText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
}
output :
Plain Text: This is a secret message!
Encrypted Text: S/VzTbT3NDq3Zm7xnZoAYA==
Decrypted Text: This is a secret message!