【问题标题】:MD5 hash of a string which is already md5 hashed: Syntax error已经经过 md5 散列的字符串的 MD5 散列:语法错误
【发布时间】:2019-05-21 04:23:42
【问题描述】:

我想生成一个已经经过 md5 散列的字符串的 md5 散列。这就是我所做的!我已经循环了它,但不幸的是,它显示了一些错误“sh:2:语法错误:“|”意外”。 我希望它与循环内的“strcat”有关。 不知何故在循环内的行

strcpy(command,"echo ");
strcat(command,str);

被忽略。我迷路了!

谁能帮帮我?

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
   FILE *fp;
   char str[100], command[100];
   char var[100];
   int i;
   printf("Enter the string:\n");
   scanf("%[^\n]s",str);
   printf("\nString is: %s\n\n",str);
   for (i=0; i<3; i++) {
       strcpy(command,"echo ");
       strcat(command,str);
       strcat(command," | md5sum");
       strcat(command," | cut -c1-32");
       fp = popen(command, "r");
       fgets(var, sizeof(var), fp);
       pclose(fp);
       strcpy(str,var);
   }
   printf("The md5 has is :\n");
   printf("%s\n", var);   
   return 0;     

}

【问题讨论】:

  • Io 重定向是 shell 所做的;不是您通过popen 做的事情。如果您真的想从一个进程重定向到另一个进程,这是可能的,但比复制/粘贴您在 shell 提示符下键入的内容(看起来就是您正在尝试的内容)要复杂得多。我敢问,你为什么不使用像 OpenSSL 这样的加密库?使用该工具包制作 anything 的 MD5 哈希值几乎是微不足道的。
  • 感谢 WhozCraig 的此输入。我会尝试这种替代方法。

标签: c md5sum


【解决方案1】:

您的问题来自fgets,它在读取缓冲区中保留换行符。

来自 man fgets:

fgets() 从流中最多读入一个小于 size 的字符,并将它们存储到 s 指向的缓冲区中。在 EOF 或换行符后停止读取。 如果读取了换行符,则将其存储到缓冲区中。一个终止的空字节 (\0) 存储在缓冲区中的最后一个字符之后。

因此,您可能希望将 \n 替换为一些 \0。你可以用strcspn

   ...           
   fgets(var, sizeof(var), fp);
   pclose(fp);
   strcpy(str,var);

   /* remove first \n in str*/
   str[strcspn(str, "\n")] = '\0';

   ...

【讨论】:

  • 它还应该转义很多特殊字符,例如重定向字符(|&gt;&lt;)和所有引号。无论如何,通过 shell 执行此操作很奇怪,使用库绝对是要走的路。只有作为一个实验,这是可以接受的,仍然应该进行转义。
  • 感谢 Mathieu 和 Ho Zong,我已经设法修复了我当前的代码。但是会使用一个库并重写它。非常感谢
猜你喜欢
  • 1970-01-01
  • 2017-01-04
  • 2014-06-04
  • 2012-06-17
  • 1970-01-01
  • 2014-11-18
  • 2015-03-13
  • 2013-08-29
  • 1970-01-01
相关资源
最近更新 更多