c - 使用凯撒密码在 C 中进行加密
问题描述
我被要求创建一个程序,我必须使用凯撒密码加密多条信息。我理解它背后的概念,但我在视觉上遇到的问题是如何在函数中输入数据片段。例如,我将加密密码保存在文件中(“hrkk1”表示“pass1”等)。我必须创建一个密码函数来从 scanf 和 strcmp 读取输入,以便它与允许用户登录的文件中的内容相匹配。
验证用户输入并使“pass1”变为“hrkk1”以匹配文件中的内容并允许用户登录的最佳方法是什么?
谢谢
这是我到目前为止的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <windows.h>
void checkValid(void);
void loginDetails(char username[5][6], char password[5][9]);
void encryption(char username[5][6], char password[5][9]);
int main(void)
{
FILE *EP;
FILE *UN;
char username[5][6];
char password [5][9], ch, key;
EP = fopen("encrypted_passwords.txt", "r");
fscanf(EP, "%s %s %s %s %s", password[0], password[1],
password[2], password[3], password[4]);
fclose(EP);
UN = fopen("username.txt", "r");
fscanf(UN, "%s %s %s %s %s", username[0], username[1], username[2],
username[3], username[4]);
fclose(UN);
printf("Welcome.");
loginDetails(username, password);
return 0;
}
void loginDetails(char username[5][6], char password[5][9])
{
int i;
char nurseUsername[6];
char nursePassword[6];
bool useValid = 0;
bool passValid = 0;
printf("Please Enter your username: \n");
scanf("%s", nurseUsername);
for (i = 0; i < 5; i++)
{
if(strcmp(nurseUsername, username[i]) == 0)
{
useValid = 1;
}
}
if(useValid != 1)
{
printf("\nError. Invalid Username. Returning to menu.\n");
Sleep(1000);
system("cls");
main();
}
else
{
printf("\nPlease enter your password: \n");
scanf("%s", nursePassword);
}
for(i = 0; i < 5; i++)
{
if((strcmp(nurseUsername, username[i]) == 0) &&
(strcmp(nursePassword, password[i]) == 0))
{
passValid = 1;
}
if(passValid != 1)
{
printf ("Error. Invalid Password. Returning to menu.\n");
Sleep(1000);
system("cls");
main();
}
else
{
printf("\nLogin Successful. Loading menu.\n");
Sleep(1000);
system("cls");
patientEntry();
}
}
}
解决方案
您需要使用 c 中的字符移位。这可以通过对 char 值进行简单的加法(或减法)来实现。
请注意,您的示例不会移动数字字符,并且该字符可能也不会超出字母表,并且还考虑了大写字母。所以在做加法时要注意不要超出大写或非大写字母的范围。我的建议是使用 ascii 表。
推荐阅读
- maven - 在 Maven 中将 Primefaces 从 6.2 升级到 7.0.14
- javascript - 获取 typeError: (options.astTransformers || []).map 在 Angular 中运行测试套件时不是一个函数
- java - JAXB post api 不接受 json 请求,java 中出现通用 500 错误
- javascript - Nodejs axios 比邮递员花费更长的时间
- html - 删除 Material 图标和周围 div 之间的空间
- php - 在插件中扩展 WooCommerce COD 支付网关
- graph - Gremlin with java - 是否可以在启用新 TraversalStrategy 的情况下从 java 客户端覆盖 gremlin 服务器的“g”
- docker - docker-compose 命令无法正常停止
- sql - 使用 sql 查询产生问题的父权字符
- python-3.x - gsutil 的 subprocess.Popen 出现语法错误