github.com/zorawar87/trillian@v1.2.1/merkle/rfc6962/rfc6962.go (about)

     1  // Copyright 2016 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package rfc6962 provides hashing functionality according to RFC6962.
    16  package rfc6962
    17  
    18  import (
    19  	"crypto"
    20  	_ "crypto/sha256" // SHA256 is the default algorithm.
    21  
    22  	"github.com/google/trillian"
    23  	"github.com/google/trillian/merkle/hashers"
    24  )
    25  
    26  func init() {
    27  	hashers.RegisterLogHasher(trillian.HashStrategy_RFC6962_SHA256, New(crypto.SHA256))
    28  }
    29  
    30  // Domain separation prefixes
    31  const (
    32  	RFC6962LeafHashPrefix = 0
    33  	RFC6962NodeHashPrefix = 1
    34  )
    35  
    36  // DefaultHasher is a SHA256 based LogHasher.
    37  var DefaultHasher = New(crypto.SHA256)
    38  
    39  // Hasher implements the RFC6962 tree hashing algorithm.
    40  type Hasher struct {
    41  	crypto.Hash
    42  }
    43  
    44  // New creates a new Hashers.LogHasher on the passed in hash function.
    45  func New(h crypto.Hash) *Hasher {
    46  	return &Hasher{Hash: h}
    47  }
    48  
    49  // EmptyRoot returns a special case for an empty tree.
    50  func (t *Hasher) EmptyRoot() []byte {
    51  	return t.New().Sum(nil)
    52  }
    53  
    54  // HashLeaf returns the Merkle tree leaf hash of the data passed in through leaf.
    55  // The data in leaf is prefixed by the LeafHashPrefix.
    56  func (t *Hasher) HashLeaf(leaf []byte) ([]byte, error) {
    57  	h := t.New()
    58  	h.Write([]byte{RFC6962LeafHashPrefix})
    59  	h.Write(leaf)
    60  	return h.Sum(nil), nil
    61  }
    62  
    63  // HashChildren returns the inner Merkle tree node hash of the the two child nodes l and r.
    64  // The hashed structure is NodeHashPrefix||l||r.
    65  func (t *Hasher) HashChildren(l, r []byte) []byte {
    66  	h := t.New()
    67  	h.Write([]byte{RFC6962NodeHashPrefix})
    68  	h.Write(l)
    69  	h.Write(r)
    70  	return h.Sum(nil)
    71  }