gitee.com/lh-her-team/common@v1.5.1/opencrypto/gmssl/sm2/privatekey.go (about) 1 package sm2 2 3 import ( 4 crypto2 "crypto" 5 "encoding/pem" 6 7 "gitee.com/lh-her-team/common/opencrypto/utils" 8 9 bccrypto "gitee.com/lh-her-team/common/crypto" 10 "gitee.com/lh-her-team/common/crypto/hash" 11 "gitee.com/lh-her-team/common/opencrypto/gmssl/gmssl" 12 ) 13 14 var _ bccrypto.PrivateKey = (*PrivateKey)(nil) 15 16 type PrivateKey struct { 17 *gmssl.PrivateKey 18 skPem string 19 Pub PublicKey 20 } 21 22 func (sk *PrivateKey) Bytes() ([]byte, error) { 23 p, _ := pem.Decode([]byte(sk.skPem)) 24 return p.Bytes, nil 25 } 26 27 func (sk *PrivateKey) Type() bccrypto.KeyType { 28 return bccrypto.SM2 29 } 30 31 func (sk *PrivateKey) String() (string, error) { 32 return sk.skPem, nil 33 } 34 35 func (sk *PrivateKey) PublicKey() bccrypto.PublicKey { 36 return &sk.Pub 37 } 38 39 func (sk *PrivateKey) Sign(msg []byte) ([]byte, error) { 40 return sk.signWithSM3(msg, utils.SM2_DEFAULT_USER_ID) 41 } 42 43 func (sk *PrivateKey) SignWithOpts(msg []byte, opts *bccrypto.SignOpts) ([]byte, error) { 44 if opts == nil { 45 return sk.Sign(msg) 46 } 47 if opts.Hash == bccrypto.HASH_TYPE_SM3 && sk.Type() == bccrypto.SM2 { 48 uid := opts.UID 49 if len(uid) == 0 { 50 uid = bccrypto.CRYPTO_DEFAULT_UID 51 } 52 return sk.signWithSM3(msg, uid) 53 } 54 dgst, err := hash.Get(opts.Hash, msg) 55 if err != nil { 56 return nil, err 57 } 58 return sk.Sign(dgst) 59 60 } 61 62 func (sk *PrivateKey) ToStandardKey() crypto2.PrivateKey { 63 return &signer{PrivateKey: *sk} 64 } 65 66 // PrivateKey implements bccrypto.PrivateKey 67 func (sk *PrivateKey) signWithSM3(msg []byte, uid string) ([]byte, error) { 68 dgst, err := sk.Pub.CalSM2Digest(uid, msg) 69 if err != nil { 70 return nil, err 71 } 72 return sk.PrivateKey.Sign("sm2sign", dgst, nil) 73 } 74 75 var _ bccrypto.DecryptKey = (*PrivateKey)(nil) 76 77 func (sk *PrivateKey) Decrypt(ciphertext []byte) ([]byte, error) { 78 return sk.PrivateKey.Decrypt("sm2encrypt-with-sm3", ciphertext, nil) 79 } 80 81 func (sk *PrivateKey) DecryptWithOpts(ciphertext []byte, opts *bccrypto.EncOpts) ([]byte, error) { 82 return sk.Decrypt(ciphertext) 83 } 84 85 func (sk *PrivateKey) EncryptKey() bccrypto.EncryptKey { 86 return &PublicKey{PublicKey: sk.Pub.PublicKey} 87 }