golib/crypto/gsha1/sha1.go

56 lines
1.1 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// sha1.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package gsha1
import (
2023-08-12 21:29:17 +08:00
"crypto/hmac"
2023-06-15 21:22:51 +08:00
"crypto/sha1"
"encoding/hex"
"io"
"os"
)
// Encrypt encrypts any type of variable using SHA1 algorithms.
// It uses package gconv to convert `v` to its bytes type.
func Encrypt(in string) string {
r := sha1.Sum([]byte(in))
return hex.EncodeToString(r[:])
}
// EncryptFile encrypts file content of `path` using SHA1 algorithms.
func EncryptFile(path string) (encrypt string, err error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha1.New()
_, err = io.Copy(h, f)
if err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// MustEncryptFile encrypts file content of `path` using SHA1 algorithms.
// It panics if any error occurs.
func MustEncryptFile(path string) string {
result, err := EncryptFile(path)
if err != nil {
panic(err)
}
return result
}
2023-08-12 21:29:17 +08:00
// hmac sha1
func HmacSha1(in, key []byte) []byte {
h := hmac.New(sha1.New, key)
h.Write(in)
return h.Sum(nil)
}