Vigenere's Cipher code C

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Here's a link explaining Vigenere's cipher

https://www.geeksforgeeks.org/vigenere-cipher/

 

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

int main(int argc, string argv[])
{
    int x=0;
    // storing the key in k
    string k = argv[1];
    // checking if key contains only alphabets
    for (int n = 0; n < strlen(k); n++)
        {
            if (!isalpha(k[n]))
            {
                x=1;
            }
        }

    // if key exists
    if ((argc == 2) && (x == 0))
    {
        int cipher[64];
        string message = get_string("plaintext:  ");
        char result[strlen(message)], newKey[strlen(message)];
        int keyCount = 0;

        // For loop to convert key to upper and set value ie A = 0, B = 1 etc
        for (int j = 0; j < strlen(k); j++)
        {
            cipher[j] = (toupper(k[j]) - 65);
        }

        // converting the message
        for (int i = 0; i < strlen(message); i++)
        {
            if (isupper(message[i]))
            {
                result[i] = (message[i] - 65 + cipher[keyCount]) % 26 + 65;
                keyCount++;
            }
            else if (islower(message[i]))
            {
                result[i] = (message[i] - 97 + cipher[keyCount]) % 26 + 97;
                keyCount++;
            }
            else
            {
                result[i] = message[i];
            }
            if (keyCount >= strlen(k))
            {
                keyCount = 0;
            }
        }

        printf("ciphertext: %s\n", result);
    }
    else
    {

        printf("Error Enter valid key \n");
        return 1;
    }

    return 0;
}

Here is the code I've written. It works for most cases except two cases which I've come across: when the message is 'a' and the key is 'a' (O/P should be a) and when the key is 'baz' and the message is 'world!&$'. In both these cases, I get a random letter in the encrypted message at the end. It is random. Where am i going wrong?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

ran it through a linter

primary warnings :

  • signed and unsigned at the first 'for' (n shouldn't be an int) (a few more of that kind of warning)
  • newKey is declared but not read

added :

typedef char* string;

then

PC-lint Plus Online Demo - Gimpel Software - The Leader in Static Analysis for C and C++ with PC-lint Plus

C11, Visual Studio 2015

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

"result" is not terminated (and it is too small to do so).

Stefan Ernst