cuelang.org/go@v0.10.1/pkg/crypto/hmac/hmac.go (about) 1 // Copyright 2021 CUE Authors 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 hmac implements the Keyed-Hash Message Authentication Code (HMAC) as 16 // defined in U.S. Federal Information Processing Standards Publication 198. 17 // 18 // An HMAC is a cryptographic hash that uses a key to sign a message. 19 // The receiver verifies the hash by recomputing it using the same key. 20 package hmac 21 22 import ( 23 "crypto/hmac" 24 "crypto/md5" 25 "crypto/sha1" 26 "crypto/sha256" 27 "crypto/sha512" 28 "fmt" 29 "hash" 30 ) 31 32 const ( 33 MD5 = "MD5" 34 SHA1 = "SHA1" 35 SHA224 = "SHA224" 36 SHA256 = "SHA256" 37 SHA384 = "SHA384" 38 SHA512 = "SHA512" 39 SHA512_224 = "SHA512_224" 40 SHA512_256 = "SHA512_256" 41 ) 42 43 // Sign returns the HMAC signature of the data, using the provided key and hash function. 44 // 45 // Supported hash functions: "MD5", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA512_224", 46 // and "SHA512_256". 47 func Sign(hashName string, key []byte, data []byte) ([]byte, error) { 48 hash, err := hashFromName(hashName) 49 if err != nil { 50 return nil, err 51 } 52 mac := hmac.New(hash, key) 53 mac.Write(data) 54 return mac.Sum(nil), nil 55 } 56 57 func hashFromName(hash string) (func() hash.Hash, error) { 58 switch hash { 59 case MD5: 60 return md5.New, nil 61 case SHA1: 62 return sha1.New, nil 63 case SHA224: 64 return sha256.New224, nil 65 case SHA256: 66 return sha256.New, nil 67 case SHA384: 68 return sha512.New384, nil 69 case SHA512: 70 return sha512.New, nil 71 case SHA512_224: 72 return sha512.New512_224, nil 73 case SHA512_256: 74 return sha512.New512_256, nil 75 } 76 return nil, fmt.Errorf("unsupported hash function") 77 }