Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Per-byte file encryption

encryption

  • Please log in to reply
No replies to this topic

#1 DarkLordCthulhu

DarkLordCthulhu

    CC Devotee

  • Senior Member
  • PipPipPipPipPipPip
  • 422 posts
  • Location:The bash shell
  • Programming Language:C, JavaScript, Bash, Others
  • Learning:Ruby, Others

Posted 01 January 2012 - 01:49 PM

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.
  • 0
Programming is a journey, not a destination.





Also tagged with one or more of these keywords: encryption

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download