【问题标题】:Something wrong while using crypt function in C在 C 中使用 crypt 函数时出现问题
【发布时间】:2013-01-28 05:48:16
【问题描述】:

我在 C 中使用 crypt 函数,我在其中给命令行输入一个加密的单词。我使用 /usr/share/dict/words 中的单词并使用 crypt 函数对其进行加密,然后将 crypt 函数的加密输出与命令行输入进行比较。如果单词相同,那么我使用 printf 语句将未加密的代码作为输出给出。 代码如下。

    #include<stdio.h>
    #define _XOPEN_SOURCE
    #include<unistd.h>
    #include<cs50.h>
    #include<string.h>
    int
    main(int argc, string argv[]){
    char line[80];
    string crypto;
    if(argc>2||argc<2)
     {
     printf("ERROR. Enter only one crypt");
     return 1;
     }
    string crypti=argv[1];
    FILE *fr;
    string as;
    fr=fopen("/usr/share/dict/words","r");
    if(!fr)
        {
      printf("File can't be read");
      exit(-1);
        }
    while(fgets(line,80,fr)!=NULL)
      {
      as=crypt(line,"50");
      if(strcmp(as,crypti)==0)
       {
     printf("%s",line);
      break;
       }
       }
    fclose(fr);
   }

代码似乎仅适用于 1 个输入,即当我给出“./a.out 50q.zrL5e0Sak”(不带引号)时。但是,如果我对 crypt 使用任何其他输入,则代码似乎会失败。另一个密码:加密密码的例子是 abaca:50TZxhJSbeG1I。 abaca 一词出现在列表中,但无法识别。我无法修复此代码以适用于所有输入。

【问题讨论】:

    标签: c encryption cs50


    【解决方案1】:

    while (fgets...)正文的开头添加以下sn-p:

      size_t len = strlen(line);
      if (len)
        line[len-1]='\0';
    

    fgets 读取的缓冲区末尾通常有一个换行符\n(读取时)。

    您的原始代码适用于"password",因为crypt 实际上只使用了密钥的前8 个字符。它也适用于长度为 8 或更长的任何单词。

    另外,通过在格式字符串中添加换行符或(如果您不想输出额外的换行符)调用fflush(stdout),确保在打印结果后刷新输出:

    printf("%s\n",line);
    /* or */
    printf("%s",line);
    fflush(stdout);
    

    【讨论】:

    • 谢谢。它似乎适用于 8 个字符或更多字符。但仍然无法让它在少于 8 个字符的情况下工作。
    • 它对我有用(我在/usr/share/dict/words 中没有“abaca”,但 abacus 在那里并且可以为508kXyEKZ232U 找到)。如果您的 shell 提示符没有以换行符结尾,则可能很难看到您的输出:尝试将 \n 添加到您的格式字符串中。
    • 我使用 fflush(stdout) 后它似乎工作正常。非常感谢。
    猜你喜欢
    • 2010-10-25
    • 1970-01-01
    • 2017-07-17
    • 2020-01-23
    • 2011-04-22
    • 2020-04-25
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多