Szabó Andor
Szabó Andor

Reputation: 11

Vigenere code in C crashes with a multi-character key

If I use one character long key everything works fine, but if i use longer key the program crashes. For this input: '2A282E2A282E' should output this: 'aaaaaa'

#include <stdio.h>
#define KL 3
main()
{
    unsigned char ch;
    FILE *fpIn, *fpOut;
    int i;
    unsigned char key[KL] = {0x4B, 0x49, 0x4F};

    fpIn = fopen("ctext.txt", "r");
    fpOut = fopen("dtext.txt", "w");

    i=0;
    while(fscanf(fpIn, "%02X", &ch) != EOF)
    {

        fprintf(fpOut, "%c", ch ^ key[i % KL]); 
        i++;

    }

    fclose(fpIn);
    fclose(fpOut);
    return(0) ;
}

Upvotes: 1

Views: 90

Answers (2)

Szab&#243; Andor
Szab&#243; Andor

Reputation: 11

I had to read in with '%c' not with '%02X' and convert characters to hex value. The final code solved:

#include <stdio.h>
#define KL 3

int ctox(char c)               //this is the convertin part
{
if(c>='0'&&c<='9') return c-'0';
return 10+c-'A';
}

main()
{
    unsigned char ch, c1, c2;
    FILE *fpIn, *fpOut;
    int i=0;
    unsigned char key[KL] = {0x4B, 0x49, 0x4F} ;

    fpIn = fopen("ctext.txt", "r");
    fpOut = fopen("dtext.txt", "w");



    while(fscanf(fpIn, "%c%c", &c1, &c2) != EOF)    //the read in part corrected
    {
    ch = 16*ctox(c1) + ctox(c2);

    printf("HEX %c%c ", c1, c2); 
    printf("DEC %3d ", ch);       // this three line just for examination
    printf("i %d\n", i);

    fprintf(fpOut, "%c", ch^key[i % KL ] ) ;
    i++;

    }

    fclose(fpIn);
    fclose(fpOut);
    return(0) ;
}

Thanks for all of you.

Upvotes: 0

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27652

When I compile your program with GCC, I get the warning "format '%X' expects argument of type 'unsigned int *', but argument 3 has type 'unsigned char *'". That is an error that can cause a crash, since a char is typically one byte wide, while an int is typically four bytes. fscanf will try to put four bytes of data in your single-byte space, happily overwriting any data that comes after.

As BLUEPIXY suggested in a comment, you can just replace your unsigned char ch with unsigned ch.

Other than that, it works when I try it, and I see no other obvious problems, except that you should check the return values from fopen.

Upvotes: 1

Related Questions