Click here to Skip to main content
Licence CPOL
First Posted 7 Aug 2002
Views 124,229
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  
GeneralRe: Things I had to change to compile CXR Pinmemberichscheissdirinsgsichthey6:20 11 Sep '06  
GeneralThanks, and improvements PinmemberBoniolopez7:16 18 Jan '06  
Dear Sir,
Thanks for this utility, it did just what I wanted. I made a small improvements.
1. Added casts, because else VS.NET compiler complains.
2. I hate to write things twice, therefore I added generation of a header file with externs. I.e. for your demo project it generates
--strings.h---
extern const char* pString1   ;//blabal
extern const char* pString2   ;
Now one can just include this file into all project files.
 
3. I added
#define CXR_CPP
into the generated cpp file. So that one can customize cxr_inc.h, depending on whether it is now included in cxr generated cpp or other project files (sometimes usefull).
 

I share the changes with people in the hope, that it can be usefull for somebody else too.
 
----crx.cpp--
<code>
/*********************************************************************
 
   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
 
**********************************************************************/
 
// CXR.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include "CXR.h"
#include "CmdLine.h"
#include "Tokenizer.h"
#include "Stream.h"
 

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
 
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
 
CWinApp theApp;
 
using namespace std;
 
/////////////////////////////////////////////////////////////////
 
static bool      ProcessFile(CStdioFile &in, CStdioFile &out, CStdioFile &outh);
static bool      AddDecode(const CString & csPassword, CStdioFile &out);
static CString   Encrypt(const CString &csIn, const char *pPass);
static CString   Decrypt(const char *pIn, const char *pPass);
static bool      ExpandOctal(const CString &csIn, CString &csOut, int &iConsumed);
static CString   TranslateCString(const CString &csIn);
static bool      ExpandHex(const CString &csIn, CString &csOut, int &iConsumed);
static CString      EscapeCString(const char *pIn);
 
// these can be adjusted in the range 1 to 239
const int basechar1 = 128;
const int basechar2 = 128;
 
/////////////////////////////////////////////////////////////////
 
int _tmain(int argc, char* argv[], char* envp[])
{
     int nRetCode = 0;
 
   srand(time(NULL));
 
     // initialize MFC and print and error on failure
     if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
     {
          // TODO: change error code to suit your needs
          cerr << _T("Fatal Error: MFC initialization failed") << endl;
          nRetCode = 1;
     }
     else
     {
         cerr << "Starting CXR, the literal string encryptor. Copyright 2002, Smaller Animals Software Inc.\n";
 
         if ((basechar1 == 0) || (basechar2 == 0) || (basechar1 > 239) || (basechar2 > 239))
         {
            cerr << "CXR basechar values out of acceptable range. Aborting\n";
            nRetCode = 1;
            return nRetCode;
         }
 
         CCmdLine cmd;
         if (cmd.SplitLine(argc, argv) >= 2)
         {
            CString csInFile = cmd.GetSafeArgument("-i", 0, "");
            CString csOutFile = cmd.GetSafeArgument("-o", 0, "");
            if (!csInFile.IsEmpty() && !csOutFile.IsEmpty())
            {
                   // open the input file
                  CStdioFile fileIn;
 
                  // open the output file
                  CStdioFile fileOut;
                  CStdioFile fileOuth;
               string _HeaderName=csOutFile;
               string::size_type _dot=_HeaderName.find_last_of(".");
               if   ((_dot!=string::npos)&&(_dot>1)){
                    _HeaderName=_HeaderName.substr(0,_dot);              
               };
               _HeaderName+=".h";
                  if (fileIn.Open(csInFile, CFile::modeRead | CFile::typeText))
                  {
                     if (fileOut.Open(csOutFile, CFile::modeCreate | CFile::modeWrite | CFile::typeText ))
                     {
                       if (fileOuth.Open(_HeaderName.c_str(), CFile::modeCreate | CFile::modeWrite | CFile::typeText ))
                           if (!ProcessFile(fileIn, fileOut,fileOuth))
                           {
                              cerr << "CXR failed\n";
                              nRetCode = 1;
                           }
                     }
                     else
                     {
                           cerr << _T("Unable to open output file: ") << (LPCTSTR)csOutFile << endl;
                           nRetCode = 1;
                     }
                  }
                  else
                  {
                     cerr << _T("Unable to open input file: ") << (LPCTSTR)csInFile << endl;
                     nRetCode = 1;
                  }
 
                  if (nRetCode==0)
                  {
                     cerr << "CXR created: " << (LPCTSTR)csOutFile << "\n";
                  }
            }
            else
            {
                  cerr << _T("Not enough parameters") << endl;
                  nRetCode = 1;
            }
         }        
         else
         {
            cerr << _T("Not enough parameters") << endl;
            nRetCode = 1;
         }
     }
 
     return nRetCode;
}
 
/////////////////////////////////////////////////////////////////
 
bool ProcessFile(CStdioFile &in, CStdioFile &out,CStdioFile &outh)
{
   enum
   {
         eStateWantPassword,
         eStateHavePassword,
   };
 
   int iState = eStateWantPassword;
 
   CString csPassword;
   CString line;
 
   char *pMetachars = _T("/\\=();'");
   char *pKeyWords[3] = {_T("//"), _T("_CXR"), _T("CXRP")};
  
   CTokenizer tokenizer(pKeyWords, 3, pMetachars, strlen(pMetachars));
   int iErr = CTokenizer::eErrorNone;
   bool ok = true;
 
   out.WriteString(_T("/////////////////////////////////////////////////////////////\n"));
   out.WriteString(_T("// "));
   out.WriteString(out.GetFileName());
   out.WriteString(_T("\n//\n"));
   out.WriteString(_T("// This file was generated by CXR, the literal string encryptor.\n"));
   out.WriteString(_T("// CXR, Copyright 2002, Smaller Animals Software, Inc., all rights reserved.\n"));
   out.WriteString(_T("//\n"));
   out.WriteString(_T("// 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//      "));
   out.WriteString(in.GetFilePath());
   out.WriteString(_T("\n//\n"));
   out.WriteString(_T("\n/////////////////////////////////////////////////////////////\n\n"));
   out.WriteString(_T("\n#define CXR_CPP\n\n"));
   out.WriteString(_T("#include \"stdafx.h\"\n"));
   out.WriteString(_T("#include \"cxr_inc.h\"\n\n"));
 

   outh.WriteString(_T("// 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//      "));
   outh.WriteString(in.GetFilePath());
   outh.WriteString(_T("\n//\n"));
 
   outh.WriteString(_T("#ifndef "));
   CString _fn=outh.GetFileName();
   _fn.Replace(".","_");
   _fn.MakeUpper();

   outh.WriteString(_fn);
   outh.WriteString(_T("\n#define "));
   outh.WriteString(_fn);
   outh.WriteString(_T("\n"));
   outh.WriteString(_T("#include \"cxr_inc.h\"\n\n"));
 
   bool bFoundCXR = false;
 
   do
   {
         if (!in.ReadString(line))
         {
            break;
         }
 
         switch (iState)
         {
         case eStateWantPassword:
            iErr = tokenizer.Tokenize(line);
            if (iErr == CTokenizer::eErrorNone)
            {
                  if (tokenizer.GetTokenCount() >= 4)
                  {
                     // password declaration always looks like : // CXRP = "Password"
                     if ((tokenizer.GetToken(0).csToken == _T("//")) &&
                           (tokenizer.GetToken(1).csToken == _T("CXRP")) &&
                           (tokenizer.GetToken(2).csToken == _T("=")) &&
                           (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.
                           csPassword = tokenizer.GetToken(3).csToken;
 
                           if (csPassword.IsEmpty())
                           {
                              cerr << _T("Invalid CXR password: \"") << (LPCTSTR)csPassword << _T("\"") << endl;
                              ASSERT(0);
                              break;
                           }
 
                           iState = eStateHavePassword;
                           continue;
                     }
                  }
            }
            break;
         case eStateHavePassword:
            bFoundCXR = false;
            iErr = tokenizer.Tokenize(line);
            if (iErr == CTokenizer::eErrorNone)
            {
                  if (tokenizer.GetTokenCount() > 4)
                  {
                     for (int i=0;i<tokenizer.GetTokenCount() - 4; i++)
                     {
                           // looking for _CXR ( "..." )
                           if (
                              (tokenizer.GetToken(i).csToken == _T("_CXR")) && !tokenizer.GetToken(i).bIsQuotedString &&
                              (tokenizer.GetToken(i + 1).csToken == _T("(")) && !tokenizer.GetToken(i + 1).bIsQuotedString &&
                              (tokenizer.GetToken(i + 2).bIsQuotedString) &&
                              (tokenizer.GetToken(i + 3).csToken == _T(")")) && !tokenizer.GetToken(i + 3).bIsQuotedString
                              )
                           {
                              CString csTrans = TranslateCString(tokenizer.GetToken(i + 2).csToken);
                              CString csEnc = Encrypt(csTrans, csPassword);
                              //CString csDec = Decrypt(csEnc, csPassword);
 
                              out.WriteString(_T("///////////////////////////\n#ifdef _USING_CXR\n"));
 
                              /*
                              out.WriteString("//");
                              out.WriteString(csDec);
                              out.WriteString("\n");
                              */
 
                              // output up to _CXR
                              out.WriteString(line.Left(tokenizer.GetToken(i).iStart));
                         CString _newline=line.Left(tokenizer.GetToken(i).iStart);
                         _newline.Replace("=","");
                         _newline=_newline.Trim(" ");
                        
                         // extern const char* ltrUnknown; //Unknown.
                         //Find last token in the string before = (i.e. variable name)
                         //and make #define lThisName _CRX(ThisName)
                         CString resToken;
                         CString TypeName;
                         int curPos=0;
                         resToken= _newline.Tokenize("% #*",curPos);
                         while (resToken != ""){
                              TypeName=resToken;
                              resToken= _newline.Tokenize("% #*",curPos);
                        
                         };
 
                         _newline=" extern "+_newline;
 
                         outh.WriteString(_newline);
                         outh.WriteString(_T("; //")+csTrans+_T("\n"));
                         outh.WriteString(_T("#define l")+TypeName+ _T("   _CXR(")+TypeName+_T(").c_str()\n\n"));
                              // encrypted stuff
                              out.WriteString(_T("\""));
                              out.WriteString(csEnc);
                              out.WriteString(_T("\""));
 
                              // to the end of the line
                              out.WriteString(line.Mid(tokenizer.GetToken(i + 4).iStop));
 
                              out.WriteString(_T("\n"));

                              out.WriteString(_T("#else\n"));
                              out.WriteString(line);
                              out.WriteString(_T("\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.WriteString(line);
         out.WriteString("\n");
 
   } while (1);
   outh.WriteString(_T("\n\n#endif"));
   if (iState == eStateWantPassword)
   {
         cerr << "No password line found in input file\n";
         return false;
   }
 
   ASSERT(iState==eStateHavePassword);
 
   // add the decoder functions
   AddDecode(csPassword, out);
 
   return true;
}
 
/////////////////////////////////////////////////////////////////
 
void AddEncByte(BYTE c, CString &csOut)
{
  
   char buf[4];
 
   BYTE b1 = c >> 4;
   BYTE b2 = c & 0x0f;
 
   _snprintf(buf, 3, "%x", b1 + basechar1);
   csOut+="\\x";
   csOut+=buf;
 
   _snprintf(buf, 3, "%x", b2 + basechar1);
   csOut+="\\x";
   csOut+=buf;
}
 
/////////////////////////////////////////////////////////////////
 
CString Encrypt(const CString &csIn, const char *pPass)
{
   CString csOut;
 
   // initialize out
   CCXRIntEnc sap((const BYTE*)pPass, 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, csOut);
 
   // encrypt and convert to hex string
   for (int i=0; i < csIn.GetLength(); i++)
   {
         char t = csIn.GetAt(i);
         BYTE c = sap.ProcessByte((BYTE)(t));
         AddEncByte(c, csOut);
   }
 
   return csOut;
}
 

/////////////////////////////////////////////////////////////////
 
CString Decrypt(const char *pIn, const char *pPass)
{
   CString csOut;
 
   CCXRIntDec sap((const BYTE *)pPass, strlen(pPass));
 
   int iLen = _tcslen(pIn);
 
   if (iLen > 2)
   {
         int iBufLen = strlen(pIn);
         if (iBufLen & 0x01)
         {
            cerr << "Illegal string length in Decrypt\n";
            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) csOut+=(char)bc;
         }
   }
 
   return csOut;
}
 
/////////////////////////////////////////////////////////////////
 
bool AddDecode(const CString & csPassword, CStdioFile &out)
{
   out.WriteString(_T("\n\n/////////////////////////////////////////////////////////////\n"));
   out.WriteString(_T("// CXR-generated decoder follows\n\n"));
   out.WriteString(_T("#include <algorithm>\n"));
   out.WriteString(_T("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.WriteString(EscapeCString(csPassword));
 
   out.WriteString(_T("\";\n"));
   CString t;
   t.Format("const int __iCXRDecBase1 = %d;\nconst int __iCXRDecBase2 = %d;\n\n", basechar1, basechar2);
   out.WriteString(t);
                                         
   // the high-level decoding function
const char *pDec1 =
"CString __CXRDecrypt(const char *pIn)\n"\
"{\n"\
"   CString x;char b[3];b[2]=0;\n"\
"   CXRD sap((const BYTE*)__pCXRPassword, strlen(__pCXRPassword));\n"\
"   int iLen = strlen(pIn);\n"\
"   if (iLen > 2)\n"\
"   {\n"\
"         int ibl=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) x+=ch;\n"\
"         }\n"\
"   }\n"\
"   return x;\n"\
"}\n";

   // the stream cipher
   const char *pStr1 =
"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<lm)mk=(mk<<1)+1;do{*rs=c[*rs]+uk[(*kp)++];if(*kp>=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.WriteString(pStr1);
   out.WriteString(pDec1);
 
   return true;
}
 
/////////////////////////////////////////////////////////////////
 
CString TranslateCString(const CString &csIn)
{
   // translate C-style string escapes as documented in K&R 2nd, A2.5.2
 
   CString csOut;
 
   for (int i=0;i<csIn.GetLength(); i++)
   {
         int c = csIn.GetAt(i);
         switch (c)
         {
         default:
            // normal text
            csOut+=static_cast<char>(c);
            break;
            // c-style escape
         case _T('\\'):
            if (i < csIn.GetLength() - 1)
            {
                  c = csIn.GetAt(i + 1);
                  switch (c)
                  {
                  case _T('n'):
                     csOut+=_T('\n');
                     break;
                  case _T('t'):
                     csOut+=_T('\t');
                     break;
                  case _T('v'):
                     csOut+=_T('\v');
                     break;
                  case _T('b'):
                     csOut+=_T('\b');
                     break;
                  case _T('r'):
                     csOut+=_T('\r');
                     break;
                  case _T('f'):
                     csOut+=_T('\f');
                     break;
                  case _T('a'):
                     csOut+=_T('\a');
                     break;
                  case _T('\\'):
                     csOut+=_T('\\');
                     break;
                  case _T('?'):
                     csOut+=_T('?');
                     break;
                  case _T('\''):
                     csOut+=_T('\'');
                     break;
                  case _T('\"'):
                     csOut+=_T('\"');
                     break;
                  case _T('0'):
                  case _T('1'):
                  case _T('2'):
                  case _T('3'):
                  case _T('4'):
                  case _T('5'):
                  case _T('6'):
                  case _T('7'):
                     {
                           // expand octal
                           int iConsumed = 0;
                           if (!ExpandOctal(csIn.Mid(i), csOut, iConsumed))
                           {
                              cerr << _T("Invalid octal sequence: ") << _T('\"') << (LPCTSTR)csIn << _T('\"') << endl;
                              csOut = csIn;
                              break;
                           }
 
                           i+=iConsumed - 1;
                     }
                     break;
                  case _T('x'):
                     {
                           // expand hex
                           int iConsumed = 0;
                           if (!ExpandHex(csIn.Mid(i), csOut, iConsumed))
                           {
                              cerr << _T("Invalid hex sequence: ") << _T('\"') << (LPCTSTR)csIn << _T('\"') << endl;
                              csOut = csIn;
                              break;
                           }
 
                           i+=iConsumed - 1;
 
                     }
                     break;
                  }
 
                  i++;
                  continue;
            }
            else
            {
                  cerr << _T("Invalid escape sequence: ") << _T('\"') << (LPCTSTR)csIn << _T('\"') << endl;
                  csOut = csIn;
                  break;
            }
            break;
         }
   }
 
   return csOut;
}
 
/////////////////////////////////////////////////////////////////
 
bool ExpandOctal(const CString &csIn, CString &csOut, int &iConsumed)
{
   // staring with the escape, we need at least one more char
   if (csIn.GetLength() < 2)
   {
         return false;
   }
 
   if (csIn.GetAt(0) != _T('\\'))
   {
         return false;
   }
 
   int iStart = 1;
   int iCur = iStart;
 
   CString digits;
   int c = csIn.GetAt(iCur);
   while ((c >= _T('0')) && (c <= _T('7')))
   {
         digits+=static_cast<char>(c);
 
         // an escape can't hold more that 3 octal digits (K&R 2nd A2.5.2)
         if (iCur == 3)
         {
            break;
         }
           
         iCur++;
         c = csIn.GetAt(iCur);
   }
 
   char *end;
   int octval = (char)_tcstol(digits, &end, 8);
 
   iConsumed = digits.GetLength();
 
   csOut+=static_cast<char>(octval);
 
   return true;
}
 
/////////////////////////////////////////////////////////////////
 
bool ExpandHex(const CString &csIn, CString &csOut, int &iConsumed)
{
   // staring with the escape and the 'x', we need at least one more char
   if (csIn.GetLength() < 3)
   {
         return false;
   }
 
   if ((csIn.GetAt(0) != _T('\\')) || (csIn.GetAt(1) != _T('x')))
   {
         return false;
   }
 
   int iStart = 2;
   int iCur = iStart;
 
   CString digits;
   int c = csIn.GetAt(iCur);
   while (_istxdigit(c))
   {
         digits+=static_cast<char>(c);
 
         iCur++;
         c = csIn.GetAt(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)_tcstol(digits, &end, 16);
 
   iConsumed = digits.GetLength();
 
   iConsumed++; // count the "x"
 
   csOut+=static_cast<char>(hex);
 
   return true;
}
 
/////////////////////////////////////////////////////////////////
 
CString EscapeCString(const char *pIn)
{
   CString csOut;
 
   int iLen = _tcslen(pIn);
 
   for (int i=0;i<iLen;i++)
   {
         csOut+=pIn[i];
         // double all "\" chars
         if (pIn[i] == _T('\\'))
         {
            csOut+=_T('\\');
         }
   }
 
   return csOut;
}
 
/////////////////////////////////////////////////////////////////
</code>
 
-- modified at 16:57 Thursday 2nd March, 2006
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