github.com/bartle-stripe/trillian@v1.2.1/testonly/hasher.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 testonly 16 17 // This file implements the hashing functions that are part of a Trillian 18 // personality. 19 20 import ( 21 "crypto/sha256" 22 ) 23 24 // HashKey converts a map key into a map index using SHA256. 25 // This preserves tests that precomputed indexes based on SHA256. 26 func HashKey(key string) []byte { 27 h := sha256.New() 28 h.Write([]byte(key)) 29 return h.Sum(nil) 30 } 31 32 // TransparentHash returns a key that can be visually inspected. 33 // This supports testing where it was nice to see what the key was. 34 func TransparentHash(key string) []byte { 35 const prefixLen = 8 36 if prefixLen+len(key) > sha256.Size { 37 panic("key too long") 38 } 39 b := make([]byte, sha256.Size) 40 // Put some hashed bytes before the key so that key values are 41 // a bit more widely distributed around the Merkle tree. 42 h := HashKey(key) 43 copy(b[0:prefixLen], h[0:prefixLen]) 44 copy(b[prefixLen:], key) 45 return b 46 }