// Crypt.h
//

#include "stdafx.h"
#include "crypt.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

char* CCrypt::m_pszKey = "SPConsole1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

CString CCrypt::Encrypt(CString sString)
{
	USES_CONVERSION;

	int nKeyLen = (int)strlen(m_pszKey);
	int iPos    = (int)sString.GetLength() % nKeyLen;

	CString sRet;

	LPCSTR pszAscii = T2CA(sString);
	for (unsigned int i = 0;i < strlen(pszAscii); i++) {
		CString sTemp = sRet;
		sRet.Format(_T("%s%03d"), sTemp, (unsigned char)pszAscii[i] ^ m_pszKey[(i + iPos) % nKeyLen]);
	}

	return sRet;
}

CString CCrypt::Decrypt(CString sString)
{
	USES_CONVERSION;

	LPCSTR pszAscii = T2CA(sString);

	int nKeyLen = (int)strlen(m_pszKey);
	int iPos    = ((int)strlen(pszAscii) / 3) % nKeyLen;

	CString sRet;

	TCHAR szTemp[2];
	szTemp[1] = 0;
	for (unsigned int i = 0; i < strlen(pszAscii) / 3; i++) {
		int nDigit, nNumber = 0;

		nDigit = pszAscii[i * 3];
		if (nDigit < '0' || nDigit > '9')
			return _T("");
		nNumber += (nDigit - '0') * 100;
		nDigit = pszAscii[i * 3 + 1];
		if (nDigit < '0' || nDigit > '9')
			return _T("");
		nNumber += (nDigit - '0') * 10;
		nDigit = pszAscii[i * 3 + 2];
		if (nDigit < '0' || nDigit > '9')
			return _T("");
		nNumber += nDigit - '0';

		szTemp[0] = nNumber ^ m_pszKey[(i + iPos) % nKeyLen];
		sRet += szTemp;
	}

	return sRet;
}
