본문 바로가기

프로그래밍/JAVA 프로그래밍

자바를 이용한 암호화

HEX 클래스 사용을 위한 라이브러리:

commons-codec-1.8.jar

CipherUtils.java

 

MD5/SHA256 을 이용한 해쉬생성 예제

 

 public static String getMD5(String source) {
		  String MD5 = ""; 
			try{
				MessageDigest md = MessageDigest.getInstance("MD5"); 
				md.update(source.getBytes()); 
				byte byteData[] = md.digest();
				MD5=Hex.encodeHexString(byteData);
				System.out.println("원문: "+source+ "   MD5: "+MD5);
			}catch(NoSuchAlgorithmException e){
				e.printStackTrace(); 
				MD5 = null; 
			}
			return MD5;
	  }
	  
	  public static String getSHA256(String source) {
		  String SHA256 = ""; 
			try{
				MessageDigest md = MessageDigest.getInstance("SHA-256"); 
				md.update(source.getBytes()); 
				byte byteData[] = md.digest();
				SHA256=Hex.encodeHexString(byteData);
			    System.out.println("원문: "+source+ "   MD5: "+SHA256);
			}catch(NoSuchAlgorithmException e){
				e.printStackTrace(); 
				SHA256 = null; 
			}
			return SHA256;
	  }

 

AES 128을 이용한 블록 암호화예제

 

public static void testAES(String message) {
		  try {
			  KeyGenerator generator = KeyGenerator.getInstance("AES");
			  SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			  generator.init(128, random);
			  Key secureKey = generator.generateKey();
			  
			  System.out.println("원문: "+message);
			  
			  Cipher cipher = Cipher.getInstance("AES");
			  cipher.init(Cipher.ENCRYPT_MODE, secureKey);
			  byte[] encryptedData = cipher.doFinal(message.getBytes());
			  System.out.println("암호문: "+Hex.encodeHexString(encryptedData));
			  
			  cipher = Cipher.getInstance("AES");
			  cipher.init(Cipher.DECRYPT_MODE, secureKey);
			  byte[] plainText = cipher.doFinal(encryptedData);
			  System.out.println("복호문: "+new String(plainText));
		  
		  }catch(Exception e){
			  e.printStackTrace();
		  }
	  }

 

java에서 AES 암호화를 이용할 때 키 길이가 긴 경우 JDK버전에 따라 아래와 같은 에러가 나올 수 있다. 

java.lang.SecurityException: Unsupported keysize or algorithm parameters

java.security.InvalidKeyException: Illegal key size or default parameters

이럴 경우 첨부된 파일을 아래의 경로에 복사해주면 해결된다.

%JAVA%\jdk1.7.0_03\jre\lib\security
%JAVA%\jre7\lib\security


UnlimitedJCEPolicyJDK7.zip


 



자바 암호화 패키지

출처: http://web.sihu.org:9080/wordpress/?p=83

JCE 라고 함 javax.crypto 패키지는 JDK 1.4버전 부터 포함 되고 있으며, 보통 JAVA_HOME/jre/lib 아래에 jce.jar라는 파일로 포함 되어 있음

/*
 * 작성된 날짜: 2010. 5. 20.
 */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES128 {
 /*
  * AES의 경우 128, 192, 256bit의 키 길이를 지원합니다
  * key 에 해당하는 문자열을 16byte(128) 또는 24byte(192) 또는 32byte(256) 생성
  */

    public static String key = “0123456789123456″;
    /**
     * hex to byte[] : 16진수 문자열을 바이트 배열로 변환한다.
     *
     * @param hex    hex string
     * @return
     */

    public static byte[] hexToByteArray(String hex) {
        if (hex == null || hex.length() == 0) {
            return null;
        }

        byte[] ba = new byte[hex.length() / 2];
        for (int i = 0; i < ba.length; i++) {
            ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
       return ba;
    }

    /**
     * byte[] to hex : unsigned byte(바이트) 배열을 16진수 문자열로 바꾼다.
     *
     * @param ba        byte[]
     * @return
     */

    public static String byteArrayToHex(byte[] ba) {
        if (ba == null || ba.length == 0) {
            return null;
        }
        StringBuffer sb = new StringBuffer(ba.length * 2);
        String hexNumber;
        for (int x = 0; x < ba.length; x++) {
            hexNumber = “0″ + Integer.toHexString(0xff & ba[x]);
            sb.append(hexNumber.substring(hexNumber.length() – 2));
        }
        return sb.toString();
    }

    /**
     * AES 방식의 암호화
     *
     * @param message
     * @return
     * @throws Exception
     */

    public static String encrypt(String message) throws Exception {

        // use key coss2
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), “AES”);
        // Instantiate the cipher
        Cipher cipher = Cipher.getInstance(“AES”);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(message.getBytes());
        return byteArrayToHex(encrypted);
    }

    /**
     * AES 방식의 복호화
     *
     * @param message
     * @return
     * @throws Exception
     */

    public static String decrypt(String encrypted) throws Exception {
        // use key coss2
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), “AES”);

        Cipher cipher = Cipher.getInstance(“AES”);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] original = cipher.doFinal(hexToByteArray(encrypted));
        String originalString = new String(original);
        return originalString;

    }

    public static void main(String[] args)
    {
        try {
            String encrypt = encrypt(“test1234″);
            System.out.println(“origin str = “+”test1234″);
            System.out.println(“encrypt str = “+encrypt);  
            String decrypt = decrypt(encrypt);
            System.out.println(“decrypt str = “+decrypt);        

        } catch (Exception e) {
            e.printStackTrace();
        }    
    }
}