在 SHA256 哈希函数中使用的 Setw 和 setfill
Setw and setfill as it's used in a SHA256 hash function
在学习 OpenSSL 的一些基础知识时,我遇到了 create an SHA256 hash:
的代码
using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
谁能解释一下ss << hex << setw(2) << setfill('0') << (int)hash[i];
在这个具体例子中做了什么,尽可能简单,同时仍然有效地解释它?
由于我似乎无法理解这些答案,它们无助于理解我的特定片段:
Using setw and setfill on string
How to use setw and setfill together in C++ to pad with blanks AND chars
在 C++ 中有许多不同的 流。您可能知道 cout
将输出写入控制台,cin
读取输入。 stringstream
is a class whose object write to and read from string
个对象。写入字符串流(如变量 ss
)就像写入 cout
一样,但写入的是字符串而不是控制台。
你说你会C语言?那你应该知道十六进制表示法吧?这就是 the hex
manipulator 告诉流使用的内容。这类似于 printf
格式说明符 "%x"
.
The setw
manipulator设置下一次输出的字段宽度。
The setfill
manipulator 设置输出的 fill 字符。
最后 hash[i]
到 int
的转换是因为 hash[i]
是一个 char
并且输出到流将把它写成一个字符而不是一个小整数.
简而言之,
ss << hex << setw(2) << setfill('0') << (int)hash[i];
相当于C代码
sprintf(temporaryBuffer, "%02x", hash[i]);
strcat(ss, temporaryBuffer);
在学习 OpenSSL 的一些基础知识时,我遇到了 create an SHA256 hash:
的代码using namespace std;
#include <openssl/sha.h>
string sha256(const string str)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, str.c_str(), str.size());
SHA256_Final(hash, &sha256);
stringstream ss;
for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
{
ss << hex << setw(2) << setfill('0') << (int)hash[i];
}
return ss.str();
}
谁能解释一下ss << hex << setw(2) << setfill('0') << (int)hash[i];
在这个具体例子中做了什么,尽可能简单,同时仍然有效地解释它?
由于我似乎无法理解这些答案,它们无助于理解我的特定片段:
Using setw and setfill on string
How to use setw and setfill together in C++ to pad with blanks AND chars
在 C++ 中有许多不同的 流。您可能知道 cout
将输出写入控制台,cin
读取输入。 stringstream
is a class whose object write to and read from string
个对象。写入字符串流(如变量 ss
)就像写入 cout
一样,但写入的是字符串而不是控制台。
你说你会C语言?那你应该知道十六进制表示法吧?这就是 the hex
manipulator 告诉流使用的内容。这类似于 printf
格式说明符 "%x"
.
The setw
manipulator设置下一次输出的字段宽度。
The setfill
manipulator 设置输出的 fill 字符。
最后 hash[i]
到 int
的转换是因为 hash[i]
是一个 char
并且输出到流将把它写成一个字符而不是一个小整数.
简而言之,
ss << hex << setw(2) << setfill('0') << (int)hash[i];
相当于C代码
sprintf(temporaryBuffer, "%02x", hash[i]);
strcat(ss, temporaryBuffer);