sm2.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // reference to ecdsa
  15. import (
  16. "crypto"
  17. "crypto/aes"
  18. "crypto/cipher"
  19. "crypto/elliptic"
  20. "crypto/rand"
  21. "crypto/sha512"
  22. "encoding/asn1"
  23. "errors"
  24. "io"
  25. "math/big"
  26. )
  27. type combinedMult interface {
  28. CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)
  29. }
  30. const (
  31. aesIV = "IV for <SM2> CTR"
  32. )
  33. type PublicKey struct {
  34. elliptic.Curve
  35. X, Y *big.Int
  36. }
  37. type PrivateKey struct {
  38. PublicKey
  39. D *big.Int
  40. }
  41. type sm2Signature struct {
  42. R, S *big.Int
  43. }
  44. // The SM2's private key contains the public key
  45. func (priv *PrivateKey) Public() crypto.PublicKey {
  46. return &priv.PublicKey
  47. }
  48. // sign format = 30 + len(z) + 02 + len(r) + r + 02 + len(s) + s, z being what follows its size, ie 02+len(r)+r+02+len(s)+s
  49. func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
  50. r, s, err := Sign(priv, msg)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return asn1.Marshal(sm2Signature{r, s})
  55. }
  56. func (pub *PublicKey) Verify(msg []byte, sign []byte) bool {
  57. var sm2Sign sm2Signature
  58. _, err := asn1.Unmarshal(sign, &sm2Sign)
  59. if err != nil {
  60. return false
  61. }
  62. return Verify(pub, msg, sm2Sign.R, sm2Sign.S)
  63. }
  64. var one = new(big.Int).SetInt64(1)
  65. func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
  66. params := c.Params()
  67. b := make([]byte, params.BitSize/8+8)
  68. _, err = io.ReadFull(rand, b)
  69. if err != nil {
  70. return
  71. }
  72. k = new(big.Int).SetBytes(b)
  73. n := new(big.Int).Sub(params.N, one)
  74. k.Mod(k, n)
  75. k.Add(k, one)
  76. return
  77. }
  78. func GenerateKey() (*PrivateKey, error) {
  79. c := P256Sm2()
  80. k, err := randFieldElement(c, rand.Reader)
  81. if err != nil {
  82. return nil, err
  83. }
  84. priv := new(PrivateKey)
  85. priv.PublicKey.Curve = c
  86. priv.D = k
  87. priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
  88. return priv, nil
  89. }
  90. var errZeroParam = errors.New("zero parameter")
  91. func Sign(priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
  92. entropylen := (priv.Curve.Params().BitSize + 7) / 16
  93. if entropylen > 32 {
  94. entropylen = 32
  95. }
  96. entropy := make([]byte, entropylen)
  97. _, err = io.ReadFull(rand.Reader, entropy)
  98. if err != nil {
  99. return
  100. }
  101. // Initialize an SHA-512 hash context; digest ...
  102. md := sha512.New()
  103. md.Write(priv.D.Bytes()) // the private key,
  104. md.Write(entropy) // the entropy,
  105. md.Write(hash) // and the input hash;
  106. key := md.Sum(nil)[:32] // and compute ChopMD-256(SHA-512),
  107. // which is an indifferentiable MAC.
  108. // Create an AES-CTR instance to use as a CSPRNG.
  109. block, err := aes.NewCipher(key)
  110. if err != nil {
  111. return nil, nil, err
  112. }
  113. // Create a CSPRNG that xors a stream of zeros with
  114. // the output of the AES-CTR instance.
  115. csprng := cipher.StreamReader{
  116. R: zeroReader,
  117. S: cipher.NewCTR(block, []byte(aesIV)),
  118. }
  119. // See [NSA] 3.4.1
  120. c := priv.PublicKey.Curve
  121. N := c.Params().N
  122. if N.Sign() == 0 {
  123. return nil, nil, errZeroParam
  124. }
  125. var k *big.Int
  126. e := new(big.Int).SetBytes(hash)
  127. for { // 调整算法细节以实现SM2
  128. for {
  129. k, err = randFieldElement(c, csprng)
  130. if err != nil {
  131. r = nil
  132. return
  133. }
  134. r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
  135. r.Add(r, e)
  136. r.Mod(r, N)
  137. if r.Sign() != 0 {
  138. break
  139. }
  140. if t := new(big.Int).Add(r, k); t.Cmp(N) == 0 {
  141. break
  142. }
  143. }
  144. rD := new(big.Int).Mul(priv.D, r)
  145. s = new(big.Int).Sub(k, rD)
  146. d1 := new(big.Int).Add(priv.D, one)
  147. d1Inv := new(big.Int).ModInverse(d1, N)
  148. s.Mul(s, d1Inv)
  149. s.Mod(s, N)
  150. if s.Sign() != 0 {
  151. break
  152. }
  153. }
  154. return
  155. }
  156. func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
  157. c := pub.Curve
  158. N := c.Params().N
  159. if r.Sign() <= 0 || s.Sign() <= 0 {
  160. return false
  161. }
  162. if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
  163. return false
  164. }
  165. // 调整算法细节以实现SM2
  166. t := new(big.Int).Add(r, s)
  167. t.Mod(t, N)
  168. if N.Sign() == 0 {
  169. return false
  170. }
  171. var x *big.Int
  172. if opt, ok := c.(combinedMult); ok {
  173. x, _ = opt.CombinedMult(pub.X, pub.Y, s.Bytes(), t.Bytes())
  174. } else {
  175. x1, y1 := c.ScalarBaseMult(s.Bytes())
  176. x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes())
  177. x, _ = c.Add(x1, y1, x2, y2)
  178. }
  179. e := new(big.Int).SetBytes(hash)
  180. x.Add(x, e)
  181. x.Mod(x, N)
  182. return x.Cmp(r) == 0
  183. }
  184. type zr struct {
  185. io.Reader
  186. }
  187. func (z *zr) Read(dst []byte) (n int, err error) {
  188. for i := range dst {
  189. dst[i] = 0
  190. }
  191. return len(dst), nil
  192. }
  193. var zeroReader = &zr{}