3DES

2009. 9. 3. 19:21코드

 
package com.umaking;

import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

/**
* 3DES 암호화로 암호화 복호화를 한다.
* @author ChangYeol.Kim
*
*/
public class CryptoUtil {
	private static Key key = null;

	static {
		if(key == null) {
			// Key 초기화
			KeyGenerator keyGenerator;
			try {
				keyGenerator = KeyGenerator.getInstance("TripleDES");
				keyGenerator.init(168);
				key = keyGenerator.generateKey();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
	}

	public static String Encode(String inStr) {
		StringBuffer sb = null;
		try {
			Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] plaintext = inStr.getBytes("UTF8");
			byte[] ciphertext = cipher.doFinal(plaintext);

			sb = new StringBuffer(ciphertext.length * 2);
			for(int i = 0; i < ciphertext.length; i++) {
			String hex = "0" + Integer.toHexString(0xff & ciphertext[i]); 
			sb.append(hex.substring(hex.length()-2));
		}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return sb.toString();
	}

	public static String Decode(String inStr) {
	String text = null;
	try {
		byte[] b = new byte[inStr.length()/2];
		Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		for(int i = 0; i < b.length; i++) {
			b[i] = (byte)Integer.parseInt(inStr.substring(2*i, 2*i+2), 16);
		}
		byte[] decryptedText = cipher.doFinal(b);
		text = new String(decryptedText,"UTF8");
	}catch(Exception e) {
		e.printStackTrace();
	}
	
	return text;
	}
}

'코드' 카테고리의 다른 글

GNUstep Make파일을 만들다.  (0) 2009.10.22
AWK - 디스크 용량 분석  (0) 2009.10.13
TrayIcon - TaskbarCreated 신호시....  (0) 2009.07.12
JSTL - customTag를 만들어 보자.  (0) 2009.03.16
prototype 1.6에서 SelectBOX 생성  (0) 2009.03.07