Click here to Skip to main content
Licence CPOL
First Posted 7 Aug 2002
Views 124,243
Bookmarked 63 times

Literal string encryption as part of the build process

By | 17 Mar 2005 | Article
CXR allows you to create encrypted strings at compile time.

Introduction

Have you ever wished there was a way to use strings for messages, passwords or other text inside your app that didn't require you to use a literal string, because you were worried about someone finding the strings in your EXE ? Wish no more, CXR is here.

What does it do?

CXR is a combination of a text parser, a stream cipher and C source code generator. You define your literal text strings in a ".CXR" file as part of your normal coding process, using standard C/C++ constructs. Then, when you build your project, the CXR program will encrypt those strings and generate a new .CPP file that is compiled into your project, automatically. The process is somewhat like what happens with .IDL files when you are working on an ATL project.

What?

Here's an example:
You create a .CXR file that contains your string definitions and a unique password:
////////////////////
// my .CRX file
//
// here is my password definition:
// CXRP = "SexyBeast"		
//
// here are some strings:				

// my first string   
const char* pString1 = _CXR("AbcdEfg1234  blah\tblah"); 

// string #2
const char* pString2
       = _CXR("This is a long one, not that it should matter...");

As you can see, the only difference between this and standard C/C++ is the _CXR specifier. The comment line with the password is required, and any text you want encrypted must be inside a _CXR(...) specifier. Anything else in the file will be copied over to the output .CPP unchanged. So, that's how you set up the .CXR file. When you build your project, the CXR parser will read this file and generate a .CPP that looks like this:

///////////////////////////
#ifdef _USING_CXR
// my first string
const char* pString1 = "ab63103ff470cb642b7c319cb56e2dbd591b63a93cf88a";
#else
const char* pString1 = _CXR("AbcdEfg1234  blah\tblah");  // my first string
#endif

///////////////////////////
#ifdef _USING_CXR

// string #2
const char* pString2 = 
    "baff195a3b712e15ee7af636065910969bb24997c49c6d0cc6a40d3ec1...";
#else
// string #2
const char* pString2 = 
    _CXR("This is a long one, not that it should matter..."); 
#endif
...more stuff below...

Presto. The CXR parser has encrypted your strings.

OK, how do i get my strings back?

The "...more stuff below..." is actually the decryptor code. That decryptor code is compiled into your project, with the CXR password you gave. So, all you have to do to is this:
CString csString1 = _CRX(pString1);
// pString1 = "ab63103ff470cb642b7c319cb56e2dbd591b63a93cf88a"
// and now csString1 = "AbcdEfg1234  blah\tblah";

Note the #ifdef _USING_CXR tags. Because of these, you can disable the CXR strings by simply changing a single #define - to make testing easier. If _USING_CXR is not defined, all your strings revert to their unencrypted form and the "_CXR" turns into a macro that does nothing. If _USING_CXR is defined, your strings take on their encrypted forms and the _CXR macro becomes a call to the decrypting code. It's (almost) totally seamless.

It can't be that easy

Well, it's almost that easy. There are some steps you need to follow to add your .CRX file to your project and to enable the CXR parser. But, these are all one-time things. Once you set them up the first time, you never have to do it again.

Setting up

  1. Build the CXR.EXE and put it somewhere in your path (in your WinNT or Windows folder, perhaps).

  2. Create your .CRX file. Create a file that has your password definition and your literal text strings. Follow these rules:
    • A .CXR file must contain a password line of the form:
      // CXRP = "MyPasswordString"
      Where the password string is any string you want. The "// CXRP =" part is required.

    • All text strings that are to be encrypted must be enclosed in a _CXR(...) tag.

    • _CXR(...) tags can not span multiple lines.

    • CXR currently does not support Unicode. All your strings will be treated by the encoder as if they were ANSI strings. Using this in a Unicode build will probably cause you large headaches. Unicode support is planned in the future, but it isn't supported right now.

  3. Create a .H file for your strings. Really, this is just a basic C/C++ issue. CXR will generate a .CPP file with your encoded strings. But, as with any extern strings, if you want to use them in your code, you have to define them somewhere. In the example above, I would create a file called "strings.h" and add the following:
    extern const char* pString1;
    extern const char* pString2;

  4. Add the .CXR file to your project. You have to do this manually (right click on your project in the File View, select the .CXR file, etc.).

  5. Add a new .CPP file to your project. The CXR parser will generate a .CPP file for you. But, you have to tell the compiler to compile it. So, add another file to your project. If your .CXR file was named "Strings.CXR", add "Strings.CPP" to your project - just type in the name when the file dialog pops up. Since this file doesn't exist yet, Visual Studio will ask if you want to add a reference to it anyway. Say Yes. The first time you build, the .CPP will be created.

  6. Set the custom build options. Find your .CXR file in the Project / Settings, menu. Check "Always use custom build step". On the Custom Build tab, in the "Commands" section, enter the following:
    cxr.exe -i $(InputPath) -o $(ProjDir)\$(InputName).cpp
    This will cause Visual Studio to call CXR.EXE with the name of your .CXR file as input and the same name, but with a .CPP extension as output.

    In the "Outputs" section, enter:

    $(ProjDir)\$(InputName).cpp
    This tells the compiler that this file needs to be recompiled when the .CXR file changes.

  7. Add cxr_inc.h to your project and add #include "cxr_inc.h" in every file in which you want to use the encrypted strings. There is a copy of this file in the sample "Test" project. But, it looks just like this:
    #ifndef CRXHeaderH
    #define CRXHeaderH
    
    #define _USING_CXR
    
    #ifndef _USING_CXR
    #define _CXR(x) x
    
    #else
    
    #define _CXR(x) __CXRDecrypt(x)
    extern CString __CXRDecrypt(const char *pIn);
    
    #endif
    
    #endif
    This file defines the macros you need to use to get your strings. This is also a good place to turn off the _USING_CXR macro, if you want to use your strings un-encrypted for any reason.

  8. That's it! I know it looks like a lot. But again, the previous steps only have to be done once. After the setup is complete, the only interaction you'll have with CXR is when you edit and access your strings.

In detail

CXR is fairly simple. The parser scans the .CXR input file, looking for two things: 1. the password line and 2: quoted strings inside _CXR(...) tags. Anything else it just copies to the output as-is. When it finds a _CXR tag, it encrypts the string with your password, converts the encrypted data to printable characters and outputs the encrypted version, along with the original version, in an #ifdef...#endif chunk. The parser is somewhat dumb; it doesn't understand much C/C++; it only knows to looks for the password and _CXR("..."), this is what prevents the use of multi-line text and Unicode. It does, however understand the syntax of C/C++ literal strings (including all escapes documented in K&R v2).

The encryption code is based on the quick and small Sapphire II stream cipher, from Crypto++. XOR would work equally as well, since we're only concerned about obfuscating the strings, not in keeping them secure against decryption attack.

You must be stupid. This won't stop crackers

No, I'm not stupid. I know that this by itself won't stop crackers. This is only a part of a complete defense. Of course if they find and watch the CXR decryption code, they can see the decrypted strings coming out; but they would have to know to look for it and find it, first. What CXR really does is it stops them from finding your "Registation complete!" and "Your trial period has expired!" messages with a simple string scan of the .EXE. Protection against crackers (as cracking itself) is a black art, not a science. As I see it, every twist and turn you can throw at the crackers stands a chance of being the one that causes them to give up and move on to the next target. Every barrier you can put in their way is a good one.

Updates

  • 9 Aug, 2002 - Changed character encoding from hex digits (1,2,3..f) to offset-based. This obscures the strings even better. Fixed the demo package.
  • 17 Mar 2005 - updated source code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris Losinger

Software Developer

United States United States

Member

Chris Losinger is the president of Smaller Animals Software, Inc..

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Newscxr branch on google code Pinmemberpaleozogt5:32 13 Jan '10  
Generaldirect encryption Pinmemberpatrick.steal6:45 20 Jul '07  
GeneralRe: direct encryption [modified] PinmemberChris Losinger6:57 20 Jul '07  
Questionweird problem Pinmemberpatrick.steal7:17 3 Jul '07  
AnswerRe: weird problem PinmemberChris Losinger7:36 3 Jul '07  
News! Two Problems [modified] PinmemberSynetech5:16 23 May '06  
GeneralThings I had to change to compile CXR PinmemberHokei10:41 2 Mar '06  
GeneralRe: Things I had to change to compile CXR PinmemberHokei20:42 14 Mar '06  
I rewrote all the source to use STL classes instead of MFC. I didn't want to use MFC, and it's not portable anyway. If anyone is interested, here is the source. I apologize in advance if the Code Project comment engine screws up any of the code as I try to post it.
 
CXR_standard.cpp:

// CXR_Standard.cpp
//
// BASED ON code from Smaller Animals Software. Their copyright notice
// follows. Usage: CXR -i [filename.cpp] -o [filename.cpp]
//
//********************************************************************
//
// Copyright (C) 2002 Smaller Animals Software, Inc.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// http://www.smalleranimals.com
// smallest@smalleranimals.com
//
//*********************************************************************
 
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include "Tokenizer.h"
#include "Stream.h"
 
using namespace std;
 
static bool ProcessFile(ifstream &in, const string &strInFilename, ofstream &out, const string &strOutFilename);
static bool AddDecode(const string &strPassword, ofstream &out);
static string Encrypt(const string &strIn, const char* pPass);
static string Decrypt(const char* pIn, const char* pPass);
static bool ExpandOctal(const string &strIn, string &strOut, int &iConsumed);
static string TranslateString(const string &strIn);
static bool ExpandHex(const string &strIn, string &strOut, int &iConsumed);
static string EscapeString(const char* pIn);
 
// The basechar is added/subtracted with every character as part of the
// encrypt/decrypt process, but for what -- obfuscation?
// These can be adjusted in the range 1 to 239:
const int basechar1 = 128;
const int basechar2 = 128;
 
int _tmain(int argc, _TCHAR* argv[])
{
int nRetCode = 0;
 
srand((unsigned int)time(NULL));
 
cerr << _T("Starting CXR, the literal string encryptor. Copyright 2002, Smaller Animals Software Inc.") << endl;
 
if ((basechar1 == 0) || (basechar2 == 0) || (basechar1 > 239) || (basechar2 > 239))
{
cerr << _T("CXR basechar values out of acceptable range. Aborting") << endl;
nRetCode = 1;
return nRetCode;
}
 
if (argc >= 2)
{
//TODO: Smarter command line argument parsing:
string strInFile = argv[2];
string strOutFile = argv[4];
 
if (!strInFile.empty() && !strOutFile.empty())
{
// open the input file (always an ANSI file)
ifstream fileIn;
 
// open the output file (always an ANSI file)
ofstream fileOut;

fileIn.open(strInFile.c_str(), ios::in);
if(fileIn.is_open())
{
fileOut.open(strOutFile.c_str(), ios::trunc | ios::out);
if(fileOut.is_open())
{
if (!ProcessFile(fileIn, strInFile, fileOut, strOutFile))
{
cerr << _T("CXR failed") << endl;
nRetCode = 1;
}
}
else
{
cerr << _T("Unable to open output file: ") << strOutFile << endl;
nRetCode = 1;
}
}
else
{
cerr << _T("Unable to open input file: ") << strInFile << endl;
nRetCode = 1;
}
 
if (nRetCode==0)
{
cerr << _T("CXR created: ") << strOutFile << endl;
}
}
else
{
cerr << _T("Not enough parameters.") << endl;
cerr << _T("Usage: CXR -i [filename.cpp] -o [filename.cpp]") << endl;
nRetCode = 1;
}
}
else
{
cerr << _T("Not enough parameters.") << endl;
cerr << _T("Usage: CXR -i [filename.cpp] -o [filename.cpp]") << endl;
nRetCode = 1;
}
 
return nRetCode;
}
 

///////////////////////////////////////////////////////////////////////////////
// ProcessFile - Process a .CXR file (containing plaintext string literals)
// into C++ source files (containing the encrypted equivalent
// strings).
//
bool ProcessFile(ifstream &in, const string &strInFilename, ofstream &out, const string &strOutFilename)
{
// Note: do not use TCHAR or _T() here. Do this all with single-byte char
// and string only, because we are writing source code here and source code
// is ANSI text.
 
enum {eStateWantPassword, eStateHavePassword, };
 
int iState = eStateWantPassword;
 
string strPassword;
string strLine;
 
char* pMetachars = "/\\=();'";
char* pKeyWords[3] = {"//", "_CXR", "CXRP"};
 
CTokenizer tokenizer(pKeyWords, 3, pMetachars, (int)strlen(pMetachars));
int iErr = CTokenizer::eErrorNone;
bool ok = true;
 
out << "/////////////////////////////////////////////////////////////\n"
<< "// "
<< strOutFilename
<< "\n//\n"
<< "// This file was generated by CXR, the literal string encryptor.\n"
<< "// CXR, Copyright 2002, Smaller Animals Software, Inc., all rights reserved.\n"
<< "//\n"
<< "// Please do not edit this file. Any changes here will be overwritten on the next compile.\n// If you wish to make changes to a string, please edit:\n// "
<< strInFilename
<<"\n//\n"
<< "\n/////////////////////////////////////////////////////////////\n\n"
<< "#include \"stdafx.h\"\n"
<< "#include \"cxr_inc.h\"\n\n";
 
bool bFoundCXR = false;
 
do
{
if(in.eof())
break;
else
getline(in, strLine);
 
if (in.bad() || in.fail())
break;
 
switch (iState)
{
case eStateWantPassword:
iErr = tokenizer.Tokenize(strLine.c_str());
if (iErr == CTokenizer::eErrorNone)
{
if (tokenizer.GetTokenCount() >= 4)
{
// password declaration always looks like : // CXRP = "Password"
if ((tokenizer.GetToken(0).strToken == "//") &&
(tokenizer.GetToken(1).strToken == "CXRP") &&
(tokenizer.GetToken(2).strToken == "=") &&
(tokenizer.GetToken(3).bIsQuotedString))
{
// We'll use the password from the file, literally. it's not treated as
// a C string-literal, just as a section of a text file. when we
// go to write the decoder, we'll have to fix it up to make sure
// the compiler gets the same text by adding any necessary escapes.
strPassword = tokenizer.GetToken(3).strToken;
 
if (strPassword.empty())
{
cerr << _T("Invalid CXR password: \"") << strPassword.c_str() << _T("\"") << endl; //TODO: not gonna work in Unicode builds?
//ASSERT(0);
break;
}
 
iState = eStateHavePassword;
continue;
}
}
}
break;
case eStateHavePassword:
bFoundCXR = false;
iErr = tokenizer.Tokenize(strLine.c_str());
if (iErr == CTokenizer::eErrorNone)
{
if (tokenizer.GetTokenCount() > 4)
{
for (int i=0; i < tokenizer.GetTokenCount() - 4; i++)
{
// looking for _CXR ( "..." )
if ((tokenizer.GetToken(i).strToken == "_CXR") && !tokenizer.GetToken(i).bIsQuotedString &&
(tokenizer.GetToken(i + 1).strToken == "(") && !tokenizer.GetToken(i + 1).bIsQuotedString &&
(tokenizer.GetToken(i + 2).bIsQuotedString) &&
(tokenizer.GetToken(i + 3).strToken == ")") && !tokenizer.GetToken(i + 3).bIsQuotedString)
{
string strTrans = TranslateString(tokenizer.GetToken(i + 2).strToken);
string strEnc = Encrypt(strTrans, strPassword.c_str());
//string strDec = Decrypt(strEnc, strPassword.c_str()); //for debugging
 
out << "///////////////////////////\n#ifdef _USING_CXR\n";
 
//out << "//" << strDec << "\n";
 
// output up to _CXR
out << strLine.substr(0, tokenizer.GetToken(i).iStart);
 
// encrypted stuff
out << "\"" << strEnc << "\"";
 
// to the end of the line
out << strLine.substr(tokenizer.GetToken(i + 4).iStop)
<< "\n"
<< "#else\n"
<< strLine
<< "\n#endif\n\n";
 
bFoundCXR = true;
 
break;
} // found a good string ?
} // loop over tokens
} // > 4 tokens
} // tokenizer OK
 
if (bFoundCXR)
{
continue;
}
 
break;
} // switch
 
// done with it
out << strLine << "\n";
} while (1);
 
if (iState == eStateWantPassword)
{
cerr << _T("No password line found in input file") << endl;
return false;
}
 
//ASSERT(iState == eStateHavePassword);
 
// add the decoder functions
AddDecode(strPassword, out);
 
return true;
}
 

///////////////////////////////////////////////////////////////////////////////
// AddEncByte - Take BYTE c, obscure it by adding a base value (?), and
// append it (its value in hex characters) to string strOut
//
void AddEncByte(BYTE c, string &strOut)
{
char buf[4];
 
BYTE b1 = c >> 4;
BYTE b2 = c & 0x0f;
 
_snprintf(buf, 3, "%x", b1 + basechar1);
strOut += "\\x";
strOut += buf;
 
_snprintf(buf, 3, "%x", b2 + basechar1);
strOut += "\\x";
strOut += buf;
}
 

///////////////////////////////////////////////////////////////////////////////
// Encrypt - Given plaintext string strIn, encrypt it using password pPass
// and return it as a string of ciphertext.
//
string Encrypt(const string &strIn, const char* pPass)
{
string strOut;
 
// initialize out
CCXRIntEnc sap((const BYTE*)pPass, (int)strlen(pPass));
 
//start each string with a random char.
//because this is a stream cipher, the ciphertext of a
//string like "ABC" will be the same as the first 3 bytes
//of the ciphertext for "ABCDEFG".
 
//by starting with a random value, the cipher will be in a
//different state (255:1) when it starts the real text. the
//decoder will simply discard the first plaintext byte.
 
BYTE seed = rand() % 256;
BYTE c = sap.ProcessByte((BYTE)(seed));
AddEncByte(c, strOut);
 
// Ok, now encrypt and convert strIn to hex string:
for (int i=0; i < (int)strIn.length(); i++)
{
char temp = strIn.at(i);
BYTE c = sap.ProcessByte((BYTE)(temp));
AddEncByte(c, strOut);
}
 
return strOut;
}
 

///////////////////////////////////////////////////////////////////////////////
// Decrypt - Given ciphertext string pIn, decrypt using password pPass and
// return as a plaintext string.
//
string Decrypt(const TCHAR* pIn, const char* pPass)
{
string strOut;
 
CCXRIntDec sap((const BYTE*)pPass, (int)strlen(pPass));
 
int iLen = (int)strlen(pIn);
 
if (iLen > 2)
{
int iBufLen = (int)strlen(pIn);
if (iBufLen & 0x01)
{
cerr << _T("Illegal string length in Decrypt") << endl;
return pIn;
}
 
iBufLen /= 2;
 
for (int i=0; i < iBufLen; i++)
{
int b1 = pIn[i * 2] - basechar1;
int b2 = pIn[i * 2 + 1] - basechar2;
int c = (b1 << 4) | b2;
 
BYTE bc = sap.ProcessByte((BYTE)(c));
 
if (i>0)
strOut += (char)bc;
}
}
 
return strOut;
}
 

///////////////////////////////////////////////////////////////////////////////
// AddDecode - Write to the output source file, the decryption routines
// necessary to decrypt the strings we have encrypted.
//
bool AddDecode(const string &strPassword, ofstream &out)
{
out << "\n\n/////////////////////////////////////////////////////////////\n"
<< "// CXR-generated decoder follows\n\n"
<< "#include <algorithm>\n"
<< "const char * __pCXRPassword = \"";
 
// the password that encrypted the text used the literal text from the file (non-escaped \ chars).
// we need to make sure that compiler sees the same text when it gets the passowrd. so,
// we must double any "\" chars, to prevent them from becoming C-style escapes.
out << EscapeString(strPassword.c_str()) << "\";\n";
 
out << "const int __iCXRDecBase1 = " << basechar1 << ";\nconst int __iCXRDecBase2 = " << basechar2 << ";\n\n";

const char* szDecodingFunction =
"string __CXRDecrypt(const char* pIn)\n"\
"{\n"\
" string x; char b[3]; b[2]=0;\n"\
" CXRD sap((const BYTE*)__pCXRPassword, (int)strlen(__pCXRPassword));\n"\
" int iLen = (int)strlen(pIn);\n"\
" if (iLen > 2)\n"\
" {\n"\
" int ibl = (int)strlen(pIn);\n"\
" if (ibl & 0x01)\n"\
" {\n"\
/*" ASSERT(!\"Illegal string length in Decrypt\");\n"\*/
" return pIn;\n"\
" }\n"\
" ibl /= 2;\n"\
" for (int i=0; i < ibl; i++)\n"\
" {\n"\
" int b1 = pIn[i*2] - __iCXRDecBase1; int b2 = pIn[i*2+1] - __iCXRDecBase2;\n"\
" int c = (b1 << 4) | b2; char ch =(char)(sap.pb((BYTE)(c)));\n"\
" if (i>0)\n"\
" x += ch;\n"\
" }\n"\
" }\n"\
" return x;\n"\
"}\n";

const char* szStreamCipherFunction =
"class CCXR\n" \
"{\n" \
"protected:\n" \
" CCXR(const BYTE* key, unsigned int ks)\n" \
" {\n" \
" int i;BYTE rs;unsigned kp;\n" \
" for(i=0;i<256;i++)c[i]=i;kp=0;rs=0;for(i=255;i;i--)std::swap(c[i],c[kr(i,key,ks,&rs,&kp)]);r2=c[1];r1=c[3];av=c[5];lp=c[7];lc=c[rs];rs=0;kp=0;\n" \
" }\n" \
" inline void SC(){BYTE st=c[lc];r1+=c[r2++];c[lc]=c[r1];c[r1]=c[lp];c[lp]=c[r2];c[r2]=st;av+=c[st];}\n" \
" BYTE c[256],r2,r1,av,lp,lc; \n" \
"\n" \
" BYTE kr(unsigned int lm, const BYTE *uk, BYTE ks, BYTE *rs, unsigned *kp)\n" \
" {\n" \
" unsigned rl=0,mk=1,u;while(mk=ks){*kp=0;*rs+=ks;}u=mk&*rs;if(++rl>11)u%=lm;}while(u>lm);return u;\n" \
" }\n" \
"};\n" \
"struct CXRD:CCXR\n" \
"{\n" \
" CXRD(const BYTE *userKey, unsigned int keyLength=16) : CCXR(userKey, keyLength) {}\n" \
" inline BYTE pb(BYTE b){SC();lp=b^c[(c[r1]+c[r2])&0xFF]^c[c[(c[lp]+c[lc]+c[av])&0xFF]];lc=b;return lp;}\n" \
"};\n";
 
out << szStreamCipherFunction;
out << szDecodingFunction;
 
return true;
}
 

///////////////////////////////////////////////////////////////////////////////
// TranslateString - Translate C-style string escapes as documented in K&R
// 2nd, A2.5.2
//
string TranslateString(const string &strIn)
{
string strOut;
 
for (int i=0; i < (int)strIn.length(); i++)
{
int c = strIn.at(i); //TODO: Why even treat this as an int? Why not just char?
switch (c)
{
// normal text
default:
strOut += static_cast(c);
break;

// c-style escape
case '\\':
if (i < (int)strIn.length() - 1)
{
c = strIn.at(i + 1);
switch (c)
{
case 'n':
strOut += '\n';
break;
case 't':
strOut += '\t';
break;
case 'v':
strOut += '\v';
break;
case 'b':
strOut += '\b';
break;
case 'r':
strOut += '\r';
break;
case 'f':
strOut += '\f';
break;
case 'a':
strOut += '\a';
break;
case '\\':
strOut += '\\';
break;
case '?':
strOut += '?';
break;
case '\'':
strOut += '\'';
break;
case '\"':
strOut += '\"';
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
{
// expand octal
int iConsumed = 0;
if (!ExpandOctal(strIn.substr(i), strOut, iConsumed))
{
cerr << _T("Invalid octal sequence: ") << _T('\"') << strIn.c_str() << _T('\"') << endl; //TODO: Not gonna work in Unicode builds?
strOut = strIn;
break;
}
i += iConsumed - 1;
}
break;
case 'x':
{
// expand hex
int iConsumed = 0;
if (!ExpandHex(strIn.substr(i), strOut, iConsumed))
{
cerr << _T("Invalid hex sequence: ") << _T('\"') << strIn.c_str() << _T('\"') << endl; //TODO: Not gonna work in Unicode builds?
strOut = strIn;
break;
}
i += iConsumed - 1;
}
break;
}
 
i++;
continue;
}
else
{
cerr << _T("Invalid escape sequence: ") << _T('\"') << strIn.c_str() << _T('\"') << endl; //TODO: Not gonna work in Unicode builds?
strOut = strIn;
break;
}
break;
}
}
 
return strOut;
}
 

///////////////////////////////////////////////////////////////////////////////
// ExpandOctal
//
bool ExpandOctal(const string &strIn, string &strOut, int &iConsumed)
{
// starting with the escape, we need at least one more char
if (strIn.length() < 2)
return false;
 
if (strIn.at(0) != '\\')
return false;
 
int iStart = 1;
int iCur = iStart;
 
string strDigits;
int c = strIn.at(iCur); //TODO: again, why represent it with an int?
while ((c >= '0') && (c <= '7'))
{
strDigits += static_cast(c);
 
// An escape can't hold more that 3 octal digits (K&R 2nd A2.5.2)
if (iCur == 3)
break;

iCur++;
c = strIn.at(iCur);
}
 
char* end;
int octval = (char)strtol(strDigits.c_str(), &end, 8);
 
iConsumed = (int)strDigits.length();
 
strOut += static_cast<char>(octval);
 
return true;
}
 

///////////////////////////////////////////////////////////////////////////////
// ExpandHex
//
bool ExpandHex(const string &strIn, string &strOut, int &iConsumed)
{
// Starting with the escape and the 'x', we need at least one more char
if (strIn.length() < 3)
return false;
 
if ((strIn.at(0) != _T('\\')) || (strIn.at(1) != _T('x')))
return false;
 
int iStart = 2;
int iCur = iStart;
 
string strDigits;
int c = strIn.at(iCur);
while (_istxdigit(c))
{
strDigits += static_cast<char>(c);
 
iCur++;
c = strIn.at(iCur);
}
 
char* end;
 
// "There is no limit on the number of digits, but the behavior is undefined
// if the resulting character value exceeds that of the largest character"
// (K&R 2nd A2.5.2)
int hex = (char)strtol(strDigits.c_str(), &end, 16);
 
iConsumed = (int)strDigits.length();
 
iConsumed++; // count the "x"
 
strOut += static_cast<char>(hex);
 
return true;
}
 

///////////////////////////////////////////////////////////////////////////////
// EscapeString
//
string EscapeString(const char* pIn)
{
string strOut;
 
int iLen = (int)strlen(pIn);
 
for (int i=0; i < iLen; i++)
{
strOut += pIn[i];

// Double all "\" chars
if (pIn[i] == '\\')
{
strOut += '\\';
}
}
 
return strOut;
}

 
Tokenizer.cpp:

/*********************************************************************
 
Copyright (C) 2002 Smaller Animals Software, Inc.
 
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
 
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
 
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
 
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
 
3. This notice may not be removed or altered from any source distribution.
 
http://www.smalleranimals.com
smallest@smalleranimals.com
 
**********************************************************************/
 
// Tokenizer.cpp: implementation of the CTokenizer class.
//
//////////////////////////////////////////////////////////////////////
 
#include "stdafx.h"
#include "Tokenizer.h"
 
// CXR does not have comments
#undef ALLOW_COMMENTS
 
// strip quotes on strings, please
#undef RETURN_QUOTED_STRINGS
 
#ifdef ALLOW_COMMENTS
#define COMMENT_START "/*"
#define COMMENT_STOP "*/"
#endif
 
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//
CTokenizer::CTokenizer(char** pKeyWords, int iKeyWords, char* pMetaChars, int iMetaChars)
{
m_pKeyWords = pKeyWords;
m_iKeyWords = iKeyWords;
m_MetaChars = pMetaChars;
m_iMetaChars = iMetaChars;
}
 
CTokenizer::~CTokenizer()
{
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::Clear() - Remove tokens
//
void CTokenizer::Clear()
{
m_tokens.clear();
}
 

void CTokenizer::Init()
{
Clear();
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::Tokenize - Extract an array of tokens from input text
//
int CTokenizer::Tokenize(const char* pInputLine)
{
int err = eErrorNone;
 
Init();
 
int iLen = (int)strlen(pInputLine);
 
bool bInComment = false;
 
for (int i=0; i < iLen; i++)
{
string curTokenString;
bool bQuotedString = false;
 
int iConsumed = GetToken(pInputLine + i, curTokenString, bQuotedString);
 
if (iConsumed > 0)
{
//if (curTokenString.length() > 0)
{
#ifdef ALLOW_COMMENTS
if (curTokenString == COMMENT_START)
{
bInComment = true;
i+=iConsumed;
continue;
}

if (curTokenString == COMMENT_STOP)
{
if (!bInComment)
{
err = eErrorSyntax;
break;
}
 
bInComment = false;
 
i += iConsumed;
continue;
}
#endif
 
if (!bInComment)
{
int iStart = i;
int iStop = i + iConsumed - 1;
 
CSAToken curToken(curTokenString.c_str(), iStart, iStop, bQuotedString);
 
m_tokens.push_back(curToken);
}
}

i += iConsumed;
 
i--; // back up! the for iteration will increase i
continue;
}
else
{
if (IsMetaChar(*(pInputLine + i)))
{
if (!isspace(*(pInputLine + i)))
{
curTokenString.clear();
curTokenString += *(pInputLine + i);
 
CSAToken curToken(curTokenString.c_str(), i, (int)curTokenString.length() - 1, bQuotedString);
 
m_tokens.push_back(curToken);
}
}
}
}
 
return err;
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::IsKeyWord - Asks: is this text a keyword?
//
bool CTokenizer::IsKeyWord(string &str)
{
return IsKeyWord((const char*)str.c_str());
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::IsKeyWord
//
bool CTokenizer::IsKeyWord(const char* pInput)
{
if (m_pKeyWords==NULL)
{
return false;
}
 
int iLen = (int)strlen(pInput);
 
int iBestMatch = -1;
 
for (int i=0; i < m_iKeyWords; i++)
{
int iCurKWLen = (int)strlen(m_pKeyWords[i]);
 
if (iLen <= iCurKWLen)
{
if (strnicmp(m_pKeyWords[i], pInput, iCurKWLen)==0)
{
iBestMatch = i;
}
}
}
 
if (iBestMatch==-1)
{
#ifdef ALLOW_COMMENTS
if (CSAScrUtil::sa_strnicmp(COMMENT_START, pInput, strlen(COMMENT_START))==0)
{
iBestMatch = m_iKeyWords + 1;
}
 
if (CSAScrUtil::sa_strnicmp(COMMENT_STOP, pInput, strlen(COMMENT_STOP))==0)
{
iBestMatch = m_iKeyWords + 2;
}
#endif
}
return (iBestMatch != -1);
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::GetToken - find the next token in the string
//
int CTokenizer::GetToken(const char* pInput, string &out, bool &bQuotedString)
{
int iLen = (int)strlen(pInput);
 
bool bFoundChars = false;
 
bool bScanningMetaKW = false;
 
bool bInQuotes = false;
 
bQuotedString = false;
 
char c;
 
for (int iWS = 0; iWS < iLen; iWS++)
{
c = *(pInput + iWS);
if (!isspace(c))
break;
if (!iscntrl(c))
break;
}
 
for (int i=iWS; i 1)
return false;
 
char c = str.at(0);
 
for (int i=0; i < m_iMetaChars; i++)
{
if (c == m_MetaChars[i])
return true;
}
 
return false;
}
 

//////////////////////////////////////////////////////////////////////
// CTokenizer::Dump
//
void CTokenizer::Dump()
{
CSATokenVector::iterator theIterator;
 
int i=0;
for (theIterator = m_tokens.begin(); theIterator < m_tokens.end(); theIterator++)
{
//If you're interested in debug output, re-implement this to suit you:
//TRACE("%d [%d-%d] : \"%s\"\n", i++, (*theIterator).iStart, (*theIterator).iStop, (const TCHAR *)((*theIterator).csToken));
}
}
 

//////////////////////////////////////////////////////////////////////
// Operator overloading
//
bool operator < (const CSAToken &a, const CSAToken &b)
{
return (a.iStart < b.iStart);
}
 
bool operator == (const CSAToken &a, const CSAToken &b)
{
return (a.iStart == b.iStart);
}

 
cxr_inc.h:

/*********************************************************************
 
Copyright (C) 2002 Smaller Animals Software, Inc.
 
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
 
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
 
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
 
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
 
3. This notice may not be removed or altered from any source distribution.
 
http://www.smalleranimals.com
smallest@smalleranimals.com
 
**********************************************************************/
#pragma once
 
#include <string>
 
using namespace std;
 
#define _USING_CXR
 
#ifndef _USING_CXR
#define _CXR(x) x
#else
#define _CXR(x) __CXRDecrypt(x)
extern string __CXRDecrypt(const char* pIn);
#endif

 
stdafx.h:

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
 
#pragma once
 

#include <iostream>
#include <tchar.h>
 
// TODO: reference additional headers your program requires here
 

 
Stream.h:

/*********************************************************************
 
Copyright (C) 2002 Smaller Animals Software, Inc.
 
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
 
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
 
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
 
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
 
3. This notice may not be removed or altered from any source distribution.
 
http://www.smalleranimals.com
smallest@smalleranimals.com
 
**********************************************************************/
/*
modified by Chris Losinger for Smaller Animals Software, Inc.
*/
// Sapphire.cpp -- modified by Wei Dai from:
 
/* Sapphire.cpp -- the Saphire II stream cipher class.
Dedicated to the Public Domain the author and inventor:
(Michael Paul Johnson). This code comes with no warranty.
Use it at your own risk.
Ported from the Pascal implementation of the Sapphire Stream
Cipher 9 December 1994.
Added hash pre- and post-processing 27 December 1994.
Modified initialization to make index variables key dependent,
made the output function more resistant to cryptanalysis,
and renamed to CPASapphire II 2 January 1995
*/
 
#pragma once
 
typedef unsigned char BYTE;
 
class CCXRIntBase
{
protected:
CCXRIntBase(const BYTE* key, unsigned int ks)
{
int i;BYTE rs;unsigned kp;
for(i=0;i<256;i++)c[i]=i;kp=0;rs=0;for(i=255;i;i--)std::swap(c[i],c[kr(i,key,ks,&rs,&kp)]);r2=c[1];r1=c[3];av=c[5];lp=c[7];lc=c[rs];rs=0;kp=0;
}
inline void SC(){BYTE st=c[lc];r1+=c[r2++];c[lc]=c[r1];c[r1]=c[lp];c[lp]=c[r2];c[r2]=st;av+=c[st];}
BYTE c[256],r2,r1,av,lp,lc;
 
BYTE kr(unsigned int lm, const BYTE *uk, BYTE ks, BYTE *rs, unsigned *kp)
{
unsigned rl=0,mk=1,u;
while(mk=ks){*kp=0;*rs+=ks;}u=mk&*rs;
if(++rl>11)u%=lm;}while(u>lm);
return u;
}
};
 

struct CCXRIntDec:CCXRIntBase
{
CCXRIntDec(const BYTE *userKey, unsigned int keyLength=16) : CCXRIntBase(userKey, keyLength) {}
inline BYTE ProcessByte(BYTE b){SC();lp=b^c[(c[r1]+c[r2])&0xFF]^c[c[(c[lp]+c[lc]+c[av])&0xFF]];lc=b;return lp;}
};
 

struct CCXRIntEnc:CCXRIntBase
{
CCXRIntEnc(const BYTE *userKey, unsigned int keyLength=16) : CCXRIntBase(userKey, keyLength) {}
inline BYTE ProcessByte(BYTE b){SC();lc=b^c[(c[r1]+c[r2])&0xFF]^c[c[(c[lp]+c[lc]+c[av])&0xFF]];lp=b;return lc;}
};

 
Tokenizer.h:

/*********************************************************************
 
Copyright (C) 2002 Smaller Animals Software, Inc.
 
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
 
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
 
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
 
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
 
3. This notice may not be removed or altered from any source distribution.
 
http://www.smalleranimals.com
smallest@smalleranimals.com
 
**********************************************************************/
 
#pragma once
 
#include <vector>
#include <iterator>
 
#pragma warning(disable:4786)
using namespace std ;
using namespace std::rel_ops ;
 
//////////////////////////////////////////////////////////////////////
 
class CSAToken
{
public:
CSAToken()
{
iStart = iStop = -1;
bIsQuotedString = false;
}

CSAToken(const char* p, int x, int y, bool q)
{
strToken = p;
iStart = x;
iStop = y;
//ASSERT(x <= y);
 
bIsQuotedString = q;
}
 
string strToken;
int iStart;
int iStop;
bool bIsQuotedString;
};
 
//////////////////////////////////////////////////////////////////////
 
typedef vector<CSAToken> CSATokenVector;
 
//////////////////////////////////////////////////////////////////////
 
class CTokenizer
{
public:
enum {eErrorNone, eErrorSyntax,}eError;
 
CTokenizer(char** pKeyWords, int iKeyWords, char* pMetaChars, int iMetaChars);
virtual ~CTokenizer();
void Clear();
void Init();
 
int Tokenize(const char* pInputLine);

bool IsKeyWord(string &str);
bool IsKeyWord(const char* pInput);
 
void Dump();

bool IsMetaChar(const char c);
bool IsMetaChar(string &str);
 
_inline int GetTokenCount() {return (int)m_tokens.size();}
_inline CSAToken GetToken(int i) {return m_tokens.at(i);}
 
protected:
int GetToken(const char* pInput, string &out, bool &bQuotedString);

char** m_pKeyWords;
int m_iKeyWords;
char* m_MetaChars;
int m_iMetaChars;
 
CSATokenVector m_tokens;
};
 
//////////////////////////////////////////////////////////////////////
 
extern bool operator < (const CSAToken &a, const CSAToken &b);
extern bool operator == (const CSAToken &a, const CSAToken &b);

GeneralRe: Things I had to change to compile CXR Pinmemberichscheissdirinsgsichthey6:20 11 Sep '06  
GeneralThanks, and improvements PinmemberBoniolopez7:16 18 Jan '06  
GeneralRe: Thanks, and improvements PinmemberHokei9:24 2 Mar '06  
GeneralRe: Thanks, and improvements PinmemberBoniolopez10:56 2 Mar '06  
GeneralCXR for Linux PinmemberVoom20:25 6 May '05  
GeneralRe: CXR for Linux PinmemberHokei20:45 14 Mar '06  
GeneralRe: CXR for Linux Pinmemberpaleozogt5:59 13 Jan '10  
Generalcool PinmemberProxy4NT2:09 12 Apr '05  
GeneralYou can do (very) basic xor encryption with the preprocessors PinmemberAnonymous20:39 17 Mar '05  
GeneralRe: You can do (very) basic xor encryption with the preprocessors PinmemberAnonymous20:58 17 Mar '05  
QuestionDoesn't work with \ at the end? Pinmembermjimenez13:01 17 Mar '05  
AnswerRe: Doesn't work with \ at the end? PinmemberChris Losinger14:59 17 Mar '05  
GeneralSuggestion for obfuscated strings PinsitebuilderMichael Dunn18:30 5 Oct '02  
GeneralRe: Suggestion for obfuscated strings PinmemberChris Losinger12:23 6 Oct '02  
GeneralRe: Suggestion for obfuscated strings PinsitebuilderMichael Dunn12:35 6 Oct '02  
GeneralRe: Suggestion for obfuscated strings PinmemberChris Losinger16:59 6 Oct '02  
GeneralYou saved my job! PinsitebuilderMichael Dunn6:08 10 Aug '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 17 Mar 2005
Article Copyright 2002 by Chris Losinger
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid