golib/crypto/gmd5/md5.go

92 lines
2.0 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// md5.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package gmd5
import (
"crypto/md5"
"fmt"
"io"
"os"
)
// Encrypt encrypts any type of variable using MD5 algorithms.
// It uses gconv package to convert `v` to its bytes type.
func Encrypt(in string) (encrypt string, err error) {
return EncryptBytes([]byte(in))
}
// MustEncrypt encrypts any type of variable using MD5 algorithms.
// It uses gconv package to convert `v` to its bytes type.
// It panics if any error occurs.
func MustEncrypt(in string) string {
result, err := Encrypt(in)
if err != nil {
panic(err)
}
return result
}
// EncryptBytes encrypts `data` using MD5 algorithms.
func EncryptBytes(data []byte) (encrypt string, err error) {
h := md5.New()
if _, err = h.Write(data); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// MustEncryptBytes encrypts `data` using MD5 algorithms.
// It panics if any error occurs.
func MustEncryptBytes(data []byte) string {
result, err := EncryptBytes(data)
if err != nil {
panic(err)
}
return result
}
// EncryptString encrypts string `data` using MD5 algorithms.
func EncryptString(data string) (encrypt string, err error) {
return EncryptBytes([]byte(data))
}
// MustEncryptString encrypts string `data` using MD5 algorithms.
// It panics if any error occurs.
func MustEncryptString(data string) string {
result, err := EncryptString(data)
if err != nil {
panic(err)
}
return result
}
// EncryptFile encrypts file content of `path` using MD5 algorithms.
func EncryptFile(path string) (encrypt string, err error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := md5.New()
_, err = io.Copy(h, f)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// MustEncryptFile encrypts file content of `path` using MD5 algorithms.
// It panics if any error occurs.
func MustEncryptFile(path string) string {
result, err := EncryptFile(path)
if err != nil {
panic(err)
}
return result
}