How to resolve the algorithm SHA-256 Merkle tree step by step in the Nim programming language
How to resolve the algorithm SHA-256 Merkle tree step by step in the Nim programming language
Table of Contents
Problem Statement
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload). Implement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm SHA-256 Merkle tree step by step in the Nim programming language
Source code in the nim programming language
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]
You may also check:How to resolve the algorithm Averages/Median step by step in the AntLang programming language
You may also check:How to resolve the algorithm Non-decimal radices/Input step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Forest fire step by step in the Wren programming language
You may also check:How to resolve the algorithm Yellowstone sequence step by step in the Perl programming language
You may also check:How to resolve the algorithm First class environments step by step in the EchoLisp programming language