Coding/Java

Blowfish를 이용한 암호화. javax.crypto.Cipher이용

realizm 2015. 4. 13. 11:02


대략 짠 코드


실제 시험은 안해봤습니다 ^^

package pe.kr.realizm.blowfishcrypto;

import java.io.FileInputStream;
import java.io.FileOutputStream;

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

public class BlowfishCrypto {
	
	private final static byte[] RAW_KEY = { (byte) 0x01, (byte) 0x02,
			(byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x07,
			(byte) 0x08, (byte) 0x09, (byte) 0x0a, (byte) 0x0b, (byte) 0x0c,
			(byte) 0x0d, (byte) 0x0e, (byte) 0x0f, (byte) 0x10 };

	private final static byte[] RAW_IV = { (byte) 0x11, (byte) 0x22,
			(byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77,
			(byte) 0x88 }

	private final static Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
	private final static SecretKeySpec cipherKey = new SecretKeySpec(BlowfishCrypto.RAW_KEY, "Blowfish");
	private final static IvParameterSpec iv = new IvParameterSpec(BlowfishCrypto.RAW_IV);

	public void decode(String srcFilePath, String destFilePath) throws Exception{
		byte[] bytes = decode(srcFilePath);
		writeToFile(destFilePath, bytes);
	}
	
	public byte[] decode(String srcFilePath) throws Exception{
		byte[] bytes = BlowfishCrypto.readFromFile(srcFilePath);
		return decode(bytes);
	}
	
	public byte[] decode(byte[] bytes) throws Exception{
		
		cipher.init(Cipher.DECRYPT_MODE, cipherKey, iv);
		
		return cipher.doFinal(bytes);
	}
	
	public void encode(String srcFilePath, String destFilePath) throws Exception{
		byte[] bytes = encode(srcFilePath);
		writeToFile(destFilePath, bytes);
	}

	public byte[] encode(String srcFilePath) throws Exception{
		byte[] bytes = BlowfishCrypto.readFromFile(srcFilePath);
		return encode(bytes);
	}
	
	public byte[] encode(byte[] bytes) throws Exception{

		cipher.init(Cipher.ENCRYPT_MODE, cipherKey, iv);
		
		return cipher.doFinal(bytes);
	}
	
	private byte[] readFromFile(String path) throws Exception{

		byte[] bytes = null;
		FileInputStream fis = null;

		try {
			fis = new FileInputStream(path);
			fis.read(bytes);
		} catch (Exception ex) {
			throw ex;
		} finally {
			if (fis != null) {
				fis.close();
			}
		}

		return bytes;
		
	}
	
	private void writeToFile(String path, byte[] bytes) throws Exception   {

		FileOutputStream fos = null;
		
		try {
			fos = new FileOutputStream(path);
			
			fos.write(bytes);
		} catch (Exception ex) {
			throw ex;
		} finally {
			if(fos != null) {
				fos.close();
			}
		}
	}
	
}