18 "github.com/bytom/crypto/sm3"
22 aesIV = "IV for <SM2> CTR"
25 type PublicKey struct {
30 type PrivateKey struct {
35 type sm2Signature struct {
39 // The SM2's private key contains the public key
40 func (priv *PrivateKey) Public() crypto.PublicKey {
41 return &priv.PublicKey
44 func SignDigitToSignData(r, s *big.Int) ([]byte, error) {
45 return asn1.Marshal(sm2Signature{r, s})
48 func SignDataToSignDigit(sign []byte) (*big.Int, *big.Int, error) {
49 var sm2Sign sm2Signature
51 _, err := asn1.Unmarshal(sign, &sm2Sign)
55 return sm2Sign.R, sm2Sign.S, nil
58 // 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
59 func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) {
60 r, s, err := Sign(priv, msg)
64 return asn1.Marshal(sm2Signature{r, s})
67 func (priv *PrivateKey) Decrypt(data []byte) ([]byte, error) {
68 return Decrypt(priv, data)
71 func (pub *PublicKey) Verify(msg []byte, sign []byte) bool {
72 var sm2Sign sm2Signature
74 _, err := asn1.Unmarshal(sign, &sm2Sign)
78 return Verify(pub, msg, sm2Sign.R, sm2Sign.S)
81 func (pub *PublicKey) Encrypt(data []byte) ([]byte, error) {
82 return Encrypt(pub, data)
85 var one = new(big.Int).SetInt64(1)
87 func intToBytes(x int) []byte {
88 var buf = make([]byte, 4)
90 binary.BigEndian.PutUint32(buf, uint32(x))
94 func kdf(x, y []byte, length int) ([]byte, bool) {
100 for i, j := 0, (length+31)/32; i < j; i++ {
103 h.Write(intToBytes(ct))
105 if i+1 == j && length%32 != 0 {
106 c = append(c, hash[:length%32]...)
108 c = append(c, hash...)
112 for i := 0; i < length; i++ {
120 func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {
122 b := make([]byte, params.BitSize/8+8)
123 _, err = io.ReadFull(rand, b)
127 k = new(big.Int).SetBytes(b)
128 n := new(big.Int).Sub(params.N, one)
134 func GenerateKey() (*PrivateKey, error) {
136 k, err := randFieldElement(c, rand.Reader)
140 priv := new(PrivateKey)
141 priv.PublicKey.Curve = c
143 priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())
147 var errZeroParam = errors.New("zero parameter")
149 func Sign(priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {
150 entropylen := (priv.Curve.Params().BitSize + 7) / 16
154 entropy := make([]byte, entropylen)
155 _, err = io.ReadFull(rand.Reader, entropy)
160 // Initialize an SHA-512 hash context; digest ...
162 md.Write(priv.D.Bytes()) // the private key,
163 md.Write(entropy) // the entropy,
164 md.Write(hash) // and the input hash;
165 key := md.Sum(nil)[:32] // and compute ChopMD-256(SHA-512),
166 // which is an indifferentiable MAC.
168 // Create an AES-CTR instance to use as a CSPRNG.
169 block, err := aes.NewCipher(key)
174 // Create a CSPRNG that xors a stream of zeros with
175 // the output of the AES-CTR instance.
176 csprng := cipher.StreamReader{
178 S: cipher.NewCTR(block, []byte(aesIV)),
182 c := priv.PublicKey.Curve
185 return nil, nil, errZeroParam
188 e := new(big.Int).SetBytes(hash)
189 for { // 调整算法细节以实现SM2
191 k, err = randFieldElement(c, csprng)
196 r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
202 if t := new(big.Int).Add(r, k); t.Cmp(N) == 0 {
206 rD := new(big.Int).Mul(priv.D, r)
207 s = new(big.Int).Sub(k, rD)
208 d1 := new(big.Int).Add(priv.D, one)
209 d1Inv := new(big.Int).ModInverse(d1, N)
219 func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {
223 if r.Sign() <= 0 || s.Sign() <= 0 {
226 if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
231 t := new(big.Int).Add(r, s)
238 x1, y1 := c.ScalarBaseMult(s.Bytes())
239 x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes())
240 x, _ = c.Add(x1, y1, x2, y2)
242 e := new(big.Int).SetBytes(hash)
248 func Sm2Sign(priv *PrivateKey, msg, uid []byte) (r, s *big.Int, err error) {
249 za, err := ZA(&priv.PublicKey, uid)
253 e, err := msgHash(za, msg)
257 c := priv.PublicKey.Curve
260 return nil, nil, errZeroParam
263 for { // 调整算法细节以实现SM2
265 k, err = randFieldElement(c, rand.Reader)
270 r, _ = priv.Curve.ScalarBaseMult(k.Bytes())
276 if t := new(big.Int).Add(r, k); t.Cmp(N) == 0 {
280 rD := new(big.Int).Mul(priv.D, r)
281 s = new(big.Int).Sub(k, rD)
282 d1 := new(big.Int).Add(priv.D, one)
283 d1Inv := new(big.Int).ModInverse(d1, N)
293 func Sm2Verify(pub *PublicKey, msg, uid []byte, r, s *big.Int) bool {
296 one := new(big.Int).SetInt64(1)
297 if r.Cmp(one) < 0 || s.Cmp(one) < 0 {
300 if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {
303 za, err := ZA(pub, uid)
307 e, err := msgHash(za, msg)
311 t := new(big.Int).Add(r, s)
317 x1, y1 := c.ScalarBaseMult(s.Bytes())
318 x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes())
319 x, _ = c.Add(x1, y1, x2, y2)
326 func msgHash(za, msg []byte) (*big.Int, error) {
330 return new(big.Int).SetBytes(e.Sum(nil)[:32]), nil
333 // ZA = H256(ENTLA || IDA || a || b || xG || yG || xA || yA)
334 func ZA(pub *PublicKey, uid []byte) ([]byte, error) {
338 return []byte{}, errors.New("SM2: uid too large")
340 Entla := uint16(8 * uidLen)
341 za.Write([]byte{byte((Entla >> 8) & 0xFF)})
342 za.Write([]byte{byte(Entla & 0xFF)})
344 za.Write(sm2P256ToBig(&sm2P256.a).Bytes())
345 za.Write(sm2P256.B.Bytes())
346 za.Write(sm2P256.Gx.Bytes())
347 za.Write(sm2P256.Gy.Bytes())
349 xBuf := pub.X.Bytes()
350 yBuf := pub.Y.Bytes()
351 if n := len(xBuf); n < 32 {
352 xBuf = append(zeroByteSlice[:32-n], xBuf...)
356 return za.Sum(nil)[:32], nil
360 var zeroByteSlice = []byte{
378 func Encrypt(pub *PublicKey, data []byte) ([]byte, error) {
383 k, err := randFieldElement(curve, rand.Reader)
387 x1, y1 := curve.ScalarBaseMult(k.Bytes())
388 x2, y2 := curve.ScalarMult(pub.X, pub.Y, k.Bytes())
393 if n := len(x1Buf); n < 32 {
394 x1Buf = append(zeroByteSlice[:32-n], x1Buf...)
396 if n := len(y1Buf); n < 32 {
397 y1Buf = append(zeroByteSlice[:32-n], y1Buf...)
399 if n := len(x2Buf); n < 32 {
400 x2Buf = append(zeroByteSlice[:32-n], x2Buf...)
402 if n := len(y2Buf); n < 32 {
403 y2Buf = append(zeroByteSlice[:32-n], y2Buf...)
405 c = append(c, x1Buf...) // x分量
406 c = append(c, y1Buf...) // y分量
408 tm = append(tm, x2Buf...)
409 tm = append(tm, data...)
410 tm = append(tm, y2Buf...)
413 ct, ok := kdf(x2Buf, y2Buf, length) // 密文
418 for i := 0; i < length; i++ {
421 return append([]byte{0x04}, c...), nil
425 func Decrypt(priv *PrivateKey, data []byte) ([]byte, error) {
427 length := len(data) - 96
429 x := new(big.Int).SetBytes(data[:32])
430 y := new(big.Int).SetBytes(data[32:64])
431 x2, y2 := curve.ScalarMult(x, y, priv.D.Bytes())
434 if n := len(x2Buf); n < 32 {
435 x2Buf = append(zeroByteSlice[:32-n], x2Buf...)
437 if n := len(y2Buf); n < 32 {
438 y2Buf = append(zeroByteSlice[:32-n], y2Buf...)
440 c, ok := kdf(x2Buf, y2Buf, length)
442 return nil, errors.New("Decrypt: failed to decrypt")
444 for i := 0; i < length; i++ {
448 tm = append(tm, x2Buf...)
449 tm = append(tm, c...)
450 tm = append(tm, y2Buf...)
452 if bytes.Compare(h, data[64:96]) != 0 {
453 return c, errors.New("Decrypt: failed to decrypt")
462 func (z *zr) Read(dst []byte) (n int, err error) {
469 var zeroReader = &zr{}
471 func getLastBit(a *big.Int) uint {
475 func Compress(a *PublicKey) []byte {
477 yp := getLastBit(a.Y)
478 buf = append(buf, a.X.Bytes()...)
479 if n := len(a.X.Bytes()); n < 32 {
480 buf = append(zeroByteSlice[:(32-n)], buf...)
482 buf = append([]byte{byte(yp)}, buf...)
486 func Decompress(a []byte) *PublicKey {
487 var aa, xx, xx3 sm2P256FieldElement
490 x := new(big.Int).SetBytes(a[1:])
492 sm2P256FromBig(&xx, x)
493 sm2P256Square(&xx3, &xx) // x3 = x ^ 2
494 sm2P256Mul(&xx3, &xx3, &xx) // x3 = x ^ 2 * x
495 sm2P256Mul(&aa, &curve.a, &xx) // a = a * x
496 sm2P256Add(&xx3, &xx3, &aa)
497 sm2P256Add(&xx3, &xx3, &curve.b)
499 y2 := sm2P256ToBig(&xx3)
500 y := new(big.Int).ModSqrt(y2, sm2P256.P)
501 if getLastBit(y) != uint(a[0]) {