rweather / arduinolibs

Arduino Cryptography Library
444 stars 212 forks source link

Hashing Problem #59

Closed RicardoPires19 closed 4 years ago

RicardoPires19 commented 4 years ago

There seems to be a problem with the hashing method when reading from a file. In this case I'm using SHA256. When I open a file and read its contents and update the hash, the resulting value is wrong.

I don't understand what I'm doing wrong or if its a bug, but I can't get the correct value by reading a file and updating the hash. This is my function:

bool calculate_file_hash(char* path, byte* result) {
  File f = SD.open(path, FILE_READ);
  if (!f) {
    return false;
  }

  SHA256 hash;
  hash.clear();
  hash.reset();

  while(f.available()){
    hash.update(f.read(), 1);
    if(f.peek() < 0)
      break;
  }
  f.close();
  hash.finalize(result, 32);

  return true;
}

It reads 1 byte and updates the hash. I've also tried reading chunks of 128 bytes, but it produces a different incorrect hash. When I transfer a file over serial and update the hash with successive 128 bytes, the final hash is correct. For some reason, reading a file with the SD.h library just doesn't work. In fact simply changing the filename from "t.txt" to "/t.txt" produces a different hash. Am I doing anything wrong?

rweather commented 4 years ago

I believe that f.read() reads and returns a single character. But the hash.update() function expects a pointer as its argument. So it is turning the character into a pointer and reading whatever rubbish was at that position in memory. You should probably do something like this instead:

char ch = f.read(); hash.update(&ch, 1);

RicardoPires19 commented 4 years ago

Thanks, that fixed the problem. I'll be closing the issue now.