package sm2 import ( "crypto/ecdsa" "crypto/elliptic" "errors" "io" "math/big" "golang.org/x/crypto/cryptobyte" "golang.org/x/crypto/cryptobyte/asn1" ) // A invertible implements fast inverse in GF(N). type invertible interface { // Inverse returns the inverse of k mod Params().N. Inverse(k *big.Int) *big.Int } // A combinedMult implements fast combined multiplication for verification. type combinedMult interface { // CombinedMult returns [s1]G + [s2]P where G is the generator. CombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int) } // hashToInt converts a hash value to an integer. Per FIPS 186-4, Section 6.4, // we use the left-most bits of the hash to match the bit-length of the order of // the curve. This also performs Step 5 of SEC 1, Version 2.0, Section 4.1.3. func hashToInt(hash []byte, c elliptic.Curve) *big.Int { orderBits := c.Params().N.BitLen() orderBytes := (orderBits + 7) / 8 if len(hash) > orderBytes { hash = hash[:orderBytes] } ret := new(big.Int).SetBytes(hash) excess := len(hash)*8 - orderBits if excess > 0 { ret.Rsh(ret, uint(excess)) } return ret } var errZeroParam = errors.New("zero parameter") // Sign signs a hash (which should be the result of hashing a larger message) // using the private key, priv. If the hash is longer than the bit-length of the // private key's curve order, the hash will be truncated to that length. It // returns the signature as a pair of integers. Most applications should use // SignASN1 instead of dealing directly with r, s. // // Compliance with GB/T 32918.2-2016 regardless it's SM2 curve or not. func Sign(rand io.Reader, priv *ecdsa.PrivateKey, hash []byte) (r, s *big.Int, err error) { key := new(PrivateKey) key.PrivateKey = *priv sig, err := SignASN1(rand, key, hash, nil) if err != nil { return nil, nil, err } r, s = new(big.Int), new(big.Int) var inner cryptobyte.String input := cryptobyte.String(sig) if !input.ReadASN1(&inner, asn1.SEQUENCE) || !input.Empty() || !inner.ReadASN1Integer(r) || !inner.ReadASN1Integer(s) || !inner.Empty() { return nil, nil, errors.New("invalid ASN.1 from SignASN1") } return r, s, nil } func signLegacy(priv *PrivateKey, csprng io.Reader, hash []byte) (sig []byte, err error) { // See [NSA] 3.4.1 c := priv.PublicKey.Curve N := c.Params().N if N.Sign() == 0 { return nil, errZeroParam } var k, r, s *big.Int e := hashToInt(hash, c) for { for { k, err = randFieldElement(c, csprng) if err != nil { return nil, err } r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) // (x, y) = k*G r.Add(r, e) // r = x + e r.Mod(r, N) // r = (x + e) mod N if r.Sign() != 0 { t := new(big.Int).Add(r, k) if t.Cmp(N) != 0 { // if r != 0 && (r + k) != N then ok break } } } s = new(big.Int).Mul(priv.D, r) s = new(big.Int).Sub(k, s) dp1 := new(big.Int).Add(priv.D, one) var dp1Inv *big.Int if in, ok := priv.Curve.(invertible); ok { dp1Inv = in.Inverse(dp1) } else { dp1Inv = fermatInverse(dp1, N) // N != 0 } s.Mul(s, dp1Inv) s.Mod(s, N) // N != 0 if s.Sign() != 0 { break } } return encodeSignature(r.Bytes(), s.Bytes()) } // SignWithSM2 follow sm2 dsa standards for hash part, compliance with GB/T 32918.2-2016. func SignWithSM2(rand io.Reader, priv *ecdsa.PrivateKey, uid, msg []byte) (r, s *big.Int, err error) { digest, err := calculateSM2Hash(&priv.PublicKey, msg, uid) if err != nil { return nil, nil, err } return Sign(rand, priv, digest) } // Verify verifies the signature in r, s of hash using the public key, pub. Its // return value records whether the signature is valid. Most applications should // use VerifyASN1 instead of dealing directly with r, s. // // Compliance with GB/T 32918.2-2016 regardless it's SM2 curve or not. // Caller should make sure the hash's correctness. func Verify(pub *ecdsa.PublicKey, hash []byte, r, s *big.Int) bool { sig, err := encodeSignature(r.Bytes(), s.Bytes()) if err != nil { return false } return VerifyASN1(pub, hash, sig) } func verifyLegacy(pub *ecdsa.PublicKey, hash, sig []byte) bool { rBytes, sBytes, err := parseSignature(sig) if err != nil { return false } r, s := new(big.Int).SetBytes(rBytes), new(big.Int).SetBytes(sBytes) c := pub.Curve N := c.Params().N if r.Sign() <= 0 || s.Sign() <= 0 { return false } if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 { return false } e := hashToInt(hash, c) t := new(big.Int).Add(r, s) t.Mod(t, N) if t.Sign() == 0 { return false } var x *big.Int if opt, ok := c.(combinedMult); ok { x, _ = opt.CombinedMult(pub.X, pub.Y, s.Bytes(), t.Bytes()) } else { x1, y1 := c.ScalarBaseMult(s.Bytes()) x2, y2 := c.ScalarMult(pub.X, pub.Y, t.Bytes()) x, _ = c.Add(x1, y1, x2, y2) } x.Add(x, e) x.Mod(x, N) return x.Cmp(r) == 0 } // VerifyWithSM2 verifies the signature in r, s of raw msg and uid using the public key, pub. // It returns value records whether the signature is valid. Compliance with GB/T 32918.2-2016. func VerifyWithSM2(pub *ecdsa.PublicKey, uid, msg []byte, r, s *big.Int) bool { digest, err := calculateSM2Hash(pub, msg, uid) if err != nil { return false } return Verify(pub, digest, r, s) } var ( one = new(big.Int).SetInt64(1) ) // randFieldElement returns a random element of the order of the given // curve using the procedure given in FIPS 186-4, Appendix B.5.2. func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) { // See randomPoint for notes on the algorithm. This has to match, or s390x // signatures will come out different from other architectures, which will // break TLS recorded tests. for { N := c.Params().N b := make([]byte, (N.BitLen()+7)/8) if _, err = io.ReadFull(rand, b); err != nil { return } if excess := len(b)*8 - N.BitLen(); excess > 0 { b[0] >>= excess } k = new(big.Int).SetBytes(b) if k.Sign() != 0 && k.Cmp(N) < 0 { return } } }