package com.eactive.eai.adapter.socket2.protocol.inicis.handshake;

import kr.co.extrus.exafe.ie2e.ExafeiE2E;

public class InicisCodec {

	private static InicisCodec instance;

	private static ExafeiE2E ie2e;

	private InicisCodec() {

	}

	public static synchronized InicisCodec getInstance(String keyPath, String keyPass) throws Exception {
		if(instance==null) {
			
			instance = new InicisCodec();
			
			String E2E_KEYFILE = ""; 
			String E2E_CERTFILE = "";
			String E2E_CODE = "";
			
			try {

				E2E_KEYFILE = keyPath + "/key.pem"; 
				E2E_CERTFILE = keyPath + "/cert.pem";
				E2E_CODE = keyPass;
				
				// 암호화 모듈 초기화 - 한번만 수행				
				ie2e = new ExafeiE2E();
				ie2e.InitCert(E2E_KEYFILE, E2E_CERTFILE, E2E_CODE);
				
			} catch (Exception e) {
				throw new Exception("InicisCodec | Exafei 초기화 에러: " + e.getMessage() + ", keyPath|keyPass: " + keyPath + "|" + keyPass 
						+ ", E2E_KEYFILE|E2E_CERTFILE|E2E_CODE: " + E2E_KEYFILE + "|" + E2E_CERTFILE + "|" + E2E_CODE);
			}			
		}		
		return instance;
	}

	public byte[] decrypt(byte[] bytes) throws Exception {
		
		byte[] decrypted = null;
				
		try {
			decrypted = ie2e.Decryption(new String(bytes)).getBytes();
		} catch (Exception e) {
			throw new Exception("InicisCodec | Exafei 복호화 에러: " + e.getMessage());
		}
		
		return decrypted;
	}
	
	public static byte[] encrypt(byte[] bytes) {
		
		return bytes;
	}

	
	
//	public static void main(String[] args){
//		
//		ExafeiE2E ie2e;
//		String E2E_KEYFILE = "/";
//		String E2E_CERTFILE = "/";
//		String E2E_CODE = "/";
//		
//		ie2e = new ExafeiE2E();
//		byte[] input_data = "00000274RD8160                               T20120719095522banktpg                                 1DK                                                        0  00990007                              ^|BT|^CRYPTO=Y,GSID=                                ,FIELD_SIZE=592,DEC_LEN=11,PW_LEN=15,PAD= ,ALIGN=L,ENC_DATA=rn3f7p6cqgN5jJo9aRjbhQ==,ENVELOP_DATA=MIIBQQYJKoZIhvcNAQcDoIIBMjCCAS4CAQAxgeswgegCAQAwUTBEMQswCQYDVQQGEwJLUjEPMA0GA1UECBMGSmVvbmp1MQ8wDQYDVQQKEwZKQkJhbmsxEzARBgNVBAMUCkUyRV9TZXJ2ZXICCQCq5nr6/7/EOzANBgkqhkiG9w0BAQEFAASBgCssAOhR2yRUxjwUhIgBWoROnfkBMrGZOyYgcOafwnGwYG429ZoXC3iwtqwHlq2X5JlT84JB39U36mUHJH2rq/PYS/yEQWgoaYyHO/bvE/DtAIJW2SBztGuPMIn6spDQAoyka4ZUQyEi2zn9MxauV/Iz5F2F8K1N3ZOKr67nTjNmMDsGCSqGSIb3DQEHATAcBggqgxqMmkQBBAQQLi5FeGFmZUUyRS4uISEuLoAQrn3f7p6cqgN5jJo9aRjbhQ==^|BT|^".getBytes();
//		byte[] result = null;
//		
//		// 암호화 모듈 초기화 - 한번만 수행
//		try {
//			ie2e.InitCert(E2E_KEYFILE, E2E_CERTFILE, E2E_CODE);
//		} catch (Exception e) {
//			System.out.println("InicisServerFilter | Exafei 초기화 에러.");
//		}	
//		
//		try {
//			result = InicisCodec.decrypt(input_data, ie2e);
//		} catch (Exception e) {
//			
//			e.printStackTrace();
//		}
//		
//		System.out.println("decrypt : " + CommonLib.hexDump(result));
//		
//	}
}