github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/coder/hash.go (about) 1 package coder 2 3 import ( 4 "crypto/hmac" 5 "crypto/md5" 6 "crypto/sha1" 7 "crypto/sha256" 8 "fmt" 9 "io" 10 "os" 11 ) 12 13 func MD5String(s string) string { 14 b := md5.Sum([]byte(s)) 15 return fmt.Sprintf("%x", b) 16 } 17 18 func MD5File(filePath string) (string, error) { 19 if file, err := os.Open(filePath); err == nil { 20 m := md5.New() 21 _, _ = io.Copy(m, file) 22 return fmt.Sprintf("%x", m.Sum(nil)), nil 23 } else { 24 return "", err 25 } 26 } 27 28 func Sha1String(s string) string { 29 b := sha1.Sum([]byte(s)) 30 return fmt.Sprintf("%x", b) 31 } 32 33 func Sha1File(filePath string) (string, error) { 34 if file, err := os.Open(filePath); err == nil { 35 s := sha1.New() 36 _, _ = io.Copy(s, file) 37 return fmt.Sprintf("%x", s.Sum(nil)), nil 38 } else { 39 return "", err 40 } 41 42 } 43 44 func Sha256String(s string) string { 45 b := sha256.Sum256([]byte(s)) 46 return fmt.Sprintf("%x", b) 47 } 48 49 func Sha256File(filePath string) (string, error) { 50 if file, err := os.Open(filePath); err == nil { 51 s := sha256.New() 52 _, _ = io.Copy(s, file) 53 return fmt.Sprintf("%x", s.Sum(nil)), nil 54 } else { 55 return "", err 56 } 57 } 58 59 func HMacMD5String(s string, key string) string { 60 h := hmac.New(md5.New, []byte(key)) 61 h.Write([]byte(s)) 62 return fmt.Sprintf("%x", h.Sum(nil)) 63 } 64 65 func HMacMD5File(filePath string, key string) (string, error) { 66 if file, err := os.Open(filePath); err == nil { 67 h := hmac.New(md5.New, []byte(key)) 68 _, _ = io.Copy(h, file) 69 return fmt.Sprintf("%x", h.Sum(nil)), nil 70 } else { 71 return "", err 72 } 73 } 74 75 func HMacSha1String(s string, key string) string { 76 h := hmac.New(sha1.New, []byte(key)) 77 h.Write([]byte(s)) 78 return fmt.Sprintf("%x", h.Sum(nil)) 79 } 80 81 func HMacSha1File(filePath string, key string) (string, error) { 82 if file, err := os.Open(filePath); err == nil { 83 h := hmac.New(sha1.New, []byte(key)) 84 _, _ = io.Copy(h, file) 85 return fmt.Sprintf("%x", h.Sum(nil)), nil 86 } else { 87 return "", err 88 } 89 } 90 91 func HMacSha256String(s string, key string) string { 92 h := hmac.New(sha256.New, []byte(key)) 93 h.Write([]byte(s)) 94 return fmt.Sprintf("%x", h.Sum(nil)) 95 } 96 97 func HMacSha256File(filePath string, key string) (string, error) { 98 if file, err := os.Open(filePath); err == nil { 99 h := hmac.New(sha256.New, []byte(key)) 100 _, _ = io.Copy(h, file) 101 return fmt.Sprintf("%x", h.Sum(nil)), nil 102 } else { 103 return "", err 104 } 105 }