Jump to content

Per-byte file encryption

- - - - -

  • Please log in to reply
No replies to this topic

#1
DarkLordofthePenguins

DarkLordofthePenguins

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 409 posts
This program performs a per-byte encryption of a file by swapping the lower 4 bits with the upper 4 bits of each byte. It's a relatively unsophisticated algorithm, not very effective at deterring cybercrime, but still useful if you want to, say, hide a porno movie from your parents. Mostly I just wrote this to get a taste for encryption. The cypher function the program implements is its own inverse, so applying it to a file that has been encrypted will decrypt it.



/*

 * Date: Dec 31 2011

 *

 * Encrypts a file by swapping the lower 4 bits with the

 * upper 4 bits of each character, then writing back to

 * the file.  This algorithm reverses changes it has made

 * when applied twice.

 */


#include <stdio.h>

#include <errno.h>

#include <string.h>

#include <unistd.h>

#include <fcntl.h>


int main( int argc, char **argv ){

	char highbits; // Higher 4 bits of character

	char lowbits;  // Lower 4 bits of character

	int fd;

	if( (fd = open( argv[1], O_RDWR )) == -1 ){

		// If file does not exist

		printf( "%s: %s\n", argv[1], strerror( ENOENT ) );

		return 1;

	}

	off_t length = lseek( fd, 0, SEEK_END ); // Get file length

	lseek( fd, 0, SEEK_SET );

	char buf[1];        // Buffer for character read

	char chars[length]; // Buffer for the entire file

	for( long long i = 0; i < length; i++ ){

		read( fd, buf, 1 );

		highbits = buf[0] >> 4;

		lowbits = buf[0] << 4;

		/*

		 * Shifting the bits results in a 32-bit number,

		 * which is sign-extended.  If the highest bit in the

		 * shifted value is 1 (i.e. if the hex digit is > 7)

		 * then the number is sign-extended with 1s, changing

		 * its value.  For this reason, it is necessary to

		 * mask out all but the lowest 8 bits of lowbits and

		 * all but the lowest 4 bits of highbits.

		 */

		chars[i] = (highbits & 0xf) + (lowbits & 0xff);

	}

	lseek( fd, 0, SEEK_SET );

	write( fd, chars, length ); // Write swapped bytes

	close( fd );

	return 0;

}


This only works on the POSIX API. I have not gotten around to writing a platform-independent version.
Programming is a journey, not a destination.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users