Originally Posted by
dwks
It's quite simple.
Use the code in the first loop in the second one.
Code:
/* decrypt loop */
for ( i = 0; encry[i] != '\0'; i++ )
{
plain[i] = encry[i] ^ key[keypos];
keypos++;
if ( keypos > keylen )
keypos = 0;
}
Well, that's actually the first thing I tried, but I get garbage for output. I thought it would be the logical choice.. Here's the code, and whenever I try to decrypt I get garbage.. There has to be something wrong with the loops.. Saturday evening and I'm trying to get a XOR program to work.. Well, at least I'm committed :-)
Code:
#include <stdio.h>
#include <string.h>
main()
{
char plain[51];
char encry[51];
char key[5] = "ABCD";
int i, keylen = 0, keypos = 0;
printf("Enter text: ");
scanf("%[^\n]", plain);
printf("You entered: %s\n", plain);
keylen = strlen(key);
printf("Encryption key is: %s\n", key);
printf("Length of key is: %d\n", keylen);
for ( i = 0; plain[i] != '\0'; i++ )
{
encry[i] = plain[i] ^ key[keypos];
keypos++;
if ( keypos > keylen )
keypos = 0;
}
puts("Encrypted text: ");
puts(encry);
for ( i = 0; encry[i] != '\0'; i++ ) {
plain[i] = encry[i] ^ key[keypos];
keypos++;
if ( keypos > keylen )
keypos = 0;
}
puts("Decrypted: ");
puts(plain);
fflush(stdin);
getchar();
}