Simple XOR cipher (C)

From LiteratePrograms

Jump to: navigation, search

This is an implementation of Simple XOR cipher in C. The algorithm encrypts data by using bitwise XOR on the data stream and a key. Using the same key on the encrypted data regenerates the original.

This is not a particularly secure encryption. It is trivial to break.

Algorithm

<<xorcipher>>=
void xorcipher(const unsigned char *key, FILE *infp, FILE *outfp)
{
	int ch;
	const unsigned char *keyp=key;
	while((ch=getc(infp))>=0) {
		putc(ch^*keyp++, outfp);
		if(!*keyp) keyp=key;
	}
}

Main program

This program takes 2 file names as command-line arguments. The data in the input file (first argument) is encrypted and written to the output file (second argument). If the output file name is omitted, ".xor" is appended to the input file name and used as the output file name.

<<xorcipher.c>>=
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
void usage(const char *cmd)
{
	fprintf(stderr, "Usage: %s <in-file> [<out-file>]\n", cmd);
	exit(1);
}
xorcipher
int main(int argc, char *argv[])
{
	char *infname;
	char *outfname;
	const unsigned char *key;
	FILE *infp, *outfp;
	if(argc>1) infname=argv[1];
	else usage(argv[0]);
	if(!(infp=fopen(infname, "rb"))) {
		fprintf(stderr, "ERROR: fopen(%s)\n", argv[1]);
		exit(1);
	}
	if(argc>2) outfname=argv[2];
	else {
		if(!(outfname=malloc(strlen(infname)+5))) {
			fprintf(stderr, "ERROR: malloc failed\n");
			exit(1);
		}
		strcpy(outfname, argv[1]);
		strcat(outfname, ".xor");
	}
	if(!(outfp=fopen(outfname, "wb"))) {
		fprintf(stderr, "ERROR: fopen(%s)\n", outfname);
		exit(1);
	}
	key=(const unsigned char*)getpass("Please enter a key: ");
	xorcipher(key, infp, outfp);
	fclose(outfp);
	fclose(infp);
	if(argc<3) free(outfname);
	return 0;
}
Download code
Views