26332 total geeks with 3498 solutions
Recent challengers:
  • krc bonus 11 - 08:00AM
  • KNL reverser 7 - 07:52PM
  • krc level 2 - 11:06AM
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jun 30
June Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Nuke plants to keep
PDP-11 UNTIL 2050!
COLD BALLS OF FLAME
light up
International Space
Station
Google erases G8
venue from Earth:
Microsoft doesn"t
Chinese hackers
launch PRISM scare
campaign
Spear phish your
boss to win more
security cash
Six nations ask
Google for answers
on Glass privacy
Huawei muses on
Nokia"s future
House bill: "Hey
NASA, that asteroid
retrieval plan?
Fuggedaboutit"
Foreign keys,
JavaScript support
on deck for MySQL
Cluster update
Icahn doubles down
on Dell offer with
$14 per share
buyback scheme
Slashdot
Altering Text In
eBooks To Track
Pirates
NVIDIA To License
Its GPU Tech
MySQL Man Pages
Silently Relicensed
Away From GPL
Verizon Accused of
Intentionally
Slowing Netflix
Video Streaming
Oculus Rift Raises
Another $16 Million
KWin Maintainer:
Fanboys and Trolls
Are the Cancer
Killing Free
Software
Google Files First
Amendment Challenge
Against FISA Gag
Order
Microsoft To Start
Dumping Surface RT
To Schools For $199
With an Eye Toward
Disaster, NYC
Debuts Solar
Charging Stations
2013 U.S. Wireless
Network Tests:
AT&T Fastest,
Verizon Most
Reliable
Article viewer

Multi-Byte XOR Encoding : Part 2 of a series



Written by:typedeaF
Published by:Nightscript
Published on:2004-07-16 15:34:42
Topic:C
Search OSI about C.More articles by typedeaF.
 viewed 17821 times send this article printer friendly

Digg this!
    Rate this article :
Multi-Byte XOR Encoder/Decoder (AKA 8-bit XOR Cipher++) written in C.
Following in the "run it once to encode, run it again to decode" footsteps. Multi-Byte XOR digs a little deeper in C and brings us a little closer to making something that your colleagues will drool over.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

main(int argc, char *argv[])
{
    FILE *input, *output = stdout;
    char *prog = argv[0];
    char ch;
    unsigned masklen, j;
    unsigned long filelen, i;
    int mask[]= {'t','e','s','t', '1',0,0,0, 0,'2',0,0, 0,0,'3',0,};
        
    if(argc == 1 || argc == 2)
    {
        fprintf(stderr, "ERROR: %s requires a Source and Destination file.\n", prog);
        exit(1);
    }
    else
    {
        if((input = fopen(*++argv, "rb")) == NULL)
        {
            fprintf(stderr, "ERROR: %s can not open file %s.\n", prog, *argv);
            exit(1);
        }
        if((output = fopen(*++argv, "ab")) == NULL)
        {
            fprintf(stderr, "ERROR: %s can not create file %s.\n", prog, *argv);
            exit(2);
        }
    }

    fprintf(stdout, "Multi-Byte XOR Encoder/Decoder by typedeaF # www.osix.net\n\n");
    
    masklen = sizeof(mask)/sizeof(mask[0]);

    fseek(input, 0L, SEEK_END);
    filelen = ftell(input);
    fseek(input, 0L, SEEK_SET);

    fprintf(stdout, "Using mask: \"");

    for(i = 0L; i < masklen; i++)
    {
        if(mask[i] == 0)
            fprintf(stdout, "-");
        else
            fprintf(stdout, "%c", mask[i]);
    }
    fprintf(stdout, "\"\n");
 
    for(i = 0L, j = 0; i < filelen; i++, j++)
    {
        ch = fgetc(input);
        if(j == masklen)
            j = 0;
        if(mask[j] == 0)
            fputc(ch, output);
        else
            fputc((mask[j]^ch)&0xFF, output);
    }
    
    fclose(input);
    fclose(output);

    return 0;
}


OK, so half the work here is just opening files and printing output. The real skinny of this program starts and ends in the simple little FOR loop. But we will take it from the top anyway. We have an array of ints called 'mask'. For this program I wanted a set size mask -- 16 bytes in this example, hard coded.

The mask is what we are going to XOR our data with. I choose to enclose the chars in single quotes to make it easier to comprehend what the mask is. After opening the input and output streams the length of the mask is determined. This makes the program at least somewhat user friendly so that changes can be made to the mask without other parts of the program being affected. After mask length is determined we quickly determine the length of the file too by seeking to its end and reporting its offset. Next we have a simple routine that displays to stdout what the mask actually looks like. This is useful for debugging and such. You will notice that 0's are replaced with '-'s. This is no mistake. In this program, we are telling the 16 byte mask that even though it's 16 bytes, we don't want to XOR EVERY char.

This is good for partially encoding data. It leaves some data untouched to the naked eyes. This, imho, makes guessing the mask harder because the length is stretched out and repetition is less common. Unfortunately it makes guessing the cipher text easier than if the entire 16 bytes were XORed. Anyway, '-' means THAT byte will not be XORed against the data. Now to the actual encoding. A for loop is used that cycles through until the end of file. One byte of data at a time is gotten and XORed linearly against the mask. When the end of the mask is reached -- determined by j, the index of the mask is reset.

ex.

This is the real data in the plain text file. (plain text)
test1----2-----3-test1----2----3-test1----2-- (mask)
XXXXXis tXe reaX XXXXXin tXe plXiXXXXXt fiXe. (results (X is just symbolic here))


The byte of data is read in and IF the mask index isnt the value zero/null, then the data is xored againt the mask and placed in the output stream. Since both mask[] and ch are int types, and we are reading chars, we AND mask the resultant integer with all ones so that the extra data is 0s. Thus it resembles a single byte char instead of a multi-byte int. Just like the Rot13 function, XOR can be used to encode and decode the data. So run it again on the output file and you get the original data.

typedeaF

Did you like this article? There are hundreds more.

Comments:
niki
2006-01-01 03:50:51
the check for "if(mask[j] == 0)" is not required,
since "((mask[j]^ch)) will have the same value as "ch" in the case that mask[j] == 0.
Anonymous
2008-09-23 14:16:17
jxHkj3uJ2i3I7/3iGkU22Q==
Anonymous
2009-11-08 17:03:29
Quote Anon:
can u tell me in details about what is cookie?
A cookie is how a site recognizes your browser from other browsers; it's how when you check the remember me checkbox, you don't have to login again. Articulos Gratis
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
amisauv
Creating a Lexical Analyzer in C on Tue 9th Dec 11am
#include<stdio.h> #include<string.h> #include<conio.h> #include<ctype.h> /*************************************** ************************* Functions prototype. **************************************** *************************/ void Open_File(
amisauv
Controling digital circuit through computer on Tue 9th Dec 10am
this code access the lpt port.here only 4 of the total 8 pins are used but can be modified for full 8 pins.it has a complete GUI with mouse & keyboard interactive control panel.works well in win98, but not in winxp. #include<stdio.h> #include<conio.
amisauv
/* Computerised Electrical Equipment Control */ /* PC BASED DEVICE CONTROLLER * on Tue 9th Dec 10am
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { void tone(void); int p=0x0378; char ex={"Created By Mrc"}; int j; char ex1={"For Further Details & Improvements"}; int k; char ex2={"Contact : E-mail : anbudan
amisauv
Calendar Program on Tue 9th Dec 10am
This program prints Weekdays of specified date. It even prints calendar of a given year too. /*Ccalendar library*/ #include<stdio.h> #include<string.h> #include<conio.h> int getNumberOfDays(int month,int year) { switch(month) { case
amisauv
Calculator: on Tue 9th Dec 10am
#include"graphics.h" #include"dos.h" #include"stdio.h" #include"math.h" union REGS i,o; char text={ "7","8","9","*","4","5","6","/","1","2", "3","+","0","00",".","-","M","M+", "M-","+/-","MR","MC","x^2","sr","OFF","A C","CE","="}; int s=0,k=0,pass
amisauv
INFECTED CODES WRITTEN IN C\C++ on Tue 9th Dec 10am
This is a simple code that changes system time and date. It is written using c/c++ but can be easily converted to java. #include "stdio.h" #include "process.h" #include "dos.h" int main(void) { struct date new_date; struct date old_date; s
amisauv
A C programme which can print the file name it is kept in on Tue 9th Dec 9am
#include<stdio.h> main(){ printf(”the source file name is %s\n”,__FILE__); } actually __FILE__ is a macro which stands for the file name the programme is kept in and the compiler does the rest .. for you ..
amisauv
BOOTSECTOR EDITOR: on Tue 9th Dec 9am
Code : /*program to save the partion table of your hard disk for future use. it will save your partition table in a file partition.dat */ #include<stdio.h> #include<bios.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void main () {
amisauv
BLINKING STAR : on Tue 9th Dec 9am
#include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> void main() { int gdriver=DETECT,gmode; int i,x,y; initgraph(&gdriver,&gmode,"e: cgi"); while(!kbhit()) { x=random(640); y=random(480); setcolor
amisauv
// To print semicolons using C programming without using semicolons any where i on Tue 9th Dec 9am
// To print semicolons using C programming without using semicolons any where in the C code in program. // #include<stdio.h> #include<conio.h> void main() { char a; a=59; if(printf("%c",a)){} getch();

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
BSD sockets API by skrye

This is a test of your knowledge of the BSD socket interface
C Programming by keoki

This test is aimed at a C programmer that is at an intermediate level.


     
Your Ad Here
 
Copyright Open Source Institute, 2006