概述:计算 sha1 C++ 版

0x01 说明

鉴于个人使用的目的,在 Github 上找了些许开源 sha1 计算的项目,最后使用 vog/sha1 这个项目计算出来相关结果,使用比较简单,fork了一个 vs 版本记录一下。

仓库地址:holdyounger/SHA1: sha1 implementation in C++, fork by vog/sha1

0x02 使用

如下所示,使用比较简单

  1. 计算文本 sha1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void test_other()
{
SHA1 checksum;

cout << endl;
cout << "Test: No string" << endl;
compare(checksum.final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709");

cout << endl;
checksum.update("");
cout << "Test: Empty string" << endl;
compare(checksum.final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709");

cout << endl;
cout << "Test: abcde" << endl;
checksum.update("abcde");
compare(checksum.final(), "03de6c570bfe24bfc328ccd7ca46b76eadaf4334");

cout << endl;
cout << "Test: Two concurrent checksum calculations" << endl;
SHA1 checksum1, checksum2;
checksum1.update("abc");
compare(checksum2.final(), "da39a3ee5e6b4b0d3255bfef95601890afd80709"); /* "" */
compare(checksum1.final(), "a9993e364706816aba3e25717850c26c9cd0d89d"); /* "abc" */

cout << endl;
cout << "Test: a [00] b [7F] c [80] d [FF] e [C3] [F0] f" << endl;
checksum.update(std::string("a" "\x00" "b" "\x7f" "c" "\x80" "d" "\xff" "e" "\xc3\xf0" "f", 12));
compare(checksum.final(), "cd0dd10814c0d4f9c6a2a0a4be2304d2371468d3");
}
  1. 计算文件
1
2
3
4
void test_file(const string &filename)
{
cout << SHA1::from_file(filename) << " *" << filename << endl;
}

0x03 结果校验

以下是计算结果,与 Hash.exe 计算结果一直。