gpt4 book ai didi

c++ - 是否有将 SHA1 散列表示为 C 字符串的标准方法,我如何转换成它?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:47 25 4
gpt4 key购买 nike

This question是关于如何使用 OpenSSL 从 C 中的数据数组创建 SHA-1 HashMap 书馆。

它返回一个包含哈希值的 20 字节数组。是否有某种标准方法以字符串形式而非二进制形式表示该数据?

如果是这样,OpenSSL 本身是否有转换为所述字符串格式的函数?

如果不行,应该怎么做?当然,我可以想出自己的编码方式,使用 base64 或不使用什么,但是有一些规范的格式吗?

最佳答案

通常哈希值表示为十六进制数字序列(自然地,每个字节两个)。您可以使用带有正确修饰符的 ostringstream 轻松编写代码来编写此类内容:

#include <string>
#include <sstream>
#include <iomanip>

std::string GetHexRepresentation(const unsigned char *Bytes, size_t Length) {
std::ostringstream os;
os.fill('0');
os<<std::hex;
for(const unsigned char *ptr = Bytes; ptr < Bytes+Length; ++ptr) {
os<<std::setw(2)<<(unsigned int)*ptr;
}
return os.str();
}

可以说,这也可以更有效地“手工”完成(并且,在我今天看来,更清楚):

#include <string>

std::string GetHexRepresentation(const unsigned char *Bytes, size_t Length) {
std::string ret(Length*2, '\0');
const char *digits = "0123456789abcdef";
for(size_t i = 0; i < Length; ++i) {
ret[i*2] = digits[(Bytes[i]>>4) & 0xf];
ret[i*2+1] = digits[ Bytes[i] & 0xf];
}
return ret;
}

或者使用旧的sprintf,可能是所有方法中最容易阅读的方法:

#include <stdio.h>
#include <string>

std::string GetHexRepresentation(const unsigned char *Bytes, size_t Length) {
std::string ret;
ret.reserve(Length * 2);
for(const unsigned char *ptr = Bytes; ptr < Bytes+Length; ++ptr) {
char buf[3];
sprintf(buf, "%02x", (*ptr)&0xff);
ret += buf;
}
return ret;
}

关于c++ - 是否有将 SHA1 散列表示为 C 字符串的标准方法,我如何转换成它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3969047/

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