OSDN Git Service

new repo
[bytom/vapor.git] / crypto / sm2 / sm2_test.go
1 /*
2 Copyright Suzhou Tongji Fintech Research Institute 2017 All Rights Reserved.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7                  http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package sm2
17
18 import (
19         "crypto/rand"
20         "crypto/x509/pkix"
21         "encoding/asn1"
22         "fmt"
23         "io/ioutil"
24         "log"
25         "math/big"
26         "net"
27         "os"
28         "testing"
29         "time"
30 )
31
32 func TestSm2(t *testing.T) {
33         priv, err := GenerateKey() // 生成密钥对
34         if err != nil {
35                 log.Fatal(err)
36         }
37         fmt.Printf("%v\n", priv.Curve.IsOnCurve(priv.X, priv.Y)) // 验证是否为sm2的曲线
38         pub := &priv.PublicKey
39         msg := []byte("123456")
40         d0, err := pub.Encrypt(msg)
41         if err != nil {
42                 fmt.Printf("Error: failed to encrypt %s: %v\n", msg, err)
43                 return
44         }
45         fmt.Printf("Cipher text = %v\n", d0)
46         d1, err := priv.Decrypt(d0)
47         if err != nil {
48                 fmt.Printf("Error: failed to decrypt: %v\n", err)
49         }
50         fmt.Printf("clear text = %s\n", d1)
51         ok, err := WritePrivateKeytoPem("priv.pem", priv, nil) // 生成密钥文件
52         if ok != true {
53                 log.Fatal(err)
54         }
55         pubKey, _ := priv.Public().(*PublicKey)
56         ok, err = WritePublicKeytoPem("pub.pem", pubKey, nil) // 生成公钥文件
57         if ok != true {
58                 log.Fatal(err)
59         }
60         msg = []byte("test")
61         err = ioutil.WriteFile("ifile", msg, os.FileMode(0644)) // 生成测试文件
62         if err != nil {
63                 log.Fatal(err)
64         }
65         privKey, err := ReadPrivateKeyFromPem("priv.pem", nil) // 读取密钥
66         if err != nil {
67                 log.Fatal(err)
68         }
69         pubKey, err = ReadPublicKeyFromPem("pub.pem", nil) // 读取公钥
70         if err != nil {
71                 log.Fatal(err)
72         }
73         msg, _ = ioutil.ReadFile("ifile")                // 从文件读取数据
74         sign, err := privKey.Sign(rand.Reader, msg, nil) // 签名
75         if err != nil {
76                 log.Fatal(err)
77         }
78         err = ioutil.WriteFile("ofile", sign, os.FileMode(0644))
79         if err != nil {
80                 log.Fatal(err)
81         }
82         signdata, _ := ioutil.ReadFile("ofile")
83         ok = privKey.Verify(msg, signdata) // 密钥验证
84         if ok != true {
85                 fmt.Printf("Verify error\n")
86         } else {
87                 fmt.Printf("Verify ok\n")
88         }
89         ok = pubKey.Verify(msg, signdata) // 公钥验证
90         if ok != true {
91                 fmt.Printf("Verify error\n")
92         } else {
93                 fmt.Printf("Verify ok\n")
94         }
95         templateReq := CertificateRequest{
96                 Subject: pkix.Name{
97                         CommonName:   "test.example.com",
98                         Organization: []string{"Test"},
99                 },
100                 //              SignatureAlgorithm: ECDSAWithSHA256,
101                 SignatureAlgorithm: SM2WithSM3,
102         }
103         _, err = CreateCertificateRequestToPem("req.pem", &templateReq, privKey)
104         if err != nil {
105                 log.Fatal(err)
106         }
107         req, err := ReadCertificateRequestFromPem("req.pem")
108         if err != nil {
109                 log.Fatal(err)
110         }
111         err = req.CheckSignature()
112         if err != nil {
113                 log.Fatal(err)
114         } else {
115                 fmt.Printf("CheckSignature ok\n")
116         }
117         testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
118         testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
119         extraExtensionData := []byte("extra extension")
120         commonName := "test.example.com"
121         template := Certificate{
122                 // SerialNumber is negative to ensure that negative
123                 // values are parsed. This is due to the prevalence of
124                 // buggy code that produces certificates with negative
125                 // serial numbers.
126                 SerialNumber: big.NewInt(-1),
127                 Subject: pkix.Name{
128                         CommonName:   commonName,
129                         Organization: []string{"TEST"},
130                         Country:      []string{"China"},
131                         ExtraNames: []pkix.AttributeTypeAndValue{
132                                 {
133                                         Type:  []int{2, 5, 4, 42},
134                                         Value: "Gopher",
135                                 },
136                                 // This should override the Country, above.
137                                 {
138                                         Type:  []int{2, 5, 4, 6},
139                                         Value: "NL",
140                                 },
141                         },
142                 },
143                 NotBefore: time.Unix(1000, 0),
144                 NotAfter:  time.Unix(100000, 0),
145
146                 //              SignatureAlgorithm: ECDSAWithSHA256,
147                 SignatureAlgorithm: SM2WithSM3,
148
149                 SubjectKeyId: []byte{1, 2, 3, 4},
150                 KeyUsage:     KeyUsageCertSign,
151
152                 ExtKeyUsage:        testExtKeyUsage,
153                 UnknownExtKeyUsage: testUnknownExtKeyUsage,
154
155                 BasicConstraintsValid: true,
156                 IsCA: true,
157
158                 OCSPServer:            []string{"http://ocsp.example.com"},
159                 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
160
161                 DNSNames:       []string{"test.example.com"},
162                 EmailAddresses: []string{"gopher@golang.org"},
163                 IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
164
165                 PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
166                 PermittedDNSDomains: []string{".example.com", "example.com"},
167
168                 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
169
170                 ExtraExtensions: []pkix.Extension{
171                         {
172                                 Id:    []int{1, 2, 3, 4},
173                                 Value: extraExtensionData,
174                         },
175                         // This extension should override the SubjectKeyId, above.
176                         {
177                                 Id:       oidExtensionSubjectKeyId,
178                                 Critical: false,
179                                 Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
180                         },
181                 },
182         }
183         pubKey, _ = priv.Public().(*PublicKey)
184         ok, _ = CreateCertificateToPem("cert.pem", &template, &template, pubKey, privKey)
185         if ok != true {
186                 fmt.Printf("failed to create cert file\n")
187         }
188         cert, err := ReadCertificateFromPem("cert.pem")
189         if err != nil {
190                 fmt.Printf("failed to read cert file")
191         }
192         err = cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
193         if err != nil {
194                 log.Fatal(err)
195         } else {
196                 fmt.Printf("CheckSignature ok\n")
197         }
198 }
199
200 func BenchmarkSM2(t *testing.B) {
201         t.ReportAllocs()
202         for i := 0; i < t.N; i++ {
203                 priv, err := GenerateKey() // 生成密钥对
204                 if err != nil {
205                         log.Fatal(err)
206                 }
207                 msg := []byte("test")
208                 sign, err := priv.Sign(rand.Reader, msg, nil) // 签名
209                 if err != nil {
210                         log.Fatal(err)
211                 }
212                 ok := priv.Verify(msg, sign) // 密钥验证
213                 if ok != true {
214                         fmt.Printf("Verify error\n")
215                 } else {
216                         fmt.Printf("Verify ok\n")
217                 }
218         }
219 }