如何使用 cryptopp 进行 sha256 KAT(已知答案测试)?

问题描述 投票:0回答:0

我想使用 cryptopp 库测试 sha256 的已知答案。

在这种情况下,我通过了测试。

Len = 0 Msg = 00 MD = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

但在这种情况下,我没有通过测试。

Len = 1 Msg = 00 MD = bd4f9e98beb68c6ead3243b1b4c7fed75fa4feaab1f84795cbd8a98676a2a375

测试向量

#include <iostream>
#include <string>

#include "cryptopp/cryptlib.h"
#include "cryptopp/hex.h"
#include "cryptopp/filters.h"
#include "cryptopp/sha.h"

using namespace std;
using namespace CryptoPP;

string HexEncode(const string &data)
{
    string result;
    StringSource ss(data, true, new HexEncoder(new StringSink(result)));
    return result;
}

void printTest(string testVector, string result, string expected)
{
    cout << "Test vector:\t" << testVector << endl;
    cout << "Expected:\t" << expected << endl;
    cout << "Result:\t\t" << toLowerCase(result) << endl;
    cout << "Test:\t\t" << checkVerify(result, expected) << endl;
    cout << endl;
}

string sha2_256(string input)
{
    SHA256 hash;
    string result;
    StringSource ss(input, true, new HashFilter(hash, new StringSink(result)));
    return HexEncode(result);
}

int main()
{
    string testVector;
    string input;
    string expected;
    string result;

    testVector = "Len=0, Msg=00";
    input = "\x00";
    expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
    result = sha2_256(input);
    printTest(testVector, result, expected);

    testVector = "Len=1, Msg=00";
    input = "\x00";
    expected = "bd4f9e98beb68c6ead3243b1b4c7fed75fa4feaab1f84795cbd8a98676a2a375";
    result = sha2_256(input);
    printTest(testVector, result, expected);

    return 0;
}

测试向量给出的Msg值相同,但len值不同。我应该怎么做才能摆脱这种情况?

输出如下:

Test vector:    Len=0, Msg=00
Expected:       e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Result:         e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Test:           Verify

Test vector:    Len=1, Msg=00
Expected:       bd4f9e98beb68c6ead3243b1b4c7fed75fa4feaab1f84795cbd8a98676a2a375
Result:         e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Test:           NotVerify
hash sha256 sha crypto++
© www.soinside.com 2019 - 2024. All rights reserved.