[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

C++ XOR hashing a CString with printable characters

Posted on 2011-02-15
10
Medium Priority
?
2,136 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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 500 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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 viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

650 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