github.com/searKing/golang/go@v1.2.117/crypto/hmac/hmac.go (about) 1 // Copyright 2021 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package hmac 6 7 import ( 8 "bytes" 9 "crypto/hmac" 10 "encoding/hex" 11 "hash" 12 "io" 13 "log" 14 "os" 15 ) 16 17 func MySelf(hasher func() hash.Hash, key []byte) ([]byte, error) { 18 f, err := os.Open(os.Args[0]) 19 if err != nil { 20 log.Fatal(err) 21 } 22 defer f.Close() 23 24 h := hmac.New(hasher, key) 25 if _, err := io.Copy(h, f); err != nil { 26 return nil, err 27 } 28 29 return h.Sum(nil), nil 30 } 31 32 func SumBytes(hasher func() hash.Hash, key []byte, b []byte) []byte { 33 h := hmac.New(hasher, key) 34 h.Write(b) 35 return h.Sum(nil) 36 } 37 38 func SumString(hasher func() hash.Hash, key []byte, b string) string { 39 return string(SumBytes(hasher, key, []byte(b))) 40 } 41 42 func SumHex(hasher func() hash.Hash, key []byte, b string) string { 43 return hex.EncodeToString(SumBytes(hasher, key, []byte(b))) 44 } 45 46 func SumReader(hasher func() hash.Hash, key []byte, r io.Reader) ([]byte, error) { 47 h := hmac.New(hasher, key) 48 if _, err := io.Copy(h, r); err != nil { 49 return nil, err 50 } 51 52 return h.Sum(nil), nil 53 } 54 55 func SumFile(hasher func() hash.Hash, key []byte, name string) ([]byte, error) { 56 f, err := os.Open(name) 57 if err != nil { 58 return nil, err 59 } 60 defer f.Close() 61 return SumReader(hasher, key, f) 62 } 63 64 func SumReaderAt(hasher func() hash.Hash, key []byte, r io.ReaderAt, offset, size int64, buf []byte) ([]byte, error) { 65 h := hmac.New(hasher, key) 66 if len(buf) == 0 { 67 buf = make([]byte, 1024) 68 } 69 70 var total int64 71 for total < size { 72 n, err := r.ReadAt(buf, offset) 73 if err != nil { 74 return nil, err 75 } 76 offset += int64(n) 77 total += int64(n) 78 var copied int64 79 for copied < int64(n) { 80 copiedCount, err := io.CopyN(h, bytes.NewReader(buf), int64(n)) 81 if err != nil { 82 return nil, err 83 } 84 copied += copiedCount 85 } 86 } 87 88 return h.Sum(nil), nil 89 } 90 91 // SumFileAt return ms5sum of data by offset and len is size 92 // buf is a buffer to read from file every time. 93 func SumFileAt(hasher func() hash.Hash, key []byte, name string, offset, size int64, buf []byte) ([]byte, error) { 94 f, err := os.Open(name) 95 if err != nil { 96 return nil, err 97 } 98 defer f.Close() 99 return SumReaderAt(hasher, key, f, offset, size, buf) 100 }