I've quite a few problems with a very small C program I've been writing. Looked through all the stack overflow articles I could find but haven't had much success. The program is suppose to use a very simple XOR "encryption" on a plain text string. Both input string and key are 6 chars long. I'm new to C and pointers. I think i'm failing to grasp some the fundamentals of the language.
#include <stdio.h>
#include <string.h>
#define LENGTH 7
#define KEY "secret"
char * encryptDecrypt(char *plaintext);
int main(int argc, char **argv)
{
if(argc > 1)
{
char *plainText = argv[1];
printf("Encrypting plaintext: %s (%i)\n", plainText, strlen(plainText));
char *cipherText = encryptDecrypt(plainText);
printf("Encrypted: %s (%i)\n", cipherText, strlen(cipherText));
char *decryptedText = encryptDecrypt(cipherText);
printf("Decrypted: %s (%i)\n", decryptedText, strlen(decryptedText));
}
return 0;
}
char * encryptDecrypt(char *text)
{
char result[LENGTH];
for (int i = 0; i < LENGTH-1; i++)
{
result[i] = (char)(text[i] ^ KEY[i]);
}
char *resultPtr = &result;
return resultPtr;
}
Running the program with arg "foobar" outputs:
Encrypting plaintext: foobar (6)
Encrypted: ╠╠╠╠╠╠╠╠T¨ (19)
Decrypted: ╠╠╠╠╠╠╠╠T¨ (19)
Problems:
- Printing the pointer to the result array is different when used in the encryptDecrypt function and after it has been returned
- Using XOR on the cipher text isn't reverting it back to the original plain text (although because whatever i'm printing is wrong, this part may be alright)
- The string length of the encrypted/decrypted text is 19 chars long? How is that possible if the original string was 6 chars?