C program to encrypt and decrypt the string


In this example, you will learn about C program to encrypt and decrypt the string using a simple key at both sides.

C program to encrypt and decrypt the string

For encryption and decryption, we have used 3 as a key value.

While encrypting the given string, 3 is added to the ASCII value of the characters. Similarly, for decrypting the string, 3 is subtracted from the ASCII value of the characters to print an original string.

Let’s take a look at the program.

Example: C program to encrypt and decrypt the string.

//Simple C program to encrypt and decrypt a string

#include <stdio.h>

int main()
{
   int i, x;
   char str[100];

   printf("\nPlease enter a string:\t");
   gets(str);

   printf("\nPlease choose following options:\n");
   printf("1 = Encrypt the string.\n");
   printf("2 = Decrypt the string.\n");
   scanf("%d", &x);

   //using switch case statements
   switch(x)
   {
   case 1:
      for(i = 0; (i < 100 && str[i] != '\0'); i++)
        str[i] = str[i] + 3; //the key for encryption is 3 that is added to ASCII value

      printf("\nEncrypted string: %s\n", str);
      break;

   case 2:
      for(i = 0; (i < 100 && str[i] != '\0'); i++)
        str[i] = str[i] - 3; //the key for encryption is 3 that is subtracted to ASCII value

      printf("\nDecrypted string: %s\n", str);
      break;

   default:
      printf("\nError\n");
   }
   return 0;
}

Output

#Encryption
c encrypt string

#Decryption
c decrypt string

Explanation

In the above program, we have used simple logic for encrypting and decrypting a given string by simply adding and subtracting the particular key from ASCII value.