Solved

C++ XOR hashing a CString with printable characters

Posted on 2011-02-15
10
2,033 Views
Last Modified: 2012-05-11
I need to perform a simple XOR "encryption" to hide a password from plain text.

I am unsure how to modify the attached snippet such that the result contains only printable characters (ie. that can be copied/pasted and entered manually)

thanks!
CString XOREncrypt(CString a_sValue, CString a_sKey)
{

	CString sRet=_T("");
	
	sRet=a_sValue;

	int i = 0;
	int j = a_sValue.GetLength();
	int k = 0;
	int l = a_sKey.GetLength();
	while (i < j)
	{	
		sRet.SetAt(i, sRet.GetAt(i) ^ a_sKey.GetAt(k));
		i++;
		k++;
		if (k >= l)
			k = 0;
	}


    return sRet;
}

Open in new window

0
Comment
Question by:PMH4514
  • 5
  • 5
10 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 34901133
You could use the old UUencode or just try basE91: "basE91 is an advanced method for encoding binary data as ASCII characters. It is similar to UUencode or base64, but is more efficient." See basE91 encoding. This link has "Source code package (C, Java, PHP, 8086 assembly, AWK)"
0
 

Author Comment

by:PMH4514
ID: 34902364
Actually I'm finding a Visual Basic example that uses Asc() and Hex() to do an ascii to hex conversion to accomplish the same task. The XOR encryption does the XOR and then hex() to get a printable result, and then to decrypt uses asc() to convert the next to ASCII.

what would be the equivalent for me to perform those ASCII to hex conversions on an MFC CString?
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34902574
I don't have MFC, so I looked up Need help converting CString to hex for you. It has various code snippets that should help. Below is one snippet to try out.
LPSTR p = m_strMessage.GetBuffer(1);
int len = m_strMessage.GetLength();

for (int n = 0 ; n < len ; n++) {
	TCHAR tmp[4] = { 0 };
	_stprintf(tmp, TEXT("%02x "), p[n]);
	m_strOutput += tmp;
}
m_strMessage.ReleaseBuffer();

Open in new window

0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:PMH4514
ID: 34902820
Nice I found myself reading the same link!
0
 
LVL 32

Expert Comment

by:phoffric
ID: 34902843
!!
0
 

Author Comment

by:PMH4514
ID: 34902947
I'm not finding any details anywhere on how to then convert it back.

for reference attached is the VB code I am trying to reproduce in C++.. It doesn't have to use MFC actually.


Public Function XORDecryption(CodeKey As String, DataIn As String) As String
    
    Dim lonDataPtr As Long
    Dim strDataOut As String
    Dim intXOrValue1 As Integer
    Dim intXOrValue2 As Integer
    

    For lonDataPtr = 1 To (Len(DataIn) / 2)
        'The first value to be XOr-ed comes from the data to be encrypted
        intXOrValue1 = Val("&H" & (Mid$(DataIn, (2 * lonDataPtr) - 1, 2)))
        'The second value comes from the code key
        intXOrValue2 = Asc(Mid$(CodeKey, ((lonDataPtr Mod Len(CodeKey)) + 1), 1))
        
        strDataOut = strDataOut + Chr(intXOrValue1 Xor intXOrValue2)
    Next lonDataPtr
   XORDecryption = strDataOut
End Function


Public Function XOREncryption(CodeKey As String, DataIn As String) As String
    
    Dim lonDataPtr As Long
    Dim strDataOut As String
    Dim temp As Integer
    Dim tempstring As String
    Dim intXOrValue1 As Integer
    Dim intXOrValue2 As Integer
    

    For lonDataPtr = 1 To Len(DataIn)
        'The first value to be XOr-ed comes from the data to be encrypted
        intXOrValue1 = Asc(Mid$(DataIn, lonDataPtr, 1))
        'The second value comes from the code key
        intXOrValue2 = Asc(Mid$(CodeKey, ((lonDataPtr Mod Len(CodeKey)) + 1), 1))
        
        temp = (intXOrValue1 Xor intXOrValue2)
        tempstring = Hex(temp)
        If Len(tempstring) = 1 Then tempstring = "0" & tempstring
        
        strDataOut = strDataOut + tempstring
    Next lonDataPtr
   XOREncryption = strDataOut
End Function

Open in new window

0
 
LVL 32

Accepted Solution

by:
phoffric earned 125 total points
ID: 34903360
Here is a program for you to check out.
#include <iostream>
#include <string>
using namespace std;

string XOREncrypt(string a_sValue, string a_sKey)  
{  
        string sRet;
        sRet=a_sValue;  

        int idxVal = 0;
        int size_svalue = a_sValue.size();  
        int idxKey = 0;  
        int size_skey = a_sKey.size();  

        while (idxVal < size_svalue)
        {         
           sRet[idxVal] = sRet.at(idxVal) ^ a_sKey.at(idxKey);
                idxVal++;  
                idxKey++;  
                if (idxKey >= size_skey)  
                        idxKey = 0;  
        }
    return sRet;  
}

#include <stdio.h>

void convertToASCIIhex( string & output, string & input ) {
   char asciiHex[3];
   unsigned char num;
   for( size_t i=0; i < input.size(); ++i ) {
      num = input[i];
      sprintf( asciiHex, "%2x", num );
      output += asciiHex;
   }
}


void convertHexToBinary( string & output, string & input ) {
   char asciiHex[3];
   unsigned char num;
   for( size_t i=0; i < input.size(); ) {
      asciiHex[0] = input[i++];
      asciiHex[1] = input[i++];
      asciiHex[2] = '\0';
      num = strtoul( asciiHex, NULL, 16 );
      output += num;
   }
}


int main() {
   string plainText = "Plain Text";
   string key = "\xD3\x42\x2A\x99";
   string encrypted = XOREncrypt( plainText, key );

   string hexRepr;
   convertToASCIIhex( hexRepr, encrypted );

   string binary;
   convertHexToBinary( binary, hexRepr );

   string decrypted = XOREncrypt( binary, key );
   cout << decrypted << endl;
}

Open in new window

0
 

Author Comment

by:PMH4514
ID: 34906628
very nice I understand. Thank you kindly for your guidance.

0
 
LVL 32

Expert Comment

by:phoffric
ID: 34910502
You are very welcome. Glad it worked out.

Where there's a "%2x", maybe it would be better to make it a "%02x". And for functions whose arguments are input, it is better to add the "const" qualifier.

0
 

Author Comment

by:PMH4514
ID: 34910698
Thank you
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question