-
Notifications
You must be signed in to change notification settings - Fork 12
/
tjSM2.go
71 lines (61 loc) · 1.67 KB
/
tjSM2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package interop
import (
"crypto/rand"
tj "github.com/Hyperledger-TWGC/tjfoc-gm/sm2"
tjx509 "github.com/Hyperledger-TWGC/tjfoc-gm/x509"
)
type TJSM2 struct {
PrivateKey *tj.PrivateKey
PublicKey *tj.PublicKey
}
func NewTJSM2() (*TJSM2, error) {
PrivateKey, err := tj.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
return &TJSM2{PrivateKey: PrivateKey, PublicKey: &PrivateKey.PublicKey}, nil
}
func TJImportKey(privPEM []byte, pubPEM []byte) (*TJSM2, error) {
PrivateKey, err := tjx509.ReadPrivateKeyFromPem(privPEM, nil)
if err != nil {
return nil, err
}
PublicKey, err := tjx509.ReadPublicKeyFromPem(pubPEM)
if err != nil {
return nil, err
}
return &TJSM2{PrivateKey: PrivateKey, PublicKey: PublicKey}, nil
}
func (instance *TJSM2) ExportKey() (privPEM []byte, pubPEM []byte, err error) {
privPEM, err = tjx509.WritePrivateKeyToPem(instance.PrivateKey, nil)
if err != nil {
return
}
pubPEM, err = tjx509.WritePublicKeyToPem(instance.PublicKey)
return
}
func (instance *TJSM2) Encrypt(msg []byte) ([]byte, error) {
encrypted, err := instance.PublicKey.EncryptAsn1(msg, rand.Reader)
if err != nil {
return nil, err
}
return encrypted, nil
}
func (instance *TJSM2) Decrypt(encrypted []byte) ([]byte, error) {
decrypted, err := instance.PrivateKey.DecryptAsn1(encrypted)
if err != nil {
return nil, err
}
return decrypted, nil
}
func (instance *TJSM2) Sign(msg []byte) ([]byte, error) {
sign, err := instance.PrivateKey.Sign(rand.Reader, msg, nil) // 签名
if err != nil {
return nil, err
}
return sign, nil
}
func (instance *TJSM2) Verify(msg []byte, sign []byte) bool {
ok := instance.PublicKey.Verify(msg, sign) // 公钥验证
return ok
}