比较C中的SHA校验和值
我正在进行一项在C中创建shell的任务。程序必须读取一个配置文件,其中列出了shell中允许的命令。 同样在此配置文件中,对于允许的每个命令,还会列出sha1校验和值。 示例行如下所示:(该文件也包含其他数据)
... other data .... * /bin/ls 3848bdeada63dc59d2117a6ca1348fe0981ad2fc
当用户键入命令时,程序必须检查该命令是否在配置文件中。 如果命令在列表中,则程序必须检索它的sha1和值,然后计算给定文件的sha1和值并比较它们。
我在比较这些值时遇到问题。 我从文件中读取sha1值并将其存储在char *指针中。 稍后,我使用SHA1()来计算校验和值。 但是SHA1返回的值是unsigned char *指针。 我无法弄清楚如何比较这些值。
所以,我的问题是,我应该改变读取数据的方式吗?(考虑到该文件中还有其他数据)。 如何比较这两个校验和值?
(我在这里发布了另一个问题,这是这个问题的一部分,但在收到评论后,我意识到我的问题有所不同)。
以下是代码的一些相关部分。
阅读数据:
/** CODE DELETED */ while(fgets(line,MAXLINE,confFPtr) != NULL ){ /** CODE DELTED */ /** if a command line then process the command */ else if(line[0] == CMNDSTARTER){ char *pathCommand = NULL; /** stores path+command string */ char *sha = NULL; /** stores sha string */ const char *separator = " "; /** delimiter between * command sha */ char *arrayCommand[2]; /** stores path in one index and command in another string */ /** tokenize the string */ strtok(line,separator); pathCommand = strtok(NULL,separator); sha = strtok(NULL,separator); /** Remove trailing space from end of hash */ sha = preProcess(sha); /** separate pathcommand into path and command */ getPathCmd(arrayCommand,pathCommand); /** add to list */ /** List is a linked list */ if(!addToList(cmdList,arrayCommand,sha)){ printError("Silent Exit: couldn't add to list"); exit(1); } }
COMPUTING CHECKSUM FOR FILE(由用户键入的命令)
while(1){ /** * Read commands */ if(emitPrompt){ printf("%s",prompt); fflush(stdout); } if((fgets(cmdLine, MAXLINE, stdin) == NULL) && ferror(stdin)) printError("fgets error"); /** if ctrl-d pressed exit */ if(feof(stdin)){ fflush(stdout); exit(0); } /** * Remove trailing \n and preceding white space from user command */ processedCmdLine = preProcess(cmdLine); /** If no command, continue */ if(*processedCmdLine == 0) continue; /** check if the command entered by user is in the list of allowed commands */ struct CMDList *s = searchList(cmdList,processedCmdLine); /** if command was in the list, run checksum on the file and compare it with the stored checksum value */ if(s != NULL){ unsigned char hash[SHA_DIGEST_LENGTH]; SHA1(processedCmdLine, sizeof(processedCmdLine),hash); } }
CMDList结构
struct CMDList{ char *command; char *path; char *hash; struct CMDList *next; };
你需要使用
memcmp(hash1, hash2, SHA_DIGEST_LENGTH)
你的hash1
和hash2
是char*
还是unsigned char*
或者它们的任何组合都没关系。 虽然为了保持一致性,让它们具有相同的类型是很好的:
struct CMDList{ .... unsigned char* hash; ... };
由于sha1散列具有固定长度,因此您也可以使用
unsigned char hash[SHA_DIGEST_LENGTH];
并保存动态分配。
另请注意,SHA_DIGEST_LENGTH为20,但3848bdeada63dc59d2117a6ca1348fe0981ad2fc
是一个40个字符的字符串。 您需要先将可读哈希值转换为二进制表示,然后才能使用它们。
我稍微改了一下代码( 这里可以看到代码)。 问题是我以不同的forms存储校验和值。 来自文件的校验和值是纯文本,而计算校验和将返回unsigned char。 所以我决定将返回的校验和值转换为纯文本reprsentation,然后使用strncmp()
进行比较。 在这里可以看到。