github.com/mre-fog/trillianxx@v1.1.2-0.20180615153820-ae375a99d36a/merkle/objhasher/objhasher.go (about) 1 // Copyright 2017 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 objhasher provides generic object hashing functionality. 16 package objhasher 17 18 import ( 19 "crypto" 20 "fmt" 21 22 "github.com/benlaurie/objecthash/go/objecthash" 23 "github.com/google/trillian" 24 "github.com/google/trillian/merkle/hashers" 25 "github.com/google/trillian/merkle/rfc6962" 26 ) 27 28 func init() { 29 hashers.RegisterLogHasher(trillian.HashStrategy_OBJECT_RFC6962_SHA256, NewLogHasher(rfc6962.New(crypto.SHA256))) 30 } 31 32 type objmaphasher struct { 33 hashers.MapHasher 34 } 35 36 type objloghasher struct { 37 hashers.LogHasher 38 } 39 40 // NewMapHasher returns a new ObjectHasher based on the passed in MapHasher 41 func NewMapHasher(baseHasher hashers.MapHasher) hashers.MapHasher { 42 return &objmaphasher{ 43 MapHasher: baseHasher, 44 } 45 } 46 47 // NewLogHasher returns a new ObjectHasher based on the passed in MapHasher 48 func NewLogHasher(baseHasher hashers.LogHasher) hashers.LogHasher { 49 return &objloghasher{ 50 LogHasher: baseHasher, 51 } 52 } 53 54 // HashLeaf returns the object hash of leaf, which must be a JSON object. 55 func (o *objloghasher) HashLeaf(leaf []byte) ([]byte, error) { 56 hash, err := objecthash.CommonJSONHash(string(leaf)) 57 if err != nil { 58 return nil, fmt.Errorf("CommonJSONHash(%s): %v", leaf, err) 59 } 60 return hash[:], err 61 } 62 63 // HashLeaf returns the object hash of leaf, which must be a JSON object. 64 func (o *objmaphasher) HashLeaf(treeID int64, index []byte, leaf []byte) ([]byte, error) { 65 hash, err := objecthash.CommonJSONHash(string(leaf)) 66 if err != nil { 67 return nil, fmt.Errorf("CommonJSONHash(%s): %v", leaf, err) 68 } 69 return hash[:], nil 70 }