下面是我在openssl中创建哈希的代码。 我想知道为什么我的输出总是有些不同。
int main()
{
char alg[] = "MD5";
char buf[EVP_MAX_KEY_LENGTH] = "5";
unsigned char *testKey;
unsigned int olen;
testKey = simple_digest(alg, buf, EVP_MAX_KEY_LENGTH,&olen);
std::cout << "Printing key : >>";
print_hex(testKey,EVP_MAX_KEY_LENGTH);
std::cout << "<<" << std::endl;
}
unsigned char *simple_digest(char *alg, char *buf, unsigned int len,unsigned int *olen)
{
const EVP_MD *m;
EVP_MD_CTX ctx;
unsigned char *ret;
OpenSSL_add_all_digests();
if (!(m = EVP_get_digestbyname(alg)))
return NULL;
if (!(ret = (unsigned char *)malloc(EVP_MAX_MD_SIZE)))
return NULL;
EVP_DigestInit(&ctx, m);
EVP_DigestUpdate(&ctx, buf, len);
EVP_DigestFinal(&ctx, ret, olen);
// std::cout << "computed key" << ret << std::endl;
return ret;
}
void print_hex(unsigned char *bs, unsigned int n)
{
int i;
for (i = 0; i < n; i++)
printf("%02x", bs[i]);
printf("\n");
}
输出:
3afb8ebc9c93bf6d40285736f210b7856af8bab4d040ca090043ca09f840ca09
3afb8ebc9c93bf6d40285736f210b7856af8bab490a5f909c0a7f909b8a5f909
正如您所看到的,只有后面几个字符不同。
提前致谢! :d
更新(正确的工作版本):
int main()
{
char alg[] = "MD5";
char buf[EVP_MAX_KEY_LENGTH] = "5";
unsigned char *testKey;
unsigned int olen;
testKey = simple_digest(alg, buf,strlen(buf),&olen);
std::cout << "Printing key : >>";
print_hex(testKey,olen);
std::cout << "<<" << std::endl;
}
unsigned char *simple_digest(char *alg, char *buf, unsigned int len,unsigned int *olen)
{
const EVP_MD *m;
EVP_MD_CTX ctx;
unsigned char *ret;
OpenSSL_add_all_digests();
if (!(m = EVP_get_digestbyname(alg)))
return NULL;
if (!(ret = (unsigned char *)malloc(EVP_MAX_KEY_LENGTH)))
return NULL;
EVP_DigestInit(&ctx, m);
EVP_DigestUpdate(&ctx, buf, len);
EVP_DigestFinal(&ctx, ret, olen);
return ret;
}
void print_hex(unsigned char *bs, unsigned int n)
{
int i;
for (i = 0; i < n; i++)
printf("%02x", bs[i]);
}
输出:
Printing key : >>e4da3b7fbbce2345d7772b0674a318d5<<
答案 0 :(得分:4)
您正在尝试哈希一个字符的字符串“5”,但您告诉EVP_Digest_Update
您的缓冲区长度为EVP_MAX_KEY_LENGTH
。您需要传递缓冲区的实际长度,而不是它可能的最大长度。
为了完整性,以下是您的主要功能:
int main()
{
char alg[] = "MD5";
char buf[EVP_MAX_KEY_LENGTH] = "5";
unsigned char *testKey;
unsigned int olen;
# Pass the true length of but
testKey = simple_digest(alg, buf, strlen(buf), &olen);
std::cout << "Printing key : >>";
# Pass the true length of testKey
print_hex(testKey,olen);
std::cout << "<<" << std::endl;
}
另一个警告:您可能不希望将EVP_MAX_KEY_LENGTH
用于缓冲区,因为这会限制您可以散列的邮件大小。