我想散列一个字符串,但是看看MSDN上的例子我被卡在了DATA_SIZE上。这是什么?如果明文的长度不同,我怎么提前知道数组的大小是什么?
此外,我需要将结果作为向量返回(消费方法需要这个)
array<Byte>^ data = gcnew array<Byte>( DATA_SIZE );
array<Byte>^ result;
SHA1^ sha = gcnew SHA1CryptoServiceProvider;
// This is one implementation of the abstract class SHA1.
result = sha->ComputeHash( data );
到目前为止我的方法看起来像
std::vector<byte> sha1(const std::string& plaintext)
{
//#define SHA1_BUFFER_SIZE ????
//array<System::Byte>^ data = gcnew array<System::Byte>(DATA_SIZE);
//convert plaintext string to byte array
array<System::Byte>^ result;
SHA1^ sha = gcnew SHA1CryptoServiceProvider;
result = sha->ComputeHash(data);
//return result as a vector<byte>
}
答案 0 :(得分:1)
首先,回答你的问题:
此示例假定存在预定义的常量DATA_SIZE。
因此,假设有 #define 或枚举常量预定义
如果您希望函数接收std:string作为输入并输出std :: vector,则需要执行许多步骤。它看起来像那样:
std::vector<unsigned char> sha1(const std::string& message)
{
// Steps #1 and #2: convert from std::string to managed string
// and convert from a string to bytes (UTF-8 as example)
array<Byte>^data = Encoding::UTF8->GetBytes(gcnew String(message.c_str() ));
// Steps #3 and #4: perform hash operation
// and store result in a byte array
SHA1^ sha = gcnew SHA1CryptoServiceProvider;
array<Byte>^ array_result = sha->ComputeHash(data);
// Step #5: convert from a managed array
// to unmanaged vector
std::vector<unsigned char> vector_return(array_result->Length);
Marshal::Copy(array_result, 0, IntPtr(&vector_return[0]), array_result->Length);
return vector_return;
}
不要忘记声明您正在使用的命名空间:
using namespace System;
using namespace System::Text;
using namespace System::Security::Cryptography;
using namespace System::Runtime::InteropServices;
int main(array<System::String ^> ^args)
{
std::string str_test("This is just a test.");
std::vector<unsigned char> vec_digest( sha1(str_test) );
return 0;
}
最后的想法: