c++ - cpp用相同的输入返回不同的输出
问题描述
我用 cpp 创建了一个 sha256 演示,并想重复它 100000 次。
但是每次使用相同的输入时我都会得到不同的输出。我的代码有什么问题?
对不起,我是 cpp 的新手。
这是我的代码:
void hash_cout(string msg)
{
vector<unsigned long> block;
block = convert_to_binary(msg);
block = pad_to_512bits(block);
block = resize_block(block);
string hash = compute_hash(block);
cout << hash << endl;
}
int main(int argc, char *argv[])
{
const string message = "abcd";
for (int i = 0; i < 100000; i++)
{
hash_cout(message);
}
return 0;
}
输出:
b8863664fd63dc2f92a0858ff7059d4b4c247bd883491c1dffc84380ea320183 1d18c6dd6cd175bee1e6285ffc2ed8d2ca1c582f9818d8ffe4ef539d89e69631 d982784be169c31fe0677ecf5dc03611b9c8602c29eeac3ab71bcc0488f4dabf 888766e7fb731adfefef38ba0287b54e103b61b850a75dd106db16db1c20a25c 054a5efb4e9e67d1ebf9714bf304f78a1df3d3df79d6a793bbf1ac3e90b8af79
解决方案
从 gist.github 上发布的代码 OP:
string compute_hash(const vector<unsigned long> block)
{
...
unsigned long static H0 = 0x6a09e667;
unsigned long static H1 = 0xbb67ae85;
unsigned long static H2 = 0x3c6ef372;
unsigned long static H3 = 0xa54ff53a;
unsigned long static H4 = 0x510e527f;
unsigned long static H5 = 0x9b05688c;
unsigned long static H6 = 0x1f83d9ab;
unsigned long static H7 = 0x5be0cd19;
...
H0 = ...
}
带有 static 说明符的变量具有静态存储持续时间,在程序启动时分配,在程序结束时释放,它们仅初始化一次并在每次函数调用时保留其值。从这些行中删除说明符后static
,您的代码不再为相同的输入产生不同的结果。
现场版本可在onlinedbg 获得。
推荐阅读
- java - 如何使用 kafka 流加入主题
- javascript - 如何为元素设置动画以跟随 div 内的鼠标移动?
- python - 无法运行 mvn (Maven) 命令,因为目录中没有 pom.xml,但 pom.xml 没有出现在搜索中?
- javascript - 使用 Javascript 检测用户国家,并显示新的 div
- python - Python cd 在没有库的文件夹中
- android - SyncAdapter onPerformSync 没有被调用
- python - 使用字符串变量指定用于新线程的函数 | Python3
- windows - 使用 WAMP 和 URI 的精确站点图像
- c# - 如何为 .NET 项目中的单元测试创建 GitHub Actions?
- c# - 如何将 asp-validation-for 连接到我的新错误