JSP

[Java] 암호화 (Base64, MD5, SHA, DES (TripleDES), AES, RSA), 전자서명

 

 ByteUtils.java

 CipherTest.java

 

 

3개의 jar 파일 다운로드 위치

1.   https://commons.apache.org/proper/commons-codec/download_codec.cgi

 

2.  http://www.java2s.com/Code/Jar/h/Downloadhamcrestcore12jar.htm

 

3. http://www.java2s.com/Code/Jar/c/Downloadcomspringsourceorgjunit450jar.htm

 

 

class ByteUtils 

package crypt;

/**
 * 이 클래스는 Byte 관련 함수를 제공합니다. 
 * 
 * @author <a href="mailto:kangwoo@jarusoft.com">kangwoo</a>
 * @version 1.0
 * @since 1.0
 */
public class ByteUtils {
	
	public static Byte DEFAULT_BYTE = new Byte((byte) 0);
	
	/**
	 * <p>문자열을 바이트로 변환한다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toByte("1", *)    = 0x01
	 * ByteUtils.toByte("-1", *)   = 0xff
	 * ByteUtils.toByte("a", 0x00) = 0x00
	 * </pre>
	 * 
	 * @param value 10진수 문자열 값
	 * @param defaultValue
	 * @return
	 */
	public static byte toByte(String value, byte defaultValue) {
		try {
			return Byte.parseByte(value);	
		} catch(Exception e) {
			return defaultValue;
		}
	}

	/**
	 * <p>문자열을 바이트로 변환한다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toByteObject("1", *)    = 0x01
	 * ByteUtils.toByteObject("-1", *)   = 0xff
	 * ByteUtils.toByteObject("a", 0x00) = 0x00
	 * </pre>
	 * 
	 * @param value 10진수 문자열 값
	 * @param defaultValue
	 * @return
	 */
	public static Byte toByteObject(String value, Byte defaultValue) {
		try {
			return new Byte(value);
		} catch (Exception e) {
			return defaultValue;
		}
	}

    
    /**
     * <p>singed byte를 unsinged byte로 변환한다.</p>
     * <p>Java에는 unsinged 타입이 없기때문에, int로 반환한다.(b & 0xff)</p>
     * 
     * @param b singed byte
     * @return unsinged byte 
     */
	public static int unsignedByte(byte b) {
		return  b & 0xFF;
	}

	/**
	 * <p>입력한 바이트 배열(4바이트)을 int 형으로 변환한다.</p>
	 * 
	 * @param src
	 * @param srcPos
	 * @return
	 */
	public static int toInt(byte[] src, int srcPos) {
		int dword = 0;
		for (int i = 0; i < 4; i++) {
			dword = (dword << 8) + (src[i + srcPos] & 0xFF);
		}
		return dword;
	}
	
	/**
	 * <p>입력한 바이트 배열(4바이트)을 int 형으로 변환한다.</p>
	 * 
	 * @param src
	 * @return
	 */
	public static int toInt(byte[] src) {
		return toInt(src, 0);
	}
	
	/**
	 * <p>입력한 바이트 배열(8바이트)을 long 형으로 변환한다.</p>
	 * 
	 * @param src
	 * @param srcPos
	 * @return
	 */
	public static long toLong(byte[] src, int srcPos) {
		long qword = 0;
		for (int i = 0; i < 8; i++) {
			qword = (qword << 8) + (src[i + srcPos] & 0xFF);
		}
		return qword;
	}
	
	/**
	 * <p>입력한 바이트 배열(8바이트)을 long 형으로 변환한다.</p>
	 * 
	 * @param src
	 * @return
	 */
	public static long toLong(byte[] src) {
		return toLong(src, 0);
	}

	/**
	 * <p>int 형의 값을 바이트 배열(4바이트)로 변환한다.</p>
	 * 
	 * @param value
	 * @param dest
	 * @param destPos
	 */
	public static void toBytes(int value, byte[] dest, int destPos) {
		for (int i = 0; i < 4; i++) {
			dest[i + destPos] = (byte)(value >> ((7 - i) * 8));
		}
	}
	
	/**
	 * <p>int 형의 값을 바이트 배열(4바이트)로 변환한다.</p>
	 * 
	 * @param value
	 * @return
	 */
	public static byte[] toBytes(int value) {
		byte[] dest = new byte[4];
		toBytes(value, dest, 0);
		return dest;
	}
	
	/**
	 * <p>long 형의 값을 바이트 배열(8바이트)로 변환한다.</p>
	 * 
	 * @param value
	 * @param dest
	 * @param destPos
	 */
	public static void toBytes(long value, byte[] dest, int destPos) {
		for (int i = 0; i < 8; i++) {
			dest[i + destPos] = (byte)(value >> ((7 - i) * 8));
		}
	}
	
	/**
	 * <p>long 형의 값을 바이트 배열(8바이트)로 변환한다.</p>
	 * 
	 * @param value
	 * @return
	 */
	public static byte[] toBytes(long value) {
		byte[] dest = new byte[8];
		toBytes(value, dest, 0);
		return dest;
	}
	
	/**
	 * <p>8, 10, 16진수 문자열을 바이트 배열로 변환한다.</p>
	 * <p>8, 10진수인 경우는 문자열의 3자리가, 16진수인 경우는 2자리가, 하나의 byte로 바뀐다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toBytes(null)     = null
	 * ByteUtils.toBytes("0E1F4E", 16) = [0x0e, 0xf4, 0x4e]
	 * ByteUtils.toBytes("48414e", 16) = [0x48, 0x41, 0x4e]
	 * </pre>
	 * 
	 * @param digits 문자열
	 * @param radix 진수(8, 10, 16만 가능)
	 * @return
	 * @throws NumberFormatException
	 */
	public static byte[] toBytes(String digits, int radix) throws IllegalArgumentException, NumberFormatException {
		if (digits == null) {
			return null;
		}
		if (radix != 16 && radix != 10 && radix != 8) {
			throw new IllegalArgumentException("For input radix: \"" + radix + "\"");
		}
		int divLen = (radix == 16) ? 2 : 3;
    	int length = digits.length();
    	if (length % divLen == 1) {
    		throw new IllegalArgumentException("For input string: \"" + digits + "\"");
    	}
    	length = length / divLen;
    	byte[] bytes = new byte[length];
    	for (int i = 0; i < length; i++) {
    		int index = i * divLen;
    		bytes[i] = (byte)(Short.parseShort(digits.substring(index, index+divLen), radix));
    	}
    	return bytes;
	}
	
	/**
	 * <p>16진수 문자열을 바이트 배열로 변환한다.</p>
	 * <p>문자열의 2자리가 하나의 byte로 바뀐다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toBytesFromHexString(null)     = null
	 * ByteUtils.toBytesFromHexString("0E1F4E") = [0x0e, 0xf4, 0x4e]
	 * ByteUtils.toBytesFromHexString("48414e") = [0x48, 0x41, 0x4e]
	 * </pre>
	 * 
	 * @param digits 16진수 문자열
	 * @return
	 * @throws NumberFormatException
	 * @see HexUtils.toBytes(String)
	 */
	public static byte[] toBytesFromHexString(String digits) throws IllegalArgumentException, NumberFormatException {
		if (digits == null) {
			return null;
		}
    	int length = digits.length();
    	if (length % 2 == 1) {
    		throw new IllegalArgumentException("For input string: \"" + digits + "\"");
    	}
    	length = length / 2;
    	byte[] bytes = new byte[length];
    	for (int i = 0; i < length; i++) {
    		int index = i * 2;
    		bytes[i] = (byte)(Short.parseShort(digits.substring(index, index+2), 16));
    	}
    	return bytes;
	}
	
	/**
	 * <p>unsigned byte(바이트)를 16진수 문자열로 바꾼다.</p>
	 * 
	 * ByteUtils.toHexString((byte)1)   = "01"
	 * ByteUtils.toHexString((byte)255) = "ff"
	 * 
	 * @param b unsigned byte
	 * @return
	 * @see HexUtils.toString(byte)
	 */
	public static String toHexString(byte b) {
		StringBuffer result = new StringBuffer(3);
		result.append(Integer.toString((b & 0xF0) >> 4, 16));
		result.append(Integer.toString(b & 0x0F, 16));
		return result.toString();
	}
	
	/**
	 * <p>unsigned byte(바이트) 배열을 16진수 문자열로 바꾼다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toHexString(null)                   = null
	 * ByteUtils.toHexString([(byte)1, (byte)255])   = "01ff"
	 * </pre>
	 * 
	 * @param bytes unsigned byte's array
	 * @return
	 * @see HexUtils.toString(byte[])
	 */
	public static String toHexString(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		
		StringBuffer result = new StringBuffer();
		for (byte b : bytes) {
			result.append(Integer.toString((b & 0xF0) >> 4, 16));
			result.append(Integer.toString(b & 0x0F, 16));
		}
		return result.toString();
	}
	
	/**
	 * <p>unsigned byte(바이트) 배열을 16진수 문자열로 바꾼다.</p>
	 * 
	 * <pre>
	 * ByteUtils.toHexString(null, *, *)                   = null
	 * ByteUtils.toHexString([(byte)1, (byte)255], 0, 2)   = "01ff"
	 * ByteUtils.toHexString([(byte)1, (byte)255], 0, 1)   = "01"
	 * ByteUtils.toHexString([(byte)1, (byte)255], 1, 2)   = "ff"
	 * </pre>
	 * 
	 * @param bytes unsigned byte's array
	 * @return
	 * @see HexUtils.toString(byte[])
	 */
	public static String toHexString(byte[] bytes, int offset, int length) {
		if (bytes == null) {
			return null;
		}
		
		StringBuffer result = new StringBuffer();
		for (int i = offset; i < offset + length; i++) {
			result.append(Integer.toString((bytes[i] & 0xF0) >> 4, 16));
			result.append(Integer.toString(bytes[i] & 0x0F, 16));
		}
		return result.toString();
	}
    
	/**
	 * <p>두 배열의 값이 동일한지 비교한다.</p>
	 * 
	 * <pre>
	 * ArrayUtils.equals(null, null)                        = true
	 * ArrayUtils.equals(["one", "two"], ["one", "two"])    = true
	 * ArrayUtils.equals(["one", "two"], ["three", "four"]) = false
	 * </pre>
	 * 
	 * @param array1
	 * @param array2
	 * @return 동일하면 <code>true</code>, 아니면 <code>false</code>
	 */
	public static boolean equals(byte[] array1, byte[] array2) {
		if (array1 == array2) {
			return true;
		}
		
		if (array1 == null || array2 == null) {
			return false;
		}
		
		if (array1.length != array2.length) {
			return false;
		}
		
		for (int i = 0; i < array1.length; i++) {
			if (array1[i] != array2[i]) {
				return false;
			}
		}
		
		return true;
	}
}

 

 

 

class CipherTest

package crypt;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import static org.hamcrest.CoreMatchers.is; 
import static org.junit.Assert.assertThat; 


public class CipherTest {

	
	
	public void base64() throws Exception {
		String str = "password";
		String encStr = Base64.encodeBase64String(str.getBytes());
		String decStr = new String(Base64.decodeBase64(encStr));
		
		System.out.println("값 : " + str);
		System.out.println("Base64 Encode : " + encStr);
		System.out.println("Base64 Decode : " + decStr);
	}
	
	
	
	public void md5() throws Exception {
		String str = "password";
		
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(str.getBytes()); 
		byte byteData[] = md.digest();
		StringBuffer sb = new StringBuffer();
		for(int i = 0 ; i < byteData.length ; i++){
			sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
		}
		System.out.println("값 : " + str);
		System.out.println("MD5 : " + sb.toString());
	}
	
	
	
	public void sha256() throws Exception {
		String str = "password";
		
		MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
		sha256.update(str.getBytes()); 
		byte byteData[] = sha256.digest();
		StringBuffer sb = new StringBuffer(); 
		for(int i = 0 ; i < byteData.length ; i++){
			sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
		}
		System.out.println("값 : " + str);
		System.out.println("SHA-256 : " + sb.toString());
	}
	
	
	
	public void sha512() throws Exception {
		String str = "password";
		
		MessageDigest sha256 = MessageDigest.getInstance("SHA-512");
		sha256.update(str.getBytes()); 
		byte byteData[] = sha256.digest();
		StringBuffer sb = new StringBuffer(); 
		for(int i = 0 ; i < byteData.length ; i++){
			sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
		}
		System.out.println("값 : " + str);
		System.out.println("SHA-256 : " + sb.toString());
	}
	
	
	
	public void DES() throws Exception {
		Key key = generateKey("DES", ByteUtils.toBytes("68616e6765656e61", 16));

		String transformation = "DES/ECB/NoPadding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "korea123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));

	}
	
	
	
	
	public void DESPadding() throws Exception {
		Key key = generateKey("DES", ByteUtils.toBytes("68616e6765656e61", 16));

		String transformation = "DES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "korea";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	

	
	public void DESede() throws Exception {
		Key key = generateKey("DESede", ByteUtils.toBytes("696d697373796f7568616e6765656e61696d697373796f75", 16));

		String transformation = "DESede/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	
	public void AES() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));

		String transformation = "AES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	
	public void AES_CBC() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		String str = "hello123";
		byte[] plain = str.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	

	
	public void AESFile() throws Exception {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		String transformation = "AES/ECB/PKCS5Padding";

		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);

		File plainFile = new File("c:/plain.txt");
		File encryptFile = new File("c:/encrypt.txt");
		File decryptFile = new File("c:/decrypt.txt");
		
		BufferedInputStream input = null;
		BufferedOutputStream output = null;
		try {
			input = new BufferedInputStream(new FileInputStream(plainFile));
			output = new BufferedOutputStream(new FileOutputStream(encryptFile));
			
			int read = 0;
			byte[] inBuf = new byte[1024];
			byte[] outBuf = null;
			while ((read = input.read(inBuf)) != -1) {
				outBuf = cipher.update(inBuf, 0, read);
				if (outBuf != null) {
					output.write(outBuf);
				}
			}
			outBuf = cipher.doFinal();
			if (outBuf != null) {
				output.write(outBuf);
			}
		} finally {
			if (output != null) try {output.close();} catch(IOException ie) {}
			if (input != null) try {input.close();} catch(IOException ie) {}
		}
				
		cipher.init(Cipher.DECRYPT_MODE, key);
		try {
			input = new BufferedInputStream(new FileInputStream(encryptFile));
			output = new BufferedOutputStream(new FileOutputStream(decryptFile));
			
			int read = 0;
			byte[] inBuf = new byte[1024];
			byte[] outBuf = null;
			while ((read = input.read(inBuf)) != -1) {
				outBuf = cipher.update(inBuf, 0, read);
				if (outBuf != null) {
					output.write(outBuf);
				}
			}
			outBuf = cipher.doFinal();
			if (outBuf != null) {
				output.write(outBuf);
			}
		} finally {
			if (output != null) try {output.close();} catch(IOException ie) {}
			if (input != null) try {input.close();} catch(IOException ie) {}
		}
	}
	
	
	
	public void password() throws Exception {
		String password = "mypassword";
		
		byte[] passwordBytes = password.getBytes();
		int len = passwordBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(passwordBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(passwordBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = passwordBytes[i % len];
			}
		}
		
		Key key = generateKey("AES", keyBytes);
		String transformation = "AES/ECB/PKCS5Padding";
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		
		byte[] plain = password.getBytes();
		byte[] encrypt = cipher.doFinal(plain);
		
		System.out.println("원문 : " + ByteUtils.toHexString(plain));
		System.out.println("암호 : " + ByteUtils.toHexString(encrypt));
		
		cipher.init(Cipher.DECRYPT_MODE, key);
		byte[] decrypt = cipher.doFinal(encrypt);
		System.out.println("복호 : " + ByteUtils.toHexString(decrypt));
	}
	
	
	/**
	 * 관리자가 지정한 키로 암호화/복호화 한다.
	 * 
	 * @throws Exception
	 */
	
	public void passwordStr() throws Exception {
		String pasword = "mypassword";
		
		String encrypt = AESEncode(pasword);
		String decrypt = AESDecode(encrypt);
		
		System.out.println("원문 : " + pasword);
		System.out.println("암호 : " + encrypt);
		System.out.println("복호 : " + decrypt);
		
		assertThat(pasword, is(decrypt));
	}
	
	
	/**
	 * 비밀번호 자체를 키로 암호화/복호화 사용한다.
	 * 본인이 아니면 알 수 없으므로 보안에 좋음.
	 * 
	 * @throws Exception
	 */
	
	public void passwordStr2() throws Exception {
		String password = "mypassword";
		
		String encrypt = AESEncode2(password);
		String decrypt = AESDecode2(encrypt, password);
		
		System.out.println("원문 : " + password);
		System.out.println("암호 : " + encrypt);
		System.out.println("복호 : " + decrypt);
		
		assertThat(password, is(decrypt));
	}
	
	
	
	/**
	 * 해당 알고리즘에 사용할 비밀키(SecretKey)를 생성한다.
	 * 
	 * @param algorithm
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	private static Key generateKey(String algorithm) throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey;
	}
	
	/**
	 * 주어진 데이터로, 해당 알고리즘에 사용할 비밀키(SecretKey)를 생성한다.
	 * 
	 * @param algorithm
	 * @param keyData
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws InvalidKeySpecException
	 */
	public static Key generateKey(String algorithm, byte[] keyData) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
		if ("DES".equals(algorithm)) {
			KeySpec keySpec = new DESKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else if ("DESede".equals(algorithm) || "TripleDES".equals(algorithm)) {
			KeySpec keySpec = new DESedeKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else {
			SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
			return keySpec;
		}
		/*
		String upper = algorithm.toUpperCase();
		if ("DES".equals(upper)) {
			KeySpec keySpec = new DESKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else if ("DESede".equals(upper) || "TripleDES".equals(upper)) {
			KeySpec keySpec = new DESedeKeySpec(keyData);
			SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
			SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
			return secretKey;
		} else {
			SecretKeySpec keySpec = new SecretKeySpec(keyData, algorithm);
			return keySpec;
		}
		*/
	}
	
	
	public static String AESEncode(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = cipher.doFinal(str.getBytes("UTF-8"));
		String encryptStr = new String(Base64.encodeBase64(encrypt));
		return encryptStr;
	}
	
	public static String AESEncode2(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		byte[] strBytes = str.getBytes();
		int len = strBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(strBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(strBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = strBytes[i % len];
			}
		}
		
		
		Key key = generateKey("AES", keyBytes);
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = cipher.doFinal(str.getBytes("UTF-8"));
		String encryptStr = new String(Base64.encodeBase64(encrypt));
		return encryptStr;
	}
	
	
	public static String AESDecode(String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Key key = generateKey("AES", ByteUtils.toBytes("696d697373796f7568616e6765656e61", 16));
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = Base64.decodeBase64(str.getBytes());
		byte[] decrypt = cipher.doFinal(encrypt);
		String decryptStr = new String(decrypt, "UTF-8");
		return decryptStr;
	}
	
	
	public static String AESDecode2(String encryptStr, String str) throws InvalidKeySpecException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		byte[] strBytes = str.getBytes();
		int len = strBytes.length;
		byte[] keyBytes = new byte[16];
		if (len >= 16) {
			System.arraycopy(strBytes, 0, keyBytes, 0, 16);
		} else {
			System.arraycopy(strBytes, 0, keyBytes, 0, len);
			for (int i = 0; i < (16 - len); i++) {
				keyBytes[len + i] = strBytes[i % len];
			}
		}
		
		Key key = generateKey("AES", keyBytes);
		byte[] iv = ByteUtils.toBytes("26c7d1d26c142de0a3b82f7e8f90860a", 16);
		String transformation = "AES/CBC/PKCS5Padding";

		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
		
		byte[] encrypt = Base64.decodeBase64(encryptStr.getBytes());
		byte[] decrypt = cipher.doFinal(encrypt);
		String decryptStr = new String(decrypt, "UTF-8");
		return decryptStr;
	}
	
}

 

 

 

 

 

jsp

 

about author

PHRASE

Level 60  머나먼나라

상대가 어린아이처럼 어리고 유치한 행동을 한다면 가르치는 쪽도 역시 어리고 유치한 태도로서 해야 한다. 결코 무리하게 해서는 안 되는 것이다. -장자

댓글 ( 6)

댓글 남기기

작성