簡體   English   中英

使用凱撒密碼在 C 中加密

[英]Encryption in C using a Caesar Cipher

我被要求創建一個程序,在該程序中我必須使用凱撒密碼對多條信息進行加密。 我理解它背后的概念,但我在視覺上遇到的問題是如何在函數中輸入數據片段。 例如,我將加密的密碼保存在文件中(“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 表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM