|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/sha1"
|
|
|
|
"crypto/sha256"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/pem"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/Luzifer/go-openssl/v3"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SHA1 回傳sha1加密
|
|
|
|
func SHA1(v string) string {
|
|
|
|
h := sha1.New()
|
|
|
|
h.Write([]byte(v))
|
|
|
|
bs := h.Sum(nil)
|
|
|
|
return fmt.Sprintf("%x", bs)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SHA256 回傳sha256加密
|
|
|
|
func SHA256(v string) string {
|
|
|
|
h := sha256.New()
|
|
|
|
h.Write([]byte(v))
|
|
|
|
bs := h.Sum(nil)
|
|
|
|
return fmt.Sprintf("%x", bs)
|
|
|
|
}
|
|
|
|
|
|
|
|
// EncryptPassword 加密密碼
|
|
|
|
func EncryptPassword(pwd string) (string, error) {
|
|
|
|
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return string(hash), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CheckPassword 檢查密碼
|
|
|
|
func CheckPassword(pwd, hash string) error {
|
|
|
|
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
|
|
|
|
}
|
|
|
|
|
|
|
|
// EncryptAES aes加密
|
|
|
|
func EncryptAES(value, key string) ([]byte, error) {
|
|
|
|
o := openssl.New()
|
|
|
|
|
|
|
|
enc, err := o.EncryptBytes(key, []byte(value), openssl.DigestMD5Sum)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return enc, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecryptAES aes解密
|
|
|
|
func DecryptAES(value, key string) ([]byte, error) {
|
|
|
|
o := openssl.New()
|
|
|
|
|
|
|
|
dec, err := o.DecryptBytes(key, []byte(value), openssl.DigestMD5Sum)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return dec, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// EncryptRSA rsa加密
|
|
|
|
func EncryptRSA(value, publicKey []byte) ([]byte, error) {
|
|
|
|
block, _ := pem.Decode(publicKey)
|
|
|
|
if block == nil {
|
|
|
|
return nil, errors.New("public key error")
|
|
|
|
}
|
|
|
|
|
|
|
|
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pub := pubInterface.(*rsa.PublicKey)
|
|
|
|
return rsa.EncryptPKCS1v15(rand.Reader, pub, value)
|
|
|
|
}
|
|
|
|
|
|
|
|
// DecryptRSA rsa解密
|
|
|
|
func DecryptRSA(ciphertext, privateKey []byte) ([]byte, error) {
|
|
|
|
block, _ := pem.Decode(privateKey)
|
|
|
|
if block == nil {
|
|
|
|
return nil, errors.New("private key error")
|
|
|
|
}
|
|
|
|
|
|
|
|
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
|
|
|
|
}
|