gpt4 book ai didi

c - 如何将字符串传递给这个 MD5 程序?

转载 作者:行者123 更新时间:2023-11-30 17:55:05 25 4
gpt4 key购买 nike

我正在尝试实现一个使用底层MD5哈希的应用程序,我已经从互联网上获取了MD5哈希程序,但我不知道如何将字符串从我的程序(我用C编写的程序)传递到计算 MD5 哈希值的程序。

这是计算 MD5 哈希值的程序的主要部分..

//
// MD5 Hashing Example - Using Windows Crypto API
//
// by Napalm @ NetCore2K
//
#include <stdio.h>
#include <string.h>
#include "winmd5.h"
HCRYPTPROV hCryptProv;

int main(int argc, char *argv[])
{
int i;
CryptStartup();
if(argc > 1){
MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, (unsigned char *)argv[1], strlen(argv[1]));
MD5Final(&ctx);
for(i = 0; i < 16; i++)
printf("%02x", ctx.digest[i]);
printf("\n");
}else
printf("Usage: %s <string>\n", argv[0]);
CryptCleanup();
return 0;
}

这是头文件内容..

//
// MD5 Hashing Example - Using Windows Crypto API
//
// by Napalm @ NetCore2K
//
#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern HCRYPTPROV hCryptProv;

void PrintMD5(const char *);

typedef struct {

unsigned char digest[16];
unsigned long hHash;
} MD5Context;
BOOL CryptStartup()
{


if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET) == 0){
if(GetLastError() == NTE_EXISTS){
if(CryptAcquireContext(&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, 0) == 0){
return FALSE;
}
}
else return FALSE;
}
return TRUE;
}
void CryptCleanup()
{
if(hCryptProv) CryptReleaseContext(hCryptProv, 0);
hCryptProv = NULL;
}
void inline MD5Init(MD5Context *ctx)
{
CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &ctx->hHash);
}
void inline MD5Update(MD5Context *ctx, unsigned char const *buf, unsigned len)
{
CryptHashData(ctx->hHash, buf, len, 0);
}
void inline MD5Final(MD5Context *ctx)
{
DWORD dwCount = 16;
CryptGetHashParam(ctx->hHash, HP_HASHVAL, ctx->digest, &dwCount, 0);
if(ctx->hHash) CryptDestroyHash(ctx->hHash);
ctx->hHash = 0;
}
void PrintMD5(const char *s)
{
MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, (const unsigned char *)s, strlen(s));
MD5Final(&ctx);

int i;
for (i = 0; i < 16; i++) {
printf("%02x", ctx.hHash[i]);
}

printf("\n");
}

我应该如何调用这个Main(),以及如何将字符串传递给它并获取结果。?提前致谢。

问候

最佳答案

您不再调用main()。您宁愿使用此程序作为示例来编写单独的函数,如下所示:

void PrintMD5(const char *s)
{
MD5Context ctx;
MD5Init(&ctx);
MD5Update(&ctx, (const unsigned char *)s, strlen(s));
MD5Final(&ctx);

int i;
for (i = 0; i < 16; i++) {
printf("%02x", ctx.digest[i]);
}

printf("\n");
}

然后你可以从你自己的程序中调用它,例如:

PrintMD5("FooBarHelloWorld42");

关于c - 如何将字符串传递给这个 MD5 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14541142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com