In my Arduino project I want to compute the SHA256 hash of a string and store the result to a string, and do this recursively many times (i.e. compute hash of hash of hash etc...). So my goal is to have a reliable function as follows:
String h(String input) {
...
return output;
}
where for example h("abc") would return "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".
I downloaded this library (from Tools->Manage libraries, it is also in github) and then ran the example in TestSHA256.ino which passes all the checks. However I'm stuggling to make my function work since the library doesn't have a specific example on how to compute and return a SHA256 hash.
I have been looking in function testHash_N() in TestSHA256.ino, which appears to create a hash (from struct TestHashVector data) and compare it with the precomputed hash (from struct TestHashVector hash[]).
The hash seems to be computed in lines 89-96 in TestSHA256.ino. I just want to take the actual hash string result, so for testVectorSHA256_1 in the example, I would need to have a string = "ba7816bf....15ad" as the result.
I understand that this is related to memory referencing in Arduino but I'm not experienced so I'd be grateful if you helped me with this.
EDIT: My code snippet so far is as follows, but it doesn't output the correct hash..
#include <Crypto.h>
#include <SHA256.h>
#include <string.h>
#define HASH_SIZE 32
#define BLOCK_SIZE 64
char hex[256];
char *hashvalue;
SHA256 sha256;
byte buffer[128];
char *btoh(char *dest, uint8_t *src, int len) {
char *d = dest;
while( len-- ) sprintf(d, "%02x", (unsigned char)*src++), d += 2;
return dest;
}
char* h(Hash *hash, char* hashvalue)
{
size_t size = sizeof(&hashvalue);
size_t posn, len;
size_t inc = sizeof(&hashvalue);
uint8_t value[HASH_SIZE];
hash->reset();
for (posn = 0; posn < size; posn += inc) {
len = size - posn;
if (len > inc)
len = inc;
hash->update(&hashvalue + posn, len);
}
hash->finalize(value, sizeof(value));
return(btoh(hex, value, 32));
}
void setup()
{
Serial.begin(115200);
bool tmp;
char *testvalue = "abc";
Serial.println(h(&sha256,*testvalue));
}
void loop()
{
}
sizeof(&hashvalue);
is not the length of the string. It is the number of bytes of a pointer.*testvalue
in the statementh(&sha256,*testvalue));
is not a pointer. It is actually the value of the first character,a
in thetestvalue
.uint8_t value[HASH_SIZE];
is a local value and cannot be returned.static uint8_t value[HASH_SIZE];
will allow that.