cencryptionfgetsvigenere

Cannot print key-stream when using fgets to get key from user compared to hard coding inputs


I'm experimenting with fgets instead of hardcoding an array with a program that takes a plaintext and a key input and returns the key-stream and encrypted text. Using fgets to scan the key from the user somehow changes the output to not print the key stream, but only the key itself. The only thing I have changed is instead of hardcoding the key string with an array, i have the user enter the key with fgets.

Hard coded (snippet):

#include <stdio.h>
#include <string.h>

int main(void)
{
   char msg[] = "THECRAZYPROGRAMMER";
   char key[] = "HELLO";
   int msgLen = strlen(msg), keyLen = strlen(key), i, j;
   char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

   //generating new key
   for(i = 0, j = 0; i < msgLen; ++i, ++j){
      if(j == keyLen)
         j = 0;

    newKey[i] = key[j];
   }

   newKey[i] = '\0';
   printf("Original Message: %s", msg);
   printf("\nKey: %s", key);
   printf("\nNew Generated Key: %s", newKey);
}

fgets (snippet):

#include <stdio.h>
#include <string.h>
int main(void)
{
   char msg[512];
   char key[512];
   int msgLen = strlen(msg), keyLen = strlen(key), i, j;
   char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

   fgets(msg, 512, stdin);
   fgets(key, 512, stdin);

   //generating new key
   for(i = 0, j = 0; i < msgLen; ++i, ++j){
      if(j == keyLen)
         j = 0;

    newKey[i] = key[j];
   }

   newKey[i] = '\0';
   printf("Original Message: %s", msg);
   printf("\nKey: %s", key);
   printf("\nNew Generated Key: %s", newKey);
}

Solution

  • Check out the code below which makes a few edits to your fgets code.

    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
       char msg[512];
       char key[512];
    
       fgets(msg, 512, stdin);
       fgets(key, 512, stdin);
    
      int msgLen = strlen(msg), keyLen = strlen(key), i, j;
       char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
    
       //generating new key
       for(i = 0, j = 0; i < msgLen; ++i, ++j){
          if(j == keyLen - 1)
             j = 0;
    
        newKey[i] = key[j];
       }
    
       newKey[i] = '\0';
       printf("Original Message: %s", msg);
       printf("\nKey: %s", key);
       printf("\nNew Generated Key: %s", newKey);
    }
    

    I changed two things. First, I moved the code where you get msgLen and keyLen to after you call fgets so you aren't taking strlen of uninitialized memory. Second, I corrected an off-by-one error you have in the line if (j == keylen - 1) so that the newline character given to fgets is not included in your output.