Search code examples
cxor

How to XOR two byte streams in C?


I've been reading through SO for the past couple of days trying to figure this out, I am stumped. I want to read in two 32 bit byte arrays (from stdin, input will be hex) and xor them, then print the result.

So far I've tried using scanf, fgets, and gets. My thought was to read the large hex numbers into a char buffer and perform the xor in a for loop until I hit an EOL (with fgets) or a null terminator. So far my output is not even close. I tried lots of variations, but I will only post my latest fail below. The challenge I've been trying to complete is: http://cryptopals.com/sets/1/challenges/2/

I am trying it in C because I'm really trying to learn C, but I'm really getting frustrated with none of these attempts working.

#include <stdio.h> 
#include <math.h>

int main()
{
    char buff1[100];
    char buff2[100];
    char buff3[100];
    int size = sizeof(buff1);

    puts("Enter value\n");
    fgets(buff1, size, stdin);
    puts(buff1);
    puts("Enter value\n");
    fgets(buff2, size, stdin);
    puts(buff2);

    for (int i = 0; i != '\n'; i++) {
        buff3[i] = buff2[i] ^ buff1[i];
        printf("%x", buff3[i]);
    }

    return 0;
}

Solution

  • When using sizeof() it should be used with types, not data. For instance if you want space for 100 chars, you need to find the sizeof(char) and then multiply by 100 to find out how many bytes you need and that goes into the buffer. A char is usually a byte so expect 100 bytes. fgets() will work but I prefer to use this

    int getchar()
    

    Just stop when the the user enters a newline/terminator character. Since you don't know how many characters will come in from stdin, you need to dynamically increase the size of your buffer or it will overflow. For the purposes of this question you can just make it a very big array, check to see if its about to overflow and then terminate the program. So to recap the steps.

    1.) Create a big array

    2.) While loop over getchar() and stop when the output is the terminator, take note of how many chars you read.

    3.) Since both buffers are guaranteed to have equal chars make your final array equal to that many chars in size.

    4.) For loop over getchar() and as the chars come out, xor them with the first array and put the result into the final array. You should try doing this with 1 array afterwards to get some more C practice.

    Good luck!

    EDIT:

    fgets() can be used but depending on the implementation it is useful to know how many chars have been read in.