This is a simple Caesar cipher implementation in C.
I take a pin, make a key from it, take a message, shift the ASCII value w.r.t the key, and output the hex value of each character in hex.
Upon using (as it appeared to me) any key , for the some (not all) messages results in the printing of an extra character upon decoding.
Weird Char appearing :
Message : "hexa !
"
Pin : 454545
& Key : 23
Ciphertext : (in hexa) " 51 4e 61 4a 9 a fffffff3 4e -6f
" (-6f is simply used to terminate input)
Text given when decoding :
hexa !
e
Other keys generate other weird chars , like ' +
', for example. The weird char always appears on the next line.
The entire code is ~ 100 lines, so I wont paste it here, but it's available on GitHub . Don't use the windows .exe in this repo, it is of the older version, I'm trying to fix this issue before releasing this version.
The code where the issue is likely appearing is the encrypt() and decrypt() functions :
void encrypt() {
char msg[3001], ch;
int i,key, en[3001], count = 0;
printf("\n");
key = pin();
getchar();
printf("\nType Message - \n\n");
fgets(msg,sizeof(msg),stdin);
for (i=0; msg[i] != '\0'; i++) {
ch=msg[i];
int d = (ch - key);
en[i] = d;
count++;
}
printf("\nEncrypted message -\n\n");
for (i=0; i <= count; i++)
printf("%x ", en[i]);
printf("-6f");
}
void decrypt() {
char msg[3001], ch;
int i,key, en[3001],d;
printf("\n");
key = pin();
printf("\nEnter encrypted message -\n\n");
getchar();
for (i=0; i <= 3001; i++) {
scanf("%x",&d);
if (d == -111) {
msg[i] = '\0';
break;
} else {
ch = d + key;
msg[i] = ch;
}
}
printf("\nDecrypted message -\n\n");
puts(msg);
}
In your second for
loop:
for(i = 0; i <= count; i++)
You are running off the end of the array (array indices start at zero, not one).
Change it to:
for(i = 0; i < count; i++)
Always put your variable declarations each on their own line.
int a, b, c = 0; // only one variable is initialized.
char *src = 0, c = 0; // c is of type char, not char*
fgets
includes the trailing newline. If you don't want it, you have to strip it off.
int len = strlen(msg);
if(len > 0 && msg[len - 1] == '\n')
msg[len - 1] = '\0';