Add rsa and sha256

tags/v1.0.5 v1.0.5
Stanly 4 years ago
parent 5c5ed33f43
commit 2b62384dd9

@ -1,7 +1,13 @@
package crypto package crypto
import ( import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1" "crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"fmt" "fmt"
"github.com/Luzifer/go-openssl/v3" "github.com/Luzifer/go-openssl/v3"
@ -16,6 +22,14 @@ func SHA1(v string) string {
return fmt.Sprintf("%x", bs) 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)
}
func EncryptPassword(pwd string) (string, error) { func EncryptPassword(pwd string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
if err != nil { if err != nil {
@ -29,6 +43,17 @@ func CheckPassword(pwd, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd)) return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
} }
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
}
func DecryptAES(value, key string) ([]byte, error) { func DecryptAES(value, key string) ([]byte, error) {
o := openssl.New() o := openssl.New()
@ -40,13 +65,31 @@ func DecryptAES(value, key string) ([]byte, error) {
return dec, nil return dec, nil
} }
func EncryptAES(value, key string) ([]byte, error) { func EncryptRSA(value, publicKey []byte) ([]byte, error) {
o := openssl.New() block, _ := pem.Decode(publicKey)
if block == nil {
return nil, errors.New("public key error")
}
enc, err := o.EncryptBytes(key, []byte(value), openssl.DigestMD5Sum) pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return enc, nil pub := pubInterface.(*rsa.PublicKey)
return rsa.EncryptPKCS1v15(rand.Reader, pub, value)
}
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)
} }

Loading…
Cancel
Save