github.com/wangyougui/gf/v2@v2.6.5/crypto/gmd5/gmd5.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 // Package gmd5 provides useful API for MD5 encryption algorithms. 8 package gmd5 9 10 import ( 11 "crypto/md5" 12 "fmt" 13 "io" 14 "os" 15 16 "github.com/wangyougui/gf/v2/errors/gerror" 17 "github.com/wangyougui/gf/v2/util/gconv" 18 ) 19 20 // Encrypt encrypts any type of variable using MD5 algorithms. 21 // It uses gconv package to convert `v` to its bytes type. 22 func Encrypt(data interface{}) (encrypt string, err error) { 23 return EncryptBytes(gconv.Bytes(data)) 24 } 25 26 // MustEncrypt encrypts any type of variable using MD5 algorithms. 27 // It uses gconv package to convert `v` to its bytes type. 28 // It panics if any error occurs. 29 func MustEncrypt(data interface{}) string { 30 result, err := Encrypt(data) 31 if err != nil { 32 panic(err) 33 } 34 return result 35 } 36 37 // EncryptBytes encrypts `data` using MD5 algorithms. 38 func EncryptBytes(data []byte) (encrypt string, err error) { 39 h := md5.New() 40 if _, err = h.Write(data); err != nil { 41 err = gerror.Wrap(err, `hash.Write failed`) 42 return "", err 43 } 44 return fmt.Sprintf("%x", h.Sum(nil)), nil 45 } 46 47 // MustEncryptBytes encrypts `data` using MD5 algorithms. 48 // It panics if any error occurs. 49 func MustEncryptBytes(data []byte) string { 50 result, err := EncryptBytes(data) 51 if err != nil { 52 panic(err) 53 } 54 return result 55 } 56 57 // EncryptString encrypts string `data` using MD5 algorithms. 58 func EncryptString(data string) (encrypt string, err error) { 59 return EncryptBytes([]byte(data)) 60 } 61 62 // MustEncryptString encrypts string `data` using MD5 algorithms. 63 // It panics if any error occurs. 64 func MustEncryptString(data string) string { 65 result, err := EncryptString(data) 66 if err != nil { 67 panic(err) 68 } 69 return result 70 } 71 72 // EncryptFile encrypts file content of `path` using MD5 algorithms. 73 func EncryptFile(path string) (encrypt string, err error) { 74 f, err := os.Open(path) 75 if err != nil { 76 err = gerror.Wrapf(err, `os.Open failed for name "%s"`, path) 77 return "", err 78 } 79 defer f.Close() 80 h := md5.New() 81 _, err = io.Copy(h, f) 82 if err != nil { 83 err = gerror.Wrap(err, `io.Copy failed`) 84 return "", err 85 } 86 return fmt.Sprintf("%x", h.Sum(nil)), nil 87 } 88 89 // MustEncryptFile encrypts file content of `path` using MD5 algorithms. 90 // It panics if any error occurs. 91 func MustEncryptFile(path string) string { 92 result, err := EncryptFile(path) 93 if err != nil { 94 panic(err) 95 } 96 return result 97 }