Hi,
I'm trying to make sha256 hashes on files. For testing purposes I generate a file with
dd if=/dev/urandom of=file.bin bs=1K count=20
This is the code
import system, nimSHA2, os, strutils
proc main(): string =
const blockSize = 8192
var bytesRead: int = 0
var buffer: array[blockSize, char]
var f: File = open("./file.bin")
var sha: SHA256
sha.initSHA()
bytesRead = f.readBuffer(buffer.addr, blockSize)
while bytesRead > 0:
echo bytesRead
sha.update($buffer)
bytesRead = f.readBuffer(buffer.addr, blockSize)
let digest = sha.final()
result = digest.hex()
when isMainModule:
echo main()
Hex results:
my code: E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855
sha256sum -b file.bin: cc61635da46b2c9974335ea37e0b5fd660a5c8a42a89b271fa7ec2ac4b8b26f6
I think the error may be at the array[blockSize, char] and $buffer conversion.
PS: I am sorry for my noob question.
Update 1: I changed the file generation from /dev/zero to /dev/urandom. The result is the same.
I have to admit that I know nothing about nimSHA2 module. But a very short look at your code shows:
while bytesRead > 0:
sha.update($buffer)
So my feeling is, that you always call update() on the full buffer, even when only a part of the buffer is actually read. I may be wrong, but I have the feeling that that should not work in the general case. How does sha.update() discover actual buffer size? By zero byte? And what when data contains zero?
Hi Stefan,
thanks for the hint. I will digg deeper to find the problem.
I think this ( below ) works but IMO this library should provide a way works on arrays, not strings. This is inefficient.
import nimSHA2, os, strutils
proc main(): string =
const blockSize = 8192
var bytesRead: int = 0
var buffer: string
var f: File = open("./file.bin")
var sha: SHA256
sha.initSHA()
buffer = newString(blockSize)
bytesRead = f.readBuffer(buffer[0].addr, blockSize)
setLen(buffer,bytesRead)
while bytesRead > 0:
echo bytesRead
sha.update(buffer)
setLen(buffer,blockSize)
bytesRead = f.readBuffer(buffer[0].addr, blockSize)
setLen(buffer,bytesRead)
let digest = sha.final()
result = digest.hex()
when isMainModule:
echo main()