package biz.comm;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;

public class COMMLoadKey {
	private byte[] iv;
	private byte[] mk;
	
	public COMMLoadKey(String keyPath) throws Exception {
		String ivData = "";
		String keyData = "";
		try {
			BufferedReader br = new BufferedReader(new FileReader(keyPath));
			String readLine = "";
			for( int i = 0;(readLine = br.readLine()) != null;i++ ) {
				if( i == 0 ) {
					ivData = readLine;
				}else if( i == 1) {
					keyData = readLine;
				}else {
					break;
				}
			}
			br.close();
		}catch(IOException ioe) {
			throw ioe;
		}finally {
			ivData = clearTag(ivData);
			keyData = clearTag(keyData);
			iv = ivData.getBytes();
			mk = keyData.getBytes();
		}
	}
	
	public byte[] getIV() {
		return iv;
	}
	
	public byte[] getMK() {
		return mk;
	}
	
	public byte[] toByteArray(String data) {
		byte temp[] = (new BigInteger(data, 16)).toByteArray();
		
		if( temp[0] == 0 ) {
			byte temp2[] = new byte[temp.length - 1];
			System.arraycopy(temp, 1, temp2, 0, temp2.length);
			return temp2;
		}else {
			return temp;
		}
	}
	
	public String clearTag(String data) {
		StringBuffer sb = new StringBuffer();
		int start = data.indexOf('{');
		int end = data.lastIndexOf('}');
		
		data = data.substring(start + 1, end);
		data = data.replace(" ", "");
		
		String byteStr[] = data.split(",");
		for( int i = 0;i < byteStr.length;i++ ) {
			String temp = byteStr[i];
			if( temp.length() == 4 && temp.startsWith("0x") ) {
				sb.append(String.format("%c", Integer.parseInt(temp.substring(2))));
			}
		}
		
		return sb.toString();
	}
}