github.com/zhongdalu/gf@v1.0.0/g/crypto/gmd5/gmd5.go (about) 1 // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/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/zhongdalu/gf/g/errors/gerror" 17 "github.com/zhongdalu/gf/g/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(v interface{}) (encrypt string, err error) { 23 h := md5.New() 24 if _, err = h.Write([]byte(gconv.Bytes(v))); err != nil { 25 return "", err 26 } 27 return fmt.Sprintf("%x", h.Sum(nil)), nil 28 } 29 30 // EncryptString is alias of Encrypt. 31 // Deprecated. 32 func EncryptString(v string) (encrypt string, err error) { 33 return Encrypt(v) 34 } 35 36 // EncryptFile encrypts file content of <path> using MD5 algorithms. 37 func EncryptFile(path string) (encrypt string, err error) { 38 f, err := os.Open(path) 39 if err != nil { 40 return "", err 41 } 42 defer func() { 43 err = gerror.Wrap(f.Close(), "file closing error") 44 }() 45 h := md5.New() 46 _, err = io.Copy(h, f) 47 if err != nil { 48 return "", err 49 } 50 return fmt.Sprintf("%x", h.Sum(nil)), nil 51 }