使用 libcrypto 将哈希复制到字符数组

发布于 2024-08-16 03:40:51 字数 798 浏览 3 评论 0原文

我正在遵循以下位置的代码示例:http://www.openssl。 org/docs/crypto/sha.html#

之后:

EVP_DigestFinal_ex(&mdctx, md_value, &md_len);

最终摘要存储在 md_value 中。我想将该摘要复制到另一个相同大小的字符数组。但这是一个由两部分组成的问题。我不明白 md_value 中到底存储了什么,看起来像二进制。以下 printf 将数据格式化为输出十六进制,这就是我需要的..涉及的哈希的最终字符串版本(在我有上下文的循环内:

printf("val: %02x\n", md_value[i]);

我的问题是,如何仅将十六进制值复制到另一个字符数组这是我到目前为止所尝试的,就示例而言,这很糟糕:

for(i = 0; i < md_len; i++) {
    unsigned char c;
   printf("val: %02x\n", md_value[i]);
    sprintf(c, "%02x", md_value[i]);
    h[0] = c;
}

在本例中, h 是我想要复制十六进制字符的位置,它是一个字符数组,如下所示:

unsigned char h[EVP_MAX_MD_SIZE];

I'm following the example of code available in: http://www.openssl.org/docs/crypto/sha.html#

After the following:

EVP_DigestFinal_ex(&mdctx, md_value, &md_len);

the final digest is stored in md_value. I'd like to copy that digest to another character array of equal size. This is a two part problem though. I'm not understanding what exactly is being stored in md_value, looks like binary. The following printf formats the data to output hex, which is what I need.. a final string version of the hash involved (within a loop where i has context:

printf("val: %02x\n", md_value[i]);

My question is, how do I copy only the hex values to another character array. Here's what I've tried so far, which is terrible in as far as an example goes:

for(i = 0; i < md_len; i++) {
    unsigned char c;
   printf("val: %02x\n", md_value[i]);
    sprintf(c, "%02x", md_value[i]);
    h[0] = c;
}

h in this case is where I want the hex characters copied. It is a character array that looks like:

unsigned char h[EVP_MAX_MD_SIZE];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜夜流光相皎洁 2024-08-23 03:40:51

我不确定您的问题是否要复制原始数据或创建格式化的文本字符串。

无论如何,要复制原始数据,memcpy 就是您想要的:

unsigned char *copy = malloc(md_len);
memcpy(copy, md_value, md_len);

如果您想创建格式化字符串,那就需要 sprintf:

// each byte needs two chararacters for display plus 1 for terminating NULL
char *formatted = malloc(md_len * 2 + 1);

for (idx = 0; idx < md_len; ++idx)
{
    sprintf(formatted + idx * 2, "%02x", md_value[idx]);
}

I'm not sure from your question if you want to copy the raw data or to create a formatted textual string.

Anyway, to copy the raw data, memcpy is what you want:

unsigned char *copy = malloc(md_len);
memcpy(copy, md_value, md_len);

If you want to create a formatted string, that's when you need sprintf:

// each byte needs two chararacters for display plus 1 for terminating NULL
char *formatted = malloc(md_len * 2 + 1);

for (idx = 0; idx < md_len; ++idx)
{
    sprintf(formatted + idx * 2, "%02x", md_value[idx]);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文