Know/Java

Triple DES Encryption (DESede)

Marine™ 2005. 3. 25. 11:44
반응형



DES-EDE 기본기능을 구현해보았다.

JDK1.4이상에서 지원이 되는 패키지를 썼으므로 당근 JDK1.4 밑으로는 안된다.


JDK1.4이하에서 사용하려면 아래를 참조

----------------------------------------------------------------------------------------------------------------------
1. JSDK 1.3이하 버젼 & JCE 1.2.1 글로벌 버전 JCE 1.2.1 버전은 http://java.sun.com 사이트에서 회원가입을 해야지 Down 받을수 있다. JCE는 미국에서 무기로 관주 되기 때문에 글로벌 버전은 미국, 케나다 버전과 다르다.
2. JSDK 1.4에는 Java Cryptography Extension 1.2.1 버전이 포함되어 있다.
3. 다운 받은 JCE의 압축을 풀고 lib방 밑에 있는 모든 jar파일을[JavaHome]\jre\lib\ext방으로 카피한다. 그리고 JCE 알고리즘을 사용하기 위해서 SunJCE 프로바이터를 설치 해야 한다.
설치하기 위해서는 [JavaHome]\jre\lib\security\java.security 파일에 다음을 추가한다.

security.provider.1=sun.security.provider.Sun,
security.provider.2=com.sun.crypto.provider.SunJCE
----------------------------------------------------------------------------------------------------------------------




실행시키면, 아래와 같이 문자열을 입력받는다.
--------------------------------------------------
Input Password:
marine.pe.kr <- 입력문자열
--------------------------------------------------

문자열을 입력후 Enter를 치면
아래와 같이 입력한 문자열, 암호화된 문자열, 복호화된 문자열이 출력이 된다.
--------------------------------------------------
Entered: marine.pe.kr
Encrypt : HC46t4BzpxIuw+HldvVJuA==
Recovered: marine.pe.kr
--------------------------------------------------





소스는 아래와 같다.

import javax.crypto.Cipher;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import java.security.Key;
import java.security.InvalidKeyException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.*;
import java.io.*;


public class LocalEncrypter {

private static String algorithm = "DESede";
private static Key key = null;
private static Cipher cipher = null;
private static DESedeKeySpec desEdeKeySpec = null;

//Encryption에 사용될 키값.
private static String key_value = "AAAAAAAAAAAAAAAAAAAAAAAA";
private static byte[] salt = key_value.getBytes();




/**
* DES-EDE에 쓰일 Key 값과 cipher 객체의 초기화
*
* @throws Exception
*/
private static void setUp() throws Exception {

//DES-EDE ( 「트리플 DES」) 열쇠를 지정합니다.
desEdeKeySpec = new DESedeKeySpec(salt);

//지정된 비밀열쇠 알고리즘의 SecretKeyFactory 오브젝트를 생성합니다
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);

//지정된 열쇠 데이터로부터 SecretKey 오브젝트를 생성합니다
key = secretKeyFactory.generateSecret(desEdeKeySpec);

cipher = Cipher.getInstance(algorithm);

}


public static void main(String[] args) throws Exception {

setUp();

System.out.println( "Input Password: ");
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
String str = br.readLine();


if (str.length() < 1) {
System.out.println( "USAGE: java LocalEncrypter " + "[String]");
System.exit(1);
}

String encryptionString = "";
String input = str;

System.out.println("Entered: " + input);
encryptionString = encrypt(input);

System.out.println("Encrypt : "+encryptionString);
System.out.println("Recovered: " + decrypt(encryptionString));


}

/**
* 입력받은 String의 DES-EDE 암호화
* 암호화된 byte[]를 저장하기 위하여 Base64Encoding을 하여 Return한다.
*
* @param input
* @return
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
private static String encrypt(String input) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {


cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] inputBytes = input.getBytes();
byte[] result = cipher.doFinal(inputBytes);

String encode_result = Base64Util.encode(result);

return encode_result;
}


/**
* 입력받은 Base64Encoding 된 String을 다시 Decoding하여
* DES-EDE 복호화된 String을 반환한다.
*
* @param encryptionString
* @return
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
private static String decrypt(String encryptionString) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptionBytes = Base64Util.decode(encryptionString);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes);
return recovered;
}
}



class Base64Util {

public Base64Util() {}

/**
* Base64Encoding을 수행한다. binany in ascii out
*
* @param encodeBytes encoding할 byte array
* @return encoding 된 String
*/
public static String encode(byte[] encodeBytes) {

BASE64Encoder base64Encoder = new BASE64Encoder();
ByteArrayInputStream bin = new ByteArrayInputStream(encodeBytes);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = null;

try{
base64Encoder.encodeBuffer(bin, bout);
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
buf = bout.toByteArray();
return new String(buf).trim();
}

/**
* Base64Decoding 수행한다. binany out ascii in
*
* @param strDecode decoding할 String
* @return decoding 된 byte array
*/
public static byte[] decode(String strDecode) {

BASE64Decoder base64Decoder = new BASE64Decoder();
ByteArrayInputStream bin = new ByteArrayInputStream(strDecode.getBytes());
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = null;

try {
base64Decoder.decodeBuffer(bin, bout);
} catch(Exception e) {
System.out.println("Exception");
e.printStackTrace();
}

buf = bout.toByteArray();

return buf;

}
}




반응형