gpt4 book ai didi

c - 维吉尼亚密码

转载 作者:行者123 更新时间:2023-11-30 20:01:00 27 4
gpt4 key购买 nike

我正在尝试用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com