How to create a md5 hash of a string in C?

前端 未结 6 836
独厮守ぢ
独厮守ぢ 2020-12-07 19:06

I\'ve found some md5 code that consists of the following prototypes...

I\'ve been trying to find out where I have to put the string I want to hash, what functions I

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-07 19:45

    Here's a complete example:

    #include 
    #include 
    #include 
    #if defined(__APPLE__)
    #  define COMMON_DIGEST_FOR_OPENSSL
    #  include 
    #  define SHA1 CC_SHA1
    #else
    #  include 
    #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;
    }
    
        int main(int argc, char **argv) {
            char *output = str2md5("hello", strlen("hello"));
            printf("%s\n", output);
            free(output);
            return 0;
        }
    

提交回复
热议问题