github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/hash/writer.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package hash 19 20 import ( 21 "crypto" 22 "fmt" 23 "hash" 24 "sort" 25 "strings" 26 ) 27 28 var name2Hash = map[string]crypto.Hash{} 29 30 // ----------------------------------------------------------------------------- 31 32 func init() { 33 name2Hash["md4"] = crypto.MD4 34 name2Hash["md5"] = crypto.MD5 35 name2Hash["sha1"] = crypto.SHA1 36 name2Hash["sha224"] = crypto.SHA224 37 name2Hash["sha256"] = crypto.SHA256 38 name2Hash["sha512"] = crypto.SHA512 39 name2Hash["sha512/224"] = crypto.SHA512_224 40 name2Hash["sha512/256"] = crypto.SHA512_256 41 name2Hash["blake2b-256"] = crypto.BLAKE2b_256 42 name2Hash["blake2b-384"] = crypto.BLAKE2b_384 43 name2Hash["blake2b-512"] = crypto.BLAKE2b_512 44 name2Hash["blake2s-256"] = crypto.BLAKE2s_256 45 name2Hash["ripemd160"] = crypto.RIPEMD160 46 name2Hash["sha3-224"] = crypto.SHA3_224 47 name2Hash["sha3-256"] = crypto.SHA3_256 48 name2Hash["sha3-384"] = crypto.SHA3_384 49 name2Hash["sha3-512"] = crypto.SHA3_512 50 } 51 52 // NewHasher returns a hasher instance. 53 func NewHasher(algorithm string) (hash.Hash, error) { 54 // Normalize input 55 algorithm = strings.TrimSpace(strings.ToLower(algorithm)) 56 57 // Resolve algorithm 58 hf, ok := name2Hash[algorithm] 59 if !ok { 60 return nil, fmt.Errorf("unsupported hash algorithm %q", algorithm) 61 } 62 if !hf.Available() { 63 return nil, fmt.Errorf("hash algorithm %q is not available", algorithm) 64 } 65 66 // Build hash instance. 67 h := hf.New() 68 69 // No error 70 return h, nil 71 } 72 73 // SupportedAlgorithms returns the available hash algorithms. 74 func SupportedAlgorithms() []string { 75 res := []string{} 76 for n, c := range name2Hash { 77 if c.Available() { 78 res = append(res, n) 79 } 80 } 81 82 // Sort all algorithms 83 sort.Strings(res) 84 85 return res 86 }