我正在尝试在C中制作Vigenere Cipher。https://www.youtube.com/watch?v=9zASwVoshiM这是有关Vigenere Cipher的信息。我的代码在某些情况下不起作用,例如加密“世界,打个招呼!”。作为“ xoqmd,rby gflkp!”使用“ baz”作为关键字,而是将其加密为xomd,szz fl。另一个示例是:
使用“ BaZ”作为关键字将“ BaRFoo”加密为“ CaQGon”,但将其加密为CakGo。我的代码如下所示,请帮帮我:

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

int main(int argc, string argv[]) {
    //string plaintext;

    string key;
    if (argc != 2) {
        printf("Please run the programme again this time using a command line argument!\n");
        return 1;
    }
    key = argv[1];
    int keys[strlen(key)];

    for (int m = 0; m< strlen(key); m++) {
        if (isalpha(key[m]) == false) {
            printf("Re-Run The programme without any symbols.\n");
            return 1;
        }
    }

    for (int b = 0; b < strlen(key); b++) {
        if (isupper(key[b]) == false) {
            keys[b] = key[b] - 'a';
        }
        else {
            keys[b] = key[b] - 'A';
        }
    }

    //printf("Enter a string which should be encrypted: \n");
    string plaintext = GetString();
    int plength = strlen(plaintext);
    int klength = strlen(key);
    string ciphertext = key;

    for (int u = 0; u<plength; u++) {

        if (isalpha(plaintext[u]) == false) {
            printf("%c", plaintext[u]);
            continue;
        }

        int value = u % klength;
        ciphertext[u] = (keys[value] + plaintext[u]);
        if ((islower(plaintext[u])) && (ciphertext[u])>'z') {
            ciphertext[u] = ciphertext[u] - 'z' + 'a' - 1;
        }

        if ((isupper(plaintext[u])) && (ciphertext[u])>'z') {
            ciphertext[u] = ciphertext[u] - 'Z' + 'A' - 1;
        }

        printf("%c", ciphertext[u]);
    }

    printf("\n");

    return 0;
}

最佳答案

string ciphertext = key;


ciphertext应该以空白开头,不应将其设置为key。

ciphertext[u] = ciphertext[u] - 'z' + 'a' - 1;


这是不正确的,因为ciphertext[u]可能超出范围。字符应介于“ a”至“ z”之间。使用mod %运算符确保字符在范围内。例如:

int j = 0;
for (int u = 0; u<plength; u++)
{
    int c = plaintext[u];
    if (isalpha(plaintext[u]))
    {
        int k = keys[j % klength];
        if (islower(c))
        {
            c = 'a' + (c - 'a' + k) % 26;
        }
        else
        {
            c = 'A' + (c - 'A' + k) % 26;
        }
        j++;
    }
    ciphertext[u] = c;
}
printf("%s\n", ciphertext);

关于c - Vigenere密码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36660062/

10-10 15:58