我已经编写了加密和解密维吉尼亚密码的程序,但我有几个问题。
- 如下:句子的第一个字母加密不正确。
- 第二个:在句子之后我有字母
K
。我认为这是因为空间问题,但我不知道如何解决。 - 第三个问题:加密的句子中没有空格,我很久以前就知道,当使用维吉尼亚密码时,没有空格,但如果可能的话,我希望有 5 个字母的组。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char **argv) {
char message[100];
int choice;
int i, j;
char pass[33];
int value;
char repeat = 1;
while (repeat == 1) {
printf("Enter operation\n");
printf("Encrypt - 1 \n");
printf("Decrypt - 2\n");
scanf("%d", &choice);
if (choice == 1) {
printf("Please enter message to encrypt\n");
while (getchar() != '\n');
fgets(message, 100, stdin);
printf("Enter password\n");
scanf("%s", &pass);
for (i = 0, j = 0; i < strlen(message); i++, j++) {
if (message[i] == ' ')
continue;
if (j >= strlen(pass)) {
j = 0;
}
if (!isupper(message[i])) {
value = (((message[i]) - 97) + ((pass[j]) - 97));
}
if (!islower(message[i])) {
value = (((message[i]) - 65) + ((pass[j]) - 65));
}
printf("%c", 97 + (value % 26));
}
printf("\nWould you like to repeat? [1/0]\n");
scanf("%d", &repeat);
} else
if (choice == 2) {
printf("Enter message do decrypt\n");
while (getchar() != '\n');
fgets(message, 100, stdin);
printf("Zadejte heslo\n");
scanf("%s", &pass);
for (i = 0, j = 0; i < strlen(message); i++, j++) {
if (message[i] == ' ')
continue;
if (j >= strlen(pass)) {
j = 0;
}
if (!isupper(message[i])) {
value = (((message[i]) - 96) - ((pass[j]) - 96));
}
if (!islower(message[i])) {
value = (((message[i]) - 64) - ((pass[j]) - 64));
}
if (value < 0) {
value = value * -1;
}
printf("%c", 97 + (value % 26));
}
printf("\nWould you like to repeat? [1/0]\n");
scanf("%d", &repeat);
}
}
return (EXIT_SUCCESS);
}
[
最佳答案
代码中的主要问题是您将翻译应用于测试不正确的字符:如果您确实有大写字母,则应该翻译大写字母,而不是如果您没有小写字符。按照编码,非字母被翻译两次。
将代码更改为:
if (islower((unsigned char)message[i])) {
value = (((message[i]) - 'a') + ((pass[j]) - 'a'));
}
if (isupper((unsigned char)message[i])) {
value = (((message[i]) - 'A') + ((pass[j]) - 'a'));
}
还要确保使用字符常量而不是硬编码的 ASCII 值,并将密码设置为小写。
在解密的情况下,偏移量似乎不正确。您也应该使用 'A'
和 'a'
。
关于c - C语言维吉尼亚密码的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46266941/