简体   繁体   中英

Vigenere cipher in C wraparound

I'm having trouble writing the last part of my code for an assignment which involves writing a Vigenere cipher. The encryption part is working fine, but I'm having trouble figuring out how to repeat the encryption word/keyword. So it works fine if the message that needs to be encrypted is smaller or equal to the keyword and otherwise it puts out another couple of characters, that seem encrypted, but aren't.

This is the code so far:

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

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("YELL!\n");
        return 1;
    }
    //check if the number of command line arguments is correct, if not, YELL!

    string keyword = (argv[1]);
    //get keyword

    for (int j = 0, n = strlen(keyword); j < n; j++)
    {
    if(!isalpha(keyword[j]))
        {   
        printf("YELL!\n");
        return 1;
        }
    }
    //check if the keyword is only alphabetical, if not, YELL!

    string message = GetString();
    //get plaintext

    for (int j = 0, n = strlen(keyword); j < n; j++)
    {
        if (isupper(keyword[j]))
        {
            keyword[j] = (keyword[j] - 'A');
        }

        if (islower(keyword[j]))
        {
            keyword[j] = (keyword[j] - 'a');
        }
    }
    //this is to get the numerical values from the ascii values of the keyword.

    for (int i = 0, j = 0, n = strlen(message); i < n; i++, j++)
    //counting through the message & the cypher
    {
        if (isalpha(message[i]))
        {
            if (isupper(message[i]))
            {
            message[i] = (((message[i] - 'A') + keyword[j]) % 26 + 'A');
            }

            if (islower(message[i]))
            {
            message[i] = (((message[i] - 'a') + keyword[j]) % 26 + 'a');
            }

            //adding a keyword value [j] to message [i] and converting back to ascii value, 
            //individually for upper and lowercase characters.
        }
    printf("%c", message[i]);
    } 
}

It's probably an easy solution, but I just can't figure it out. Any help would be vastly appreciated!

It's a miracle encryption is working for you. I think is is not, as your loop is clearly might get j past the keyword length and then keyword[j] will be out of bounds and exhibit undefined behavior. You need only to iterate on i over the message length and index the keyword with keyword[i % strlen(keyword)] , such that the index will go cyclically from 0 to the length of the keyword minus one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM