gpt4 book ai didi

c - Vigenere Cipher - 无法解释的细微差别

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:43:07 27 4
gpt4 key购买 nike

我正在用 C 语言实现 Vigenere 密码。我的解决方案一直错误地加密纯文本。因此,我决定对我的代码进行(有点武断的)更改。更改的目的只是通过更好地定位我的变量并为它们提供更合适的名称来使代码更具可读性。但是,此更改现在已导致解决方案正确加密; 我无法解释为什么当前的解决方案比原来的解决方案更有效。有人可以启发我吗?

原始.c

//...code to validate user input

string k = argv[1]; //'argv' being a main method parameter
string str = GetString();

//Encrypt using vigenere
for (int i = 0, n = strlen(str); i < n; i++) {

/*An int to keep track of which char to use from the keyword.
Only increment if str[i] was alphabetic.*/
int k_index = 0;
int k_len = strlen(k);
char letter_key = tolower(k[k_index % k_len]);

//Checking if str[i] is alphabetic
if (isalpha(str[i])) {

//Checking if str[i] is uppercase
if (isupper(str[i])) {

//enciphering using vigenere formula
str[i] = ((str[i] - 'A') + (letter_key - 'a')) % 26 + 'A';
printf("%c", str[i]);
k_index++;
}

//If not uppercase, it must be lowercase
else {
//enciphering using vigenere formula
str[i] = ((str[i] - 'a') + (letter_key - 'a')) % 26 + 'a';
printf("%c", str[i]);
k_index++;
}

} else {
printf("%c", str[i]);
}
}

输出

Key: "chasi"
Input/Result: "my plaintext" ---> "oa rnckpvgzv"
Should be: "of pdikutwfv"

updated.c

//...code to validate user input

string k = argv[1];
string str = GetString();

//Encrypt using vigenere
for (int i = 0, j = 0, n = strlen(str); i < n; i++) {

/*"int j" is to keep track of which char to use from the keyword.
Only increment if str[i] was alphabetic.*/

int k_len = strlen(k);
char letter_key = tolower(k[j % k_len]) - 'a';

//Checking if str[i] is alphabetic
if (isalpha(str[i])) {

//Checking if str[i] is uppercase
if (isupper(str[i])) {

//enciphering using vigenere formula
str[i] = ((str[i] - 'A') + letter_key) % 26 + 'A';
printf("%c", str[i]);
j++;
}

//If not uppercase, it must be lowercase
else {
//enciphering using vigenere formula
str[i] = ((str[i] - 'a') + letter_key) % 26 + 'a';
printf("%c", str[i]);
j++;
}

} else {
printf("%c", str[i]);
}
}

输出:

Key: "chasi"
Input/Result: "my plaintext" ---> "of pdikutwfv" (correct)

最佳答案

原始代码做的是:

int k_index = 0;

每次循环。然后当它发生时:

char letter_key = tolower(k[k_index % k_len]);

它使用这个 0 值,所以 letter_key 总是 tolower(k[0])。它执行 k_index++; 的地方没有效果,因为变量在再次使用之前会被清零。因此,您只是将 key 的第一个字符用作整个 key 。

在更新的代码中,变量j 取代了k_index。它在循环开始时被初始化为 0,而不是每次循环。所以当你这样做时:

char letter_key = tolower(k[j % k_len]) - 'a';

您正在使用 j 的更新值。这正确地使用了整个 key 。

关于c - Vigenere Cipher - 无法解释的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053677/

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