Simple XOR encryption in C

Dont’ use XOR encryption only when you encrypt data. It’s weak. Combine it with other methods/algorithms. You can for ex. xor a string and then encrypt it with AES 256.

Definitions and Includes

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
int XOR(WCHAR **dest, const WCHAR *src, int slen, const WCHAR *key, int klen);

XOR method

int XOR(WCHAR **dest, const WCHAR *src, int slen, const WCHAR *key, int klen){
	int kIndex = 0;
 
	*dest = (WCHAR*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, slen * sizeof(WCHAR));
	if (*dest == NULL) return 0;
 
	for (int i = 0; i < slen - 1; i++){
		*(*dest + i) = src[i] ^ key[kIndex++];
		if (kIndex == klen - 1) kIndex = 0;
	}
 
	*(*dest + (slen - 1)) = '\0';
 
	return slen;
}

Usage

int main(void){
	WCHAR *xored;
	const WCHAR plain[] = L"maldevel\0";
	const WCHAR xorkey[] = L"gt32fvbn678jkfdcvb34tgbn\0";
	int xoredChars = 0;
 
	wprintf(L"plain text: %s\n", plain);
	xoredChars = XOR(&xored, plain, wcslen(plain) + 1, xorkey, wcslen(xorkey) + 1);
 
	if (xoredChars > 0)
		wprintf(L"xor result: %s\n", xored);
 
	if (xored)HeapFree(GetProcessHeap(), 0, xored);
 
	return EXIT_SUCCESS;
}
Categories: C Tags: , , ,
%d bloggers like this: