sm2_test.go 5.2 KB

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