github.com/chain5j/chain5j-pkg@v1.0.7/crypto/signature/gmsm/crypto.go (about) 1 // Package gmsm 2 // 3 // @author: xwc1125 4 package gmsm 5 6 import ( 7 "crypto" 8 "crypto/ecdsa" 9 "crypto/elliptic" 10 "crypto/rand" 11 "hash" 12 13 crypto2 "github.com/chain5j/chain5j-pkg/crypto" 14 "github.com/tjfoc/gmsm/sm2" 15 "github.com/tjfoc/gmsm/sm3" 16 ) 17 18 var ( 19 _ crypto2.ECDSA = new(SM2) 20 ) 21 22 type SM2 struct { 23 } 24 25 func (s SM2) GenerateKey(curve elliptic.Curve) (*ecdsa.PrivateKey, error) { 26 return GenerateKey() 27 } 28 29 func (s SM2) HashType(curveName string) crypto.Hash { 30 return 20 31 } 32 33 func (s SM2) HashFunc(cryptoName string) func() hash.Hash { 34 return sm3.New 35 } 36 37 func (s SM2) HashMsg(cryptoName string, data []byte) ([]byte, error) { 38 return sm3.Sm3Sum(data), nil 39 } 40 41 func (s SM2) ToECDSA(prv crypto.PrivateKey) *ecdsa.PrivateKey { 42 return ToECDSA(prv.(*sm2.PrivateKey)) 43 } 44 45 func (s SM2) FromECDSA(prv *ecdsa.PrivateKey) crypto.PrivateKey { 46 return FromECDSA(prv) 47 } 48 49 func (s SM2) ToECDSAPubKey(pub crypto.PublicKey) *ecdsa.PublicKey { 50 return ToECDSAPubKey(pub.(*sm2.PublicKey)) 51 } 52 53 func (s SM2) FromECDSAPubKey(pub *ecdsa.PublicKey) crypto.PublicKey { 54 return FromECDSAPubKey(pub) 55 } 56 57 func (s SM2) MarshalPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) { 58 return MarshalPrivateKey(key) 59 } 60 61 func (s SM2) UnmarshalPrivateKey(curve elliptic.Curve, keyBytes []byte) (*ecdsa.PrivateKey, error) { 62 privateKey, err := UnmarshalPrivateKey(keyBytes) 63 if err != nil { 64 return nil, err 65 } 66 return ToECDSA(privateKey), nil 67 } 68 69 func (s SM2) MarshalPublicKey(pub *ecdsa.PublicKey) ([]byte, error) { 70 return MarshalPublicKey(pub) 71 } 72 73 func (s SM2) UnmarshalPublicKey(curve elliptic.Curve, data []byte) (*ecdsa.PublicKey, error) { 74 return UnmarshalPublicKey(data) 75 } 76 77 func (s SM2) MarshalPrivateKeyX509(key *ecdsa.PrivateKey) ([]byte, error) { 78 return MarshalPrivateKeyX509(key) 79 } 80 81 func (s SM2) UnmarshalPrivateKeyX509(curve elliptic.Curve, keyBytes []byte) (*ecdsa.PrivateKey, error) { 82 return UnmarshalPrivateX509(keyBytes) 83 } 84 85 func (s SM2) MarshalPublicKeyX509(pub *ecdsa.PublicKey) ([]byte, error) { 86 return MarshalPublicKeyX509(pub) 87 } 88 89 func (s SM2) UnmarshalPublicKeyX509(curve elliptic.Curve, data []byte) (*ecdsa.PublicKey, error) { 90 return UnmarshalPublicKeyX509(data) 91 } 92 93 func (s SM2) Sign(prv *ecdsa.PrivateKey, msg []byte) (sig []byte, err error) { 94 return Sign(prv, msg) 95 } 96 97 func (s SM2) Verify(pub *ecdsa.PublicKey, msg []byte, signature []byte) bool { 98 return Verify(pub, msg, signature) 99 } 100 101 // GenerateKey 生成PrivateKey 102 func GenerateKey() (*ecdsa.PrivateKey, error) { 103 key, err := sm2.GenerateKey(rand.Reader) 104 if err != nil { 105 return nil, err 106 } 107 return ToECDSA(key), nil 108 }