以下は、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<<