我想在C中制作Vigenere Cipher。https://www.youtube.com/watch?v=9zASwVoshiM这是关于Vigenere Cipher的信息。我的代码工作对某些情况不起作用,比如加密“世界,打招呼!” as“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;
}
答案 0 :(得分:2)
NULL
string ciphertext = key;
应该以空白开头,不应设置为密钥。
ciphertext
这是不正确的,因为ciphertext[u] = ciphertext[u] - 'z' + 'a' - 1;
可能超出范围。性格应该在&#39; a&#39;之间。到了&#39;。使用mod ciphertext[u]
运算符确保字符在范围内。例如:
%
答案 1 :(得分:2)
许多小问题(ciphertext
需要动态分配,并以plaintext
的副本开始,而不是key
;需要对字母表的长度进行mod计算;不正确计算;将错误打印到stderr
)以及可以进行的大量小优化(组合循环;组合if
子句;将key
长度保存到变量之前)。您的代码的返工:
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[]) {
if (argc != 2) {
fprintf(stderr, "Please run the program again with a command line argument!\n");
return 1;
}
string key = argv[1];
int key_length = strlen(key);
int keys[key_length];
for (int i = 0; i < key_length; i++) {
if (!isalpha(key[i])) {
fprintf(stderr, "Re-run The program without any symbols.\n");
return 1;
}
keys[i] = toupper(key[i]) - 'A';
}
// printf("Enter a string which should be encrypted: \n");
string plaintext = GetString();
int text_length = strlen(plaintext);
string ciphertext = strcpy(malloc(text_length + 1), plaintext);
for (int i = 0, j = 0; i < text_length; i++) {
if (!isalpha(plaintext[i])) {
continue;
}
int index = j++ % key_length;
ciphertext[i] = (toupper(plaintext[i]) - 'A' + keys[index]) % (1 + 'Z' - 'A');
ciphertext[i] += isupper(plaintext[i]) ? 'A' : 'a';
}
printf("%s\n", ciphertext);
free(ciphertext);
return 0;
}
加密“世界,打招呼!” as“xoqmd,rby gflkp!”用键“baz”
使用键“BaZ”将“BaRFoo”加密为“CaQGon”