SHA-256 Merkle tree: Difference between revisions

Content added Content deleted
m (Thundergnat moved page SHA-256 Merkle Tree to SHA-256 Merkle tree: Follow normal task title capitalization policy)
(Added Go)
Line 5: Line 5:


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 [https://{{SERVERNAME}}/mw/title.png the RosettaCode title image] with that block size. The final result should be the hexadecimal digest value <tt style="font-weight:bold">a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</tt>.
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 [https://{{SERVERNAME}}/mw/title.png the RosettaCode title image] with that block size. The final result should be the hexadecimal digest value <tt style="font-weight:bold">a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c</tt>.

=={{header|Go}}==
<lang go>package main

import (
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)

func main() {
const bufferSize = 1024
f, err := os.Open("title.png")
if err != nil {
log.Fatal(err)
}
defer f.Close()

var hashes [][]byte
buffer := make([]byte, 1024)
h := sha256.New()
for {
bytesRead, err := f.Read(buffer)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
h.Reset()
h.Write(buffer[:bytesRead])
hashes = append(hashes, h.Sum(nil))
}
for len(hashes) > 1 {
var hashes2 [][]byte
for i := 0; i < len(hashes); i += 2 {
if i < len(hashes)-1 {
buffer := make([]byte, 64)
copy(buffer, hashes[i])
copy(buffer[32:], hashes[i+1])
h.Reset()
h.Write(buffer)
hashes2 = append(hashes2, h.Sum(nil))
} else {
hashes2 = append(hashes2, hashes[i])
}
}
hashes = hashes2
}
fmt.Printf("%x", hashes[0])
fmt.Println()
}</lang>

{{out}}
<pre>
a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c
</pre>


=={{header|Raku}}==
=={{header|Raku}}==