首页 > 解决方案 > 尝试编写加密算法

问题描述

我正在尝试创建一种算法,该算法使用替换方法将消息加密为另一个消息。

用户将运行

./encryption.c KEY

其中 KEY 是一串字母,它只包含字母表中的每个字母一次。例如

./encryption.c bcdefghijklmnopqrstuvwxyza

然后它会询问用户他们想通过这个 KEY 加密的消息。例如,你好世界。然后加密将遵循替换式算法。

程序将在此处查看消息的第一个/下一个字母,找到它在字母表中的位置,并在加密中将其替换为在密钥中具有相同位置的字母(应该是不同的字母)。

它是这样的:(其中明文是消息,密文是加密文本,Alphabet 是字母表中的字母数组):

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

const char Alphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; // A collection of letters to teach the computer the alphabet.
string plaintext = get_string("plaintext: ");
char ciphertext[strlen(plaintext) + 1];
ciphertext[strlen(plaintext) + 1] = '\0';
for (int j = 0; j < strlen(plaintext); j ++) // Handling the first/next letter of plaintext.
{
    char letter = plaintext[j];
    bool needCapital = isupper(letter);
    char cipherletter;
    for (int k = 0; k < strlen(ciphertext); k ++) // Finding the position of said letter.
    {
        char compe = Alphabet[k];
        if (needCapital == true)
        {
            compe = toupper(Alphabet[k]);
        }
        if (compe == letter)
        {
            cipherletter = key[k]; // Encryption.
            ciphertext[j] = cipherletter;
            printf("%s\n", ciphertext);
            break;
        }
        else if (isalpha(compe) == false)// This path is used for keeping punctuation the same.
        {
            cipherletter = letter;
            ciphertext[j] = cipherletter;
            printf("%s\n", ciphertext);
        }
    }
}
printf("ciphertext: %s\n", ciphertext); // End---

(为冗长的代码道歉)int main(void)将解决所有这些问题。

但是,虽然我的代码编译正确,但该程序似乎在某处感到困惑,因为它根本没有正确加密消息......有人可以尝试运行它并告诉我哪里出错了吗?我希望我已经设法正确解释它,但请随时要求我进一步解释。

标签: ccs50

解决方案


推荐阅读