#include "stdafx.h"
#include "SecurityV2.h"
#include "vector.h"
#include "Base64Helper.h"

static CBase64Helper base64;

SecurityV2::SecurityV2()
{
	
}

SecurityV2::~SecurityV2()
{
	
}

int SecurityV2::Init(){

	return 1;
}

// encryption is done using the conventional time pad algorithm
const TCHAR * SecurityV2::Encrypt(const TCHAR * password, const TCHAR * text)
{
	static std::wstring ciphertext;
	HRESULT hRes;
	SAFEARRAY * passwordArray, * textArray;
	BSTR Result;
	int passwordN, textN;
	short * passwordShorts, * textShorts;

	bstr_t passwordBSTR = password;
	bstr_t textBSTR = text;

	hRes = VectorFromBstr(passwordBSTR, &passwordArray);
	hRes = VectorFromBstr(textBSTR, &textArray);
	passwordN = passwordArray->rgsabound[0].cElements/sizeof(short);
	textN = textArray->rgsabound[0].cElements/sizeof(short);
	passwordShorts = (short *)passwordArray->pvData;
	textShorts = (short *)textArray->pvData;

	// shift according to password
	int i, j;
	for(i=0;i<textN;i++){
		j = passwordN-(i%passwordN)-1;
		textShorts[i] += passwordShorts[j];
	}

	hRes = base64.Base64EncodeByteArray(&textArray);
	hRes = BstrFromVector(textArray, &Result);
	::SafeArrayDestroy(textArray);
	::SafeArrayDestroy(passwordArray);

	ciphertext = Result;
	::SysFreeString(Result);

	return ciphertext.data();
}


const TCHAR * SecurityV2::Decrypt(const TCHAR * password, const TCHAR * text)
{
	static std::wstring cleartext;
	HRESULT hRes;
	SAFEARRAY * passwordArray, * textArray;
	BSTR Result;
	int passwordN, textN;
	short * passwordShorts, * textShorts;

	bstr_t passwordBSTR = password;
	bstr_t textBSTR = text;

	hRes = VectorFromBstr(passwordBSTR, &passwordArray);
	hRes = VectorFromBstr(textBSTR, &textArray);
	hRes = base64.Base64DecodeByteArray(&textArray);

	passwordN = passwordArray->rgsabound[0].cElements/sizeof(short);
	textN = textArray->rgsabound[0].cElements/sizeof(short);
	passwordShorts = (short *)passwordArray->pvData;
	textShorts = (short *)textArray->pvData;

	// shift according to password
	int i, j;
	for(i=0;i<textN;i++){
		j = passwordN-(i%passwordN)-1;
		textShorts[i] -= passwordShorts[j];
	}

	hRes = BstrFromVector(textArray, &Result);
	::SafeArrayDestroy(textArray);
	::SafeArrayDestroy(passwordArray);

	cleartext = Result;
	::SysFreeString(Result);

	return cleartext.data();
}