· 6 years ago · Jun 29, 2019, 06:34 PM
1# 테스트 용도로 하나의 파일에 모두 작성하였습니다.
2import org.apache.commons.codec.binary.Base64;
3import javax.crypto.BadPaddingException;
4import javax.crypto.Cipher;
5import javax.crypto.IllegalBlockSizeException;
6import javax.crypto.NoSuchPaddingException;
7import javax.crypto.spec.IvParameterSpec;
8import javax.crypto.spec.SecretKeySpec;
9import java.nio.charset.StandardCharsets;
10import java.security.InvalidAlgorithmParameterException;
11import java.security.InvalidKeyException;
12import java.security.NoSuchAlgorithmException;
13import java.security.spec.AlgorithmParameterSpec;
14
15/**
16 * 암호화 클래스
17 */
18class AES256Util {
19// public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
20 public static byte[] ivBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
21// public static byte[] ivBytes = { 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4 };
22
23 public static String aes_encode(String str, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
24 byte[] textBytes = str.getBytes(StandardCharsets.UTF_8);
25 AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
26 SecretKeySpec newKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
27 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
28 cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
29 return Base64.encodeBase64String(cipher.doFinal(textBytes));
30 }
31
32 public static String aes_decode(String str, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
33 byte[] textBytes = Base64.decodeBase64(str);
34 //byte[] textBytes = str.getBytes("UTF-8");
35 AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
36 SecretKeySpec newKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
37 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
38 cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
39 return new String(cipher.doFinal(textBytes), StandardCharsets.UTF_8);
40 }
41}
42/**
43 * 암호화 테스트 코드
44 */
45public class TestClass {
46 public static final String plain_text = "안녕하세요 HelloWorld";
47 public static final String secret_key = "fakecodingsecretfakecodingsecret";
48
49 public static void main(String[] args) {
50 try {
51 String encrypt_text = AES256Util.aes_encode(plain_text, secret_key);
52 String decrypt_text = AES256Util.aes_decode(encrypt_text, secret_key);
53 System.out.println(encrypt_text);
54 System.out.println(decrypt_text);
55 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
56 e.printStackTrace();
57 }
58 }
59}