当条件改变时 char* 给出不同的结果

标签 c char md5

我正在使用 C 创建一个简单的 md5 类暴力程序。我遇到的唯一问题是,如果我要替换 if 语句的一部分,Found String: 输出会完全改变。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <stdbool.h>
#if defined(__APPLE__)
#  define COMMON_DIGEST_FOR_OPENSSL
#  include <CommonCrypto/CommonDigest.h>
#  define SHA1 CC_SHA1
#else
#  include <openssl/md5.h>
#endif
char *str2md5(const char *str, int length) {
    int n;
    MD5_CTX c;
    unsigned char digest[16];
    char *out = (char*)malloc(33);

    MD5_Init(&c);

    while (length > 0) {
        if (length > 512) {
            MD5_Update(&c, str, 512);
        } else {
            MD5_Update(&c, str, length);
        }
        length -= 512;
        str += 512;
    }

    MD5_Final(digest, &c);

    for (n = 0; n < 16; ++n) {
        snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
    }

    return out;
}
typedef struct md5data {
char* output;
char* strin;
} md5data;
md5data getrand() {
        for (int i = 0; i < 10; ++i)
        {
            rand();
            srand(rand());
        }
        unsigned char strin[50];
        for (int i = 0; i < 50; i++)
        {
        strin[i] = (rand()%94)+32;
        }
        strin[49] = '\0';
        char* string = &strin;
        char *output = str2md5(string, strlen(string));
        md5data out;
        out.output = output;
        out.strin = string;
        return out;
    }
bool starts_with(const char* a, const char* b)
{
   if(strncmp(a, b, strlen(b)) == 0) return 1;
   return 0;
}
int main() {
    char input;
    printf("%s","Enter Search String: ");
    scanf("%s",&input);
    srand(time(NULL));
    while(1 == 1) {
        md5data md5 = getrand();
        if(starts_with(md5.output,&input)) {
            printf("Found String: %s\nMD5: %s\n",md5.strin,md5.output);
            break;
        }
    }
    return 0;
}

每当我编译并执行时,输出的第一行通常类似于 Found String: 0????

但是,如果我将 starts_with(md5.output,&input) 更改为 1==1 或类似的内容,则输出类似于 找到字符串:qM39$dcX_ZqFM9]?>jKhxSl@m2xrAxaL*

是什么导致输出发生变化以及为什么会发生这种情况?

最佳答案

问题出在线路上:

字符输入; printf("%s","请输入搜索字符串:"); scanf("%s",&input);

input 应该是一个字符数组(缓冲区),而不是单个字符。 例如:

字符输入[256]; printf("%s","请输入搜索字符串:"); scanf("%s",&输入);

在当前状态下,scanf 会导致堆栈上的缓冲区溢出,从而导致未定义的结果。

关于当条件改变时 char* 给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54381987/

相关文章:

c# - 在 C# 中创建 URL 简码

php - 无法使用数据库中的加密密码登录

Linux/Windows 中的 C/C++ 内存使用 API

c - 为什么不显示输出?

php - MySQL 的 CHAR 数据类型是否有可以存储超过 255 个字符的固定长度版本?

c++ - 字符到字符* C++

c - 将 int 转为 char C

java - 从消息摘要中获取 MD5 字符串

c - 返回零后出现段错误

c - fscanf 读取小时格式