/*
* 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.


Sign In
Create Account


Back to top









