1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 00:22:41 +08:00

加密算法

This commit is contained in:
2022-04-20 11:34:03 +08:00
parent 0ab7efb7ef
commit cd163ed99b
5 changed files with 31 additions and 2 deletions

18
crypto/crypto.go Normal file
View File

@ -0,0 +1,18 @@
package crypto
// 对称加密
type ISymmetric interface {
Encrypt(msg []byte) ([]byte, error)
Decrypt(cipherText []byte) ([]byte, error)
}
// 非对称加密
type IAsymmetric interface {
Encrypt(msg []byte) ([]byte, error)
Decrypt(ciphertext []byte) ([]byte, error)
}
type Signer interface {
Sign(msg []byte) ([]byte, error)
Verify(msg, sign []byte) bool
}

View File

@ -3,6 +3,7 @@ package crypto
import (
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"errors"
@ -10,6 +11,8 @@ import (
"strconv"
)
// var _ Signer = &ecdsaOptions{}
type ecdsaOptions struct {
hashOptions
prv *ecdsa.PrivateKey
@ -89,12 +92,16 @@ func ParsePublicKey(pem []byte) Option {
return publicKeyOption(pem)
}
func (opt *ecdsaOptions) Sign(msg []byte) ([]byte, error) {
sum := opt.getHash(msg)
return ecdsa.SignASN1(rand.Reader, opt.prv, sum)
}
func (opt *ecdsaOptions) Verify(msg, rText, sText []byte) bool {
var r, s big.Int
_ = r.UnmarshalText(rText)
_ = s.UnmarshalText(sText)
sum := opt.getHash(msg)
return ecdsa.Verify(opt.pub, sum, &r, &s)
}

View File

@ -10,7 +10,7 @@ import (
"strconv"
)
var _ IAsymmetric = &rsaInstance{}
type rsaInstance struct {
hashOptions

View File

@ -15,6 +15,8 @@ var (
C1C2C3 = 1
)
var _ IAsymmetric = &sm2Instance{}
type sm2Instance struct {
mode int
prk *s.PrivateKey

View File

@ -6,6 +6,8 @@ import (
"github.com/tjfoc/gmsm/sm4"
)
var _ ISymmetric = &sm4EcbInstance{}
type sm4Instance struct {
key []byte
}