my goal is to hash with sha256 a string twice, but I don't have a good result Here's the code :
void double_hash(char *string, char output[65]) {
unsigned char out[32];
char hash[65];
unsigned char scnd_hash[65];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(out, &sha256);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i ) {
sprintf(hash (i * 2), "x", out[i]);
}
SHA256_CTX sha256_2;
SHA256_Init(&sha256_2);
SHA256_Update(&sha256_2, hash, strlen(hash));
SHA256_Final(scnd_hash, &sha256_2);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i ) {
sprintf(output (i * 2), "x", scnd_hash[i]);
}
}
With the string "hello" it does :
hello
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
d7914fe546b684688bb95f4f888a92dfc680603a75f23eb823658031fff766d9
But I want :
hello
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50
I've tried with this code but it don't produce the good result :
#include <openssl/sha.h>
#include <stdio.h>
#include <string.h>
void double_hash(char *string, char output[65]) {
unsigned char out[32];
unsigned char scnd_hash[65];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, string, strlen(string));
SHA256_Final(out, &sha256);
SHA256_CTX sha256_2;
SHA256_Init(&sha256_2);
SHA256_Update(&sha256_2, out, strlen((char *)out));
SHA256_Final(scnd_hash, &sha256_2);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i ) {
sprintf(output (i * 2), "x", scnd_hash[i]);
}
}
int main() {
char outp[65];
char *hello = "hello";
double_hash(hello, outp);
printf("%s", outp);
}
It produce
852d59ce6fb3099c9d563870d298f0108eff079e1dde63e66c68d2e0b40353c1
Thank you
CodePudding user response:
To end up with 9595c9df9007...
, perform the 2nd hash on the 32-byte binary data, not on the string.
// SHA256_Update(&sha256_2, hash, strlen(hash));
SHA256_Update(&sha256_2, out, 32);
Ref: SHA256