c - 尝试编写加密算法
问题描述
我正在尝试创建一种算法,该算法使用替换方法将消息加密为另一个消息。
用户将运行
./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)
将解决所有这些问题。
但是,虽然我的代码编译正确,但该程序似乎在某处感到困惑,因为它根本没有正确加密消息......有人可以尝试运行它并告诉我哪里出错了吗?我希望我已经设法正确解释它,但请随时要求我进一步解释。
解决方案
推荐阅读
- ruby-on-rails - Rails 语法错误,意外的输入结束,期望关键字_end
- node.js - 如何在 node.js 的 res.json() 中返回键值对数组?
- powershell - PowerShell脚本从服务器的多个文件夹复制相同的文件并粘贴到另一台服务器
- node.js - 永远启动 angular-http-server 不起作用
- r - 难以计算协方差和方差
- python - 使用 Python 将自动过滤器应用于工作表
- macos - 我如何在 Mac 上打开 *.ps.gz 文件
- apache-spark - apache spark中 executorRunTime 和 executorCpuTime 的主要区别是什么。executorRunTime 是否包含 executorCpuTime
- python - 通过重用另一个函数来创建一个以元组为值的字典
- java - 在 JPanel 中对齐 JTextArea