sigs.k8s.io/cluster-api-provider-aws@v1.5.5/pkg/hash/base36.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package hash 18 19 import ( 20 "github.com/pkg/errors" 21 "golang.org/x/crypto/blake2b" 22 _ "k8s.io/apimachinery/pkg/util/intstr" // keep the blank import to include intstr. 23 ) 24 25 const base36set = "0123456789abcdefghijklmnopqrstuvwxyz" 26 27 // Base36TruncatedHash returns a consistent hash using blake2b 28 // and truncating the byte values to alphanumeric only 29 // of a fixed length specified by the consumer. 30 func Base36TruncatedHash(str string, length int) (string, error) { 31 hasher, err := blake2b.New(length, nil) 32 if err != nil { 33 return "", errors.Wrap(err, "unable to create hash function") 34 } 35 36 if _, err := hasher.Write([]byte(str)); err != nil { 37 return "", errors.Wrap(err, "unable to write hash") 38 } 39 return base36Truncate(hasher.Sum(nil)), nil 40 } 41 42 // base36Truncate returns a string that is base36 compliant 43 // It is not an encoding since it returns a same-length string 44 // for any byte value. 45 func base36Truncate(bytes []byte) string { 46 var chars string 47 for _, bite := range bytes { 48 idx := int(bite) % 36 49 chars += string(base36set[idx]) 50 } 51 52 return chars 53 }