c - 维吉尼亚密码

标签 c encryption cs50 vigenere

我正在尝试用 C 语言制作维吉尼亚密码。https://www.youtube.com/watch?v=9zASwVoshiM这是有关维吉尼亚密码的信息。我的代码适用于某些情况,例如加密“世界,打个招呼!”如“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 - 维吉尼亚密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660062/

相关文章:

c - Lapacke in C : using dsymm, 链接器错误

perl - Chilkat 加密未按预期工作

php - 加密 Controller 代码

c - 为什么我可以单独打印每个字符,但不能整体打印?

即使图像已模糊,CS50 模糊功能也未通过 check50

c - 为什么 strlen 在 C 中导致段错误?

c - 这是一个体面的自制互斥锁实现吗?批评?潜在问题?

c - 重新分配同一个数组似乎不起作用

asp.net - 保护 SQL Server 2008R2 数据库的安全

c - 为什么会输出再见(随机字母/数字)而不是预期输入的整数?