import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESManager {
// 16바이트(128비트) 키와 IV 설정 (실제 사용 시 외부에서 관리 권장)
private static final String KEY = "1234567890123456";
private static final String IV = "abcdefghijklmnop";
private static final String ALGO = "AES/CBC/PKCS5Padding";
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("사용법:");
System.out.println(" 암호화: java AESManager enc \"평문\"");
System.out.println(" 복호화: java AESManager dec \"암호문(Base64)\"");
return;
}
String mode = args[0]; // enc 또는 dec
String input = args[1]; // 대상 문자열
try {
if ("enc".equalsIgnoreCase(mode)) {
String encrypted = encrypt(input);
System.out.println("암호화 결과 (Base64): " + encrypted);
} else if ("dec".equalsIgnoreCase(mode)) {
String decrypted = decrypt(input);
System.out.println("복호화 결과: " + decrypted);
} else {
System.out.println("알 수 없는 모드입니다. 'enc' 또는 'dec'를 사용하세요.");
}
} catch (Exception e) {
System.err.println("오류 발생: " + e.getMessage());
}
}
// --- 암호화 메소드 ---
public static String encrypt(String plainText) throws Exception {
Cipher cipher = Cipher.getInstance(ALGO);
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// --- 복호화 메소드 ---
public static String decrypt(String cipherText) throws Exception {
Cipher cipher = Cipher.getInstance(ALGO);
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}