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
7 http://www.apache.org/licenses/LICENSE-2.0
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.
32 func TestSm2(t *testing.T) {
33 priv, err := GenerateKey() // 生成密钥对
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)
42 fmt.Printf("Error: failed to encrypt %s: %v\n", msg, err)
45 fmt.Printf("Cipher text = %v\n", d0)
46 d1, err := priv.Decrypt(d0)
48 fmt.Printf("Error: failed to decrypt: %v\n", err)
50 fmt.Printf("clear text = %s\n", d1)
51 ok, err := WritePrivateKeytoPem("priv.pem", priv, nil) // 生成密钥文件
55 pubKey, _ := priv.Public().(*PublicKey)
56 ok, err = WritePublicKeytoPem("pub.pem", pubKey, nil) // 生成公钥文件
61 err = ioutil.WriteFile("ifile", msg, os.FileMode(0644)) // 生成测试文件
65 privKey, err := ReadPrivateKeyFromPem("priv.pem", nil) // 读取密钥
69 pubKey, err = ReadPublicKeyFromPem("pub.pem", nil) // 读取公钥
73 msg, _ = ioutil.ReadFile("ifile") // 从文件读取数据
74 sign, err := privKey.Sign(rand.Reader, msg, nil) // 签名
78 err = ioutil.WriteFile("ofile", sign, os.FileMode(0644))
82 signdata, _ := ioutil.ReadFile("ofile")
83 ok = privKey.Verify(msg, signdata) // 密钥验证
85 fmt.Printf("Verify error\n")
87 fmt.Printf("Verify ok\n")
89 ok = pubKey.Verify(msg, signdata) // 公钥验证
91 fmt.Printf("Verify error\n")
93 fmt.Printf("Verify ok\n")
95 templateReq := CertificateRequest{
97 CommonName: "test.example.com",
98 Organization: []string{"Test"},
100 // SignatureAlgorithm: ECDSAWithSHA256,
101 SignatureAlgorithm: SM2WithSM3,
103 _, err = CreateCertificateRequestToPem("req.pem", &templateReq, privKey)
107 req, err := ReadCertificateRequestFromPem("req.pem")
111 err = req.CheckSignature()
115 fmt.Printf("CheckSignature ok\n")
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
126 SerialNumber: big.NewInt(-1),
128 CommonName: commonName,
129 Organization: []string{"TEST"},
130 Country: []string{"China"},
131 ExtraNames: []pkix.AttributeTypeAndValue{
133 Type: []int{2, 5, 4, 42},
136 // This should override the Country, above.
138 Type: []int{2, 5, 4, 6},
143 NotBefore: time.Unix(1000, 0),
144 NotAfter: time.Unix(100000, 0),
146 // SignatureAlgorithm: ECDSAWithSHA256,
147 SignatureAlgorithm: SM2WithSM3,
149 SubjectKeyId: []byte{1, 2, 3, 4},
150 KeyUsage: KeyUsageCertSign,
152 ExtKeyUsage: testExtKeyUsage,
153 UnknownExtKeyUsage: testUnknownExtKeyUsage,
155 BasicConstraintsValid: true,
158 OCSPServer: []string{"http://ocsp.example.com"},
159 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
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")},
165 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}},
166 PermittedDNSDomains: []string{".example.com", "example.com"},
168 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
170 ExtraExtensions: []pkix.Extension{
172 Id: []int{1, 2, 3, 4},
173 Value: extraExtensionData,
175 // This extension should override the SubjectKeyId, above.
177 Id: oidExtensionSubjectKeyId,
179 Value: []byte{0x04, 0x04, 4, 3, 2, 1},
183 pubKey, _ = priv.Public().(*PublicKey)
184 ok, _ = CreateCertificateToPem("cert.pem", &template, &template, pubKey, privKey)
186 fmt.Printf("failed to create cert file\n")
188 cert, err := ReadCertificateFromPem("cert.pem")
190 fmt.Printf("failed to read cert file")
192 err = cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
196 fmt.Printf("CheckSignature ok\n")
200 func BenchmarkSM2(t *testing.B) {
202 for i := 0; i < t.N; i++ {
203 priv, err := GenerateKey() // 生成密钥对
207 msg := []byte("test")
208 sign, err := priv.Sign(rand.Reader, msg, nil) // 签名
212 ok := priv.Verify(msg, sign) // 密钥验证
214 fmt.Printf("Verify error\n")
216 fmt.Printf("Verify ok\n")