[JAVA] 대칭키(AES-128) 암복호화
package main.java.hello;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* 오픈 라이브러리 */
import org.apache.commons.codec.binary.Hex;
public class AESUtil {
/* KEY SIZE Constant */
private static final int KEY_SIZE_128 = 128;
private static final int KEY_SIZE_256 = 256;
/* DES */
private static final String ALGO_DES = "DES";
private static final String ALGO_AES = "AES";
private static final String ALGO_SEED = "SEED";
/* AES */
/* SEED */
private static String plainText = "This is Cipher test";
private static KeyGenerator kgen = null;
static SecretKey skey = null;
static String sKeyHex = null;
private static void keyGenerator(String cipher, int keySize) {
try {
if(cipher.equals(ALGO_AES)) {
kgen = KeyGenerator.getInstance(cipher);
} else {
return ;
}
kgen.init(keySize);
skey = kgen.generateKey();
// 비밀 키를 이렇게 저장하여 사용하면 암호화/복호화가 편해진다.
sKeyHex = Hex.encodeHexString(skey.getEncoded());
System.out.println("Key as Hex : " + sKeyHex); // 128bit = 16bytes
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static byte[] encrypt(String plainText) {
SecretKeySpec skeySpec = new SecretKeySpec(skey.getEncoded(), kgen.getAlgorithm());
try {
Cipher cipher = Cipher.getInstance(kgen.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return encrypted;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] encryptedStr) {
/* Key Spec 생성 */
SecretKeySpec skeySpec = new SecretKeySpec(skey.getEncoded(), kgen.getAlgorithm());
try {
/* Cipher object */
Cipher cipher = Cipher.getInstance(kgen.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encryptedStr);
return original;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
try {
// 1.AES-128 비트 대칭키 생
keyGenerator(ALGO_AES, KEY_SIZE_128);
// 2. 암호화 수행
byte[] encrptedByte = encrypt(plainText);
System.out.println("encrypted string: " + Hex.encodeHexString(encrptedByte));
// 3. 복호화 수행
byte[] decrptedByte = decrypt(encrptedByte);
System.out.println("decrypted string: " + new String(decrptedByte) );
} catch (Exception e) {
e.printStackTrace();
}
}
}