Home > Software design >  I made a simple encryption and decryption program in c and is not working as expected
I made a simple encryption and decryption program in c and is not working as expected

Time:02-12

// Write a encryption program which encrypts the string by adding 1 to its ASCII value.
#include <stdio.h>
#include <string.h>

void encrypt(char *str)
{
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr   1; // This will add integer 1 to the value of character stored in ptr i.e. its ASCII value.
        *ptr  ;
    }
}

void decrypt(char *str){
    char *ptr = str;
    while (*ptr != '\0')
    {
        *ptr = *ptr -1; // This will subtract 1 from the ASCII value and restore the original string.
        *ptr  ;
    }
    
}
int main()
{
    char message[] = "We are what we choose to be!"; 
    encrypt(message);
    printf("The encrypted message is %s\n\n", message);

    char pwd[20] = "omkaushik";
    char input[20];
    printf("Enter password to decrypt the message\n");
    gets(input);

    int result = strcmp(pwd, input);
   while (result != 0)
   {
     printf("The password entered is wrong\n");
     printf("Enter the password again\n");
     gets(input);
     int result = strcmp(pwd, input);
   }
   decrypt(message);
        printf("The password entered is accepted....\n");
        printf("%s",message);

    return 0;
}

In this program when I enter the correct password at the start, it decrypts the message successfully but when I enter a wrong password and later try to enter the correct password, it doesn't exit the loop.

CodePudding user response:

First gets is deprecated and unsafe and should never be used. Second, and this is your question, inside your loop you declare a local variable instead of updating the one in the outer scope

 int result = strcmp(pwd, input);

replace it with

 result = strcmp(pwd, input);

Will update the test inside the loop

  • Related