Solved

C++ XOR hashing a CString with printable characters

Posted on 2011-02-15
10
1,980 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
 

Author Comment

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

Expert Comment

by:phoffric
ID: 34902843
!!
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

744 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now