SHA-256 Merkle tree: Difference between revisions

m (→‎{{header|Phix}}: added syntax colouring the hard way)
Line 474:
</lang>{{out}}
<pre>a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</pre>
 
=={{header|Nim}}==
{{libheader|nimcrypto}}
To compute the digests of file blocks, we use the procedure “digest” which accepts the address of a byte array and a byte count. To compute the digests of pairs of digests, we use instead a SHA256 context and the procedures “update” and “finish”, which avoids a copy in an intermediate buffer.
<lang Nim>
import nimcrypto
 
const BlockSize = 1024
 
var hashes: seq[MDigest[256]]
 
let f = open("title.png")
var buffer: array[BlockSize, byte]
while true:
let n = f.readBytes(buffer, 0, BlockSize)
if n == 0: break
hashes.add sha256.digest(buffer[0].addr, n.uint)
f.close()
 
var ctx: sha256
while hashes.len != 1:
var newHashes: seq[MDigest[256]]
for i in countup(0, hashes.high, 2):
if i < hashes.high:
ctx.init()
ctx.update(hashes[i].data)
ctx.update(hashes[i + 1].data)
newHashes.add ctx.finish()
ctx.clear()
else:
newHashes.add hashes[i]
hashes= newHashes
 
echo hashes[0]</lang>
 
{{out}}
<pre>A4F902CF9D51FE51EDA156A6792E1445DFF65EDF3A217A1F3334CC9CF1495C2C</pre>
 
=={{header|Perl}}==
Anonymous user