IT/Security2017. 2. 9. 19:10

 


이 글에서는 자바 암호 프로그래밍을 위하여 Eclipse와 JDK를 설치하고 SUN JCE를 이용해서 AES 암호화 하는 방법에 대해서 알아보겠습니다.


 

 

안녕하세요. IT반장입니다.

이번 글에서는 '자바 암호 프로그래밍'을 하기 위한 가장 기초적인 단계인 '개발 도구 설치'에 대해서 알아보겠습니다. 자바 프로그래밍에서 가장 많이 쓰이는 Eclipse(Java IDE)와 JDK(Java Development Kit) 설치 방법에 대해서 설명하고, SUN JCE 라이브러리로 AES 암복호화 하는 방법에 대해서 알아보겠습니다.


 

 

1. Eclipse 다운로드 및 설치


■ Eclipse 다운로드

http://www.eclipse.org/downloads [1]에서 최신 버전의 Eclipse를 다운로드 받습니다. ('제 PC는 windows7 64비트 환경이어서 자동으로 64비트 다운로드 버튼이 보이네요.')



 

■ Eclipse 설치

1) 다운로드 받은 설치파일을 실행하고, 설치 화면에서 'Eclipse IDE for Java Developers"를 선택


 

2) 설치할 디렉토리 지정 (여기서는 "c:\eclipse"로 지정)


 

3) 라이선스 동의


 

4) 설치 완료 후 실행('LAUNCH')


 

5) 작업디렉토리(workspace) 지정(여기서는 "C:\eclipse\workspace")


 

6) 설치 완료 !

※ eclipse가 실행이 안 되시는 분은 Java(JRE)가 시스템에 설치가 안되어 있을 수 있습니다. http://www.java.com 에서 JRE를 설치하시고 실행하시면 됩니다.

 

 

2. JDK 다운로드 및 설치

- eclipse가 동작한다면 해당 PC 또는 개발 시스템에 JDK 또는 JRE가 이미 설치되어 있을 겁니다. 여기서는 개발 환경의 독립성, 호환성을 위해서 별도의 JDK/JRE를 설치합니다.

 

■ JDK 다운로드 [2]

http://www.oracle.com/technetwork/java/javase/downloads/index.html 에서 JDK를 다운로드 받습니다.


 

- 라이선스에 동의하고 시스템에 맞는 버전을 다운로드 합니다. (여기서는 8u102 JDK와 Demo/Sample을 다운로드 합니다.)



■ JDK 설치

- 다운로드 한 JDK실행파일을 실행합니다.


 

- JDK 설치 디렉토리를 "C:\eclipse\jdk1.8.0_102"로 지정합니다. (개발 환경의 독립성을 위해 별도의 디렉토리에 설치합니다.)


 

- JRE 설치 디렉토리를 "C:\eclipse\jre1.8.0_102"로 지정합니다. (개발 환경의 독립성을 위해 별도의 디렉토리에 설치합니다.)


 

- 설치가 완료되면 'Next Steps' 버튼을 눌러 'java document'를 확인합니다.


 


※ Java에서 제공하는 많은 기능 중에, 암호 프로그래밍을 위해 우선 일부(java, security tool 등)만 사용하게 될 것입니다.

 

 

3. 개발 환경 설정하기

- eclipse와 jdk/jre 가 설치 완료되었으니, 설치한 개발 도구들을 독립적인 환경으로 설정해 보겠습니다.

※ 여기서 '독립적 환경'이란 '컴파일 환경'(jdk)과 '실행 환경'(jre)을 동일하게 하여 개발시스템에 의존적이지 않도록 하는 것을 말합니다. 즉, 개발 환경만을 위해 jdk와 jre를 별도로 설치해서 환경을 구성하는 겁니다.

 

■ eclipse 환경 설정하기

- eclipse 실행 후 Window->Preference 선택


 

- Java->Compiler->Installed JREs 선택


 

- Add->'Standard VM'->Next 선택


 

- Directory->"C:\eclipse\jdk1.8.0_102" 선택 ->Finish


 

- 새로 설치한 "jdk1.8.0_102" 체크박스 선택 -> OK(또는 Apply) 선택


※ 이제 새로 설치한 JDK가 'eclipse 기본 Java 환경'으로 됩니다.

 

 

4. '자바 암호 프로그래밍' 시작하기


■ Eclipse 프로젝트 시작하기

- File -> New -> Java Project 선택


 

- Project name : "EncryptionTest01"로 입력하고

- JRE -> 'Use a project specific JRE' 선택 -> 'jdk1.8.0_102' 선택 -> Finish 선택


 

- 'JRE System Library'에서 라이브러리들이 "C:\eclipse\jdk1.8.0_102\..."에 위치한 것인지 확인

 

 

■ AES 암호화 및 복호화 프로그래밍

※ 여기서는 OWASP [3]에서 제공하는 SUN JCE(Java Cryptography Extension) 예제로 설명하겠습니다. [4]

- src 우클릭 -> New -> Class 선택


 

- Name: "AES" 입력 -> Finish



- 소스 복사 : OWASP AES 예제 소스[4]를 복사하여 붙여 넣기

※ 첫 번째 줄 빼고, 복사한다. ("package org.owasp.java.crypto;")


 

※ 참고 소스(AES암호화)[4]

  1. import java.security.InvalidAlgorithmParameterException;  
  2. import java.security.InvalidKeyException;  
  3. import java.security.NoSuchAlgorithmException;  
  4. import java.security.SecureRandom;  
  5.     
  6. import javax.crypto.BadPaddingException;  
  7. import javax.crypto.Cipher;  
  8. import javax.crypto.IllegalBlockSizeException;  
  9. import javax.crypto.KeyGenerator;  
  10. import javax.crypto.NoSuchPaddingException;  
  11. import javax.crypto.SecretKey;  
  12. import javax.crypto.spec.IvParameterSpec;  
  13.     
  14. import sun.misc.BASE64Encoder;  
  15.     
  16. /** 
  17.  * @author Joe Prasanna Kumar 
  18.  * This program provides the following cryptographic functionalities 
  19.  * 1. Encryption using AES 
  20.  * 2. Decryption using AES 
  21.  *  
  22.  * High Level Algorithm : 
  23.  * 1. Generate a AES key (specify the Key size during this phase)  
  24.  * 2. Create the Cipher  
  25.  * 3. To Encrypt : Initialize the Cipher for Encryption 
  26.  * 4. To Decrypt : Initialize the Cipher for Decryption 
  27.  *  
  28.  *  
  29.  */  
  30.     
  31. public class AES {  
  32.     public static void main(String[] args) {  
  33.             
  34.         String strDataToEncrypt = new String();  
  35.         String strCipherText = new String();  
  36.         String strDecryptedText = new String();  
  37.     
  38.         try {  
  39.             /** 
  40.              * Step 1. Generate an AES key using KeyGenerator Initialize the 
  41.              * keysize to 128 bits (16 bytes) 
  42.              *  
  43.              */  
  44.             KeyGenerator keyGen = KeyGenerator.getInstance("AES");  
  45.             keyGen.init(128);  
  46.             SecretKey secretKey = keyGen.generateKey();  
  47.     
  48.             /** 
  49.              * Step 2. Generate an Initialization Vector (IV)  
  50.              *      a. Use SecureRandom to generate random bits 
  51.              *         The size of the IV matches the blocksize of the cipher (128 bits for AES) 
  52.              *      b. Construct the appropriate IvParameterSpec object for the data to pass to Cipher's init() method 
  53.              */  
  54.     
  55.             final int AES_KEYLENGTH = 128;  // change this as desired for the security level you want  
  56.             byte[] iv = new byte[AES_KEYLENGTH / 8];    // Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later  
  57.             SecureRandom prng = new SecureRandom();  
  58.             prng.nextBytes(iv);  
  59.                 
  60.             /** 
  61.              * Step 3. Create a Cipher by specifying the following parameters 
  62.              *      a. Algorithm name - here it is AES  
  63.              *      b. Mode - here it is CBC mode  
  64.              *      c. Padding - e.g. PKCS7 or PKCS5 
  65.              */  
  66.     
  67.             Cipher aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!  
  68.     
  69.             /** 
  70.              * Step 4. Initialize the Cipher for Encryption 
  71.              */  
  72.     
  73.             aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey,   
  74.                     new IvParameterSpec(iv));  
  75.     
  76.             /** 
  77.              * Step 5. Encrypt the Data  
  78.              *      a. Declare / Initialize the Data. Here the data is of type String  
  79.              *      b. Convert the Input Text to Bytes  
  80.              *      c. Encrypt the bytes using doFinal method 
  81.              */  
  82.             strDataToEncrypt = "Hello World of Encryption using AES ";  
  83.             byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();  
  84.             byte[] byteCipherText = aesCipherForEncryption  
  85.                     .doFinal(byteDataToEncrypt);  
  86.             // b64 is done differently on Android  
  87.             strCipherText = new BASE64Encoder().encode(byteCipherText);  
  88.             System.out.println("Cipher Text generated using AES is "  
  89.                     + strCipherText);  
  90.     
  91.             /** 
  92.              * Step 6. Decrypt the Data  
  93.              *      a. Initialize a new instance of Cipher for Decryption (normally don't reuse the same object) 
  94.              *         Be sure to obtain the same IV bytes for CBC mode. 
  95.              *      b. Decrypt the cipher bytes using doFinal method 
  96.              */  
  97.     
  98.             Cipher aesCipherForDecryption = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // Must specify the mode explicitly as most JCE providers default to ECB mode!!               
  99.     
  100.             aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey,  
  101.                     new IvParameterSpec(iv));  
  102.             byte[] byteDecryptedText = aesCipherForDecryption  
  103.                     .doFinal(byteCipherText);  
  104.             strDecryptedText = new String(byteDecryptedText);  
  105.             System.out  
  106.                     .println(" Decrypted Text message is " + strDecryptedText);  
  107.         }  
  108.     
  109.         catch (NoSuchAlgorithmException noSuchAlgo) {  
  110.             System.out.println(" No Such Algorithm exists " + noSuchAlgo);  
  111.         }  
  112.     
  113.         catch (NoSuchPaddingException noSuchPad) {  
  114.             System.out.println(" No Such Padding exists " + noSuchPad);  
  115.         }  
  116.     
  117.         catch (InvalidKeyException invalidKey) {  
  118.             System.out.println(" Invalid Key " + invalidKey);  
  119.         }  
  120.     
  121.         catch (BadPaddingException badPadding) {  
  122.             System.out.println(" Bad Padding " + badPadding);  
  123.         }  
  124.     
  125.         catch (IllegalBlockSizeException illegalBlockSize) {  
  126.             System.out.println(" Illegal Block Size " + illegalBlockSize);  
  127.         }  
  128.     
  129.         catch (InvalidAlgorithmParameterException invalidParam) {  
  130.             System.out.println(" Invalid Parameter " + invalidParam);  
  131.         }  
  132.     }  
  133. }  

 

- Run As -> Java Application 선택 (소스를 컴파일하고 실행한다.)


 

- 에러가 발생하는지 확인한다.

("No Such Algorithm exists java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7PADDING")

※ 해당 에러는 SUN JCE에서 해당 패딩을 지원하지 않기 때문입니다.[5][6] 자바 버전9부터는 포함시킨다고 합니다.


 

- "AES/CBC/PKCS7PADDING"을 "AES/CBC/PKCS5PADDING"로 수정합니다. (라인 67, 98)


 

- Run As -> Java Application 선택하여 다시 실행


※ 하단 콘솔 창에 암복호화 결과를 확인할 수 있습니다.


 

 

이번 글에서는 '자바 암호 프로그래밍'을 하기 위한 가장 기초적인 단계인 '개발 도구 설치'(Eclipse, JDK)와SUN JCE 라이브러리로 AES 암복호화 하는 방법에 대해서 알아보았습니다. JCE로도 간단히 구현할 수는 있지만 아직까지는 bouncycastle 라이브러리만큼의 호환성을 보장하지 않습니다. 하지만 간단한 데이터 암호화 정도는 쉽게 적용이 가능합니다.

 

 

 

참고 목록

[1] http://www.eclipse.org/downloads

[2] http://www.oracle.com/technetwork/java/javase/downloads/index.html

[3] https://www.owasp.org/

[4] https://www.owasp.org/index.php/Using_the_Java_Cryptographic_Extensions

[5] http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8076969

[6] https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#pkcs5Pad

 

 

문서 이력

- v1.00(2016.09.06) : 최초 등록

반응형
Posted by IT반장