github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/crypto/koblitz/signature.go (about) 1 // Copyright (c) 2013-2014 The btcsuite developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package koblitz 6 7 import ( 8 "bytes" 9 "crypto/ecdsa" 10 "crypto/elliptic" 11 "crypto/hmac" 12 "errors" 13 "fmt" 14 "hash" 15 "math/big" 16 17 "github.com/mit-dci/lit/crypto/fastsha256" 18 ) 19 20 // Errors returned by canonicalPadding. 21 var ( 22 errNegativeValue = errors.New("value may be interpreted as negative") 23 errExcessivelyPaddedValue = errors.New("value is excessively padded") 24 ) 25 26 // Signature is a type representing an ecdsa signature. 27 type Signature struct { 28 R *big.Int 29 S *big.Int 30 } 31 32 var ( 33 // Curve order and halforder, used to tame ECDSA malleability (see BIP-0062) 34 order = new(big.Int).Set(S256().N) 35 halforder = new(big.Int).Rsh(order, 1) 36 37 // Used in RFC6979 implementation when testing the nonce for correctness 38 one = big.NewInt(1) 39 40 // oneInitializer is used to fill a byte slice with byte 0x01. It is provided 41 // here to avoid the need to create it multiple times. 42 oneInitializer = []byte{0x01} 43 ) 44 45 // Serialize returns the ECDSA signature in the more strict DER format. Note 46 // that the serialized bytes returned do not include the appended hash type 47 // used in Bitcoin signature scripts. 48 // 49 // encoding/asn1 is broken so we hand roll this output: 50 // 51 // 0x30 <length> 0x02 <length r> r 0x02 <length s> s 52 func (sig *Signature) Serialize() []byte { 53 // low 'S' malleability breaker 54 sigS := sig.S 55 if sigS.Cmp(halforder) == 1 { 56 sigS = new(big.Int).Sub(order, sigS) 57 } 58 // Ensure the encoded bytes for the r and s values are canonical and 59 // thus suitable for DER encoding. 60 rb := canonicalizeInt(sig.R) 61 sb := canonicalizeInt(sigS) 62 63 // total length of returned signature is 1 byte for each magic and 64 // length (6 total), plus lengths of r and s 65 length := 6 + len(rb) + len(sb) 66 b := make([]byte, length, length) 67 68 b[0] = 0x30 69 b[1] = byte(length - 2) 70 b[2] = 0x02 71 b[3] = byte(len(rb)) 72 offset := copy(b[4:], rb) + 4 73 b[offset] = 0x02 74 b[offset+1] = byte(len(sb)) 75 copy(b[offset+2:], sb) 76 return b 77 } 78 79 // Verify calls ecdsa.Verify to verify the signature of hash using the public 80 // key. It returns true if the signature is valid, false otherwise. 81 func (sig *Signature) Verify(hash []byte, pubKey *PublicKey) bool { 82 return ecdsa.Verify(pubKey.ToECDSA(), hash, sig.R, sig.S) 83 } 84 85 // IsEqual compares this Signature instance to the one passed, returning true 86 // if both Signatures are equivalent. A signature is equivalent to another, if 87 // they both have the same scalar value for R and S. 88 func (sig *Signature) IsEqual(otherSig *Signature) bool { 89 return sig.R.Cmp(otherSig.R) == 0 && 90 sig.S.Cmp(otherSig.S) == 0 91 } 92 93 func parseSig(sigStr []byte, curve elliptic.Curve, der bool) (*Signature, error) { 94 // Originally this code used encoding/asn1 in order to parse the 95 // signature, but a number of problems were found with this approach. 96 // Despite the fact that signatures are stored as DER, the difference 97 // between go's idea of a bignum (and that they have sign) doesn't agree 98 // with the openssl one (where they do not). The above is true as of 99 // Go 1.1. In the end it was simpler to rewrite the code to explicitly 100 // understand the format which is this: 101 // 0x30 <length of whole message> <0x02> <length of R> <R> 0x2 102 // <length of S> <S>. 103 104 signature := &Signature{} 105 106 // minimal message is when both numbers are 1 bytes. adding up to: 107 // 0x30 + len + 0x02 + 0x01 + <byte> + 0x2 + 0x01 + <byte> 108 if len(sigStr) < 8 { 109 return nil, errors.New("malformed signature: too short") 110 } 111 // 0x30 112 index := 0 113 if sigStr[index] != 0x30 { 114 return nil, errors.New("malformed signature: no header magic") 115 } 116 index++ 117 // length of remaining message 118 siglen := sigStr[index] 119 index++ 120 if int(siglen+2) > len(sigStr) { 121 return nil, errors.New("malformed signature: bad length") 122 } 123 // trim the slice we're working on so we only look at what matters. 124 sigStr = sigStr[:siglen+2] 125 126 // 0x02 127 if sigStr[index] != 0x02 { 128 return nil, 129 errors.New("malformed signature: no 1st int marker") 130 } 131 index++ 132 133 // Length of signature R. 134 rLen := int(sigStr[index]) 135 // must be positive, must be able to fit in another 0x2, <len> <s> 136 // hence the -3. We assume that the length must be at least one byte. 137 index++ 138 if rLen <= 0 || rLen > len(sigStr)-index-3 { 139 return nil, errors.New("malformed signature: bogus R length") 140 } 141 142 // Then R itself. 143 rBytes := sigStr[index : index+rLen] 144 if der { 145 switch err := canonicalPadding(rBytes); err { 146 case errNegativeValue: 147 return nil, errors.New("signature R is negative") 148 case errExcessivelyPaddedValue: 149 return nil, errors.New("signature R is excessively padded") 150 } 151 } 152 signature.R = new(big.Int).SetBytes(rBytes) 153 index += rLen 154 // 0x02. length already checked in previous if. 155 if sigStr[index] != 0x02 { 156 return nil, errors.New("malformed signature: no 2nd int marker") 157 } 158 index++ 159 160 // Length of signature S. 161 sLen := int(sigStr[index]) 162 index++ 163 // S should be the rest of the string. 164 if sLen <= 0 || sLen > len(sigStr)-index { 165 return nil, errors.New("malformed signature: bogus S length") 166 } 167 168 // Then S itself. 169 sBytes := sigStr[index : index+sLen] 170 if der { 171 switch err := canonicalPadding(sBytes); err { 172 case errNegativeValue: 173 return nil, errors.New("signature S is negative") 174 case errExcessivelyPaddedValue: 175 return nil, errors.New("signature S is excessively padded") 176 } 177 } 178 signature.S = new(big.Int).SetBytes(sBytes) 179 index += sLen 180 181 // sanity check length parsing 182 if index != len(sigStr) { 183 return nil, fmt.Errorf("malformed signature: bad final length %v != %v", 184 index, len(sigStr)) 185 } 186 187 // Verify also checks this, but we can be more sure that we parsed 188 // correctly if we verify here too. 189 // FWIW the ecdsa spec states that R and S must be | 1, N - 1 | 190 // but crypto/ecdsa only checks for Sign != 0. Mirror that. 191 if signature.R.Sign() != 1 { 192 return nil, errors.New("signature R isn't 1 or more") 193 } 194 if signature.S.Sign() != 1 { 195 return nil, errors.New("signature S isn't 1 or more") 196 } 197 if signature.R.Cmp(curve.Params().N) >= 0 { 198 return nil, errors.New("signature R is >= curve.N") 199 } 200 if signature.S.Cmp(curve.Params().N) >= 0 { 201 return nil, errors.New("signature S is >= curve.N") 202 } 203 204 return signature, nil 205 } 206 207 // ParseSignature parses a signature in BER format for the curve type `curve' 208 // into a Signature type, perfoming some basic sanity checks. If parsing 209 // according to the more strict DER format is needed, use ParseDERSignature. 210 func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) { 211 return parseSig(sigStr, curve, false) 212 } 213 214 // ParseDERSignature parses a signature in DER format for the curve type 215 // `curve` into a Signature type. If parsing according to the less strict 216 // BER format is needed, use ParseSignature. 217 func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) { 218 return parseSig(sigStr, curve, true) 219 } 220 221 // canonicalizeInt returns the bytes for the passed big integer adjusted as 222 // necessary to ensure that a big-endian encoded integer can't possibly be 223 // misinterpreted as a negative number. This can happen when the most 224 // significant bit is set, so it is padded by a leading zero byte in this case. 225 // Also, the returned bytes will have at least a single byte when the passed 226 // value is 0. This is required for DER encoding. 227 func canonicalizeInt(val *big.Int) []byte { 228 b := val.Bytes() 229 if len(b) == 0 { 230 b = []byte{0x00} 231 } 232 if b[0]&0x80 != 0 { 233 paddedBytes := make([]byte, len(b)+1) 234 copy(paddedBytes[1:], b) 235 b = paddedBytes 236 } 237 return b 238 } 239 240 // canonicalPadding checks whether a big-endian encoded integer could 241 // possibly be misinterpreted as a negative number (even though OpenSSL 242 // treats all numbers as unsigned), or if there is any unnecessary 243 // leading zero padding. 244 func canonicalPadding(b []byte) error { 245 switch { 246 case b[0]&0x80 == 0x80: 247 return errNegativeValue 248 case len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80: 249 return errExcessivelyPaddedValue 250 default: 251 return nil 252 } 253 } 254 255 // hashToInt converts a hash value to an integer. There is some disagreement 256 // about how this is done. [NSA] suggests that this is done in the obvious 257 // manner, but [SECG] truncates the hash to the bit-length of the curve order 258 // first. We follow [SECG] because that's what OpenSSL does. Additionally, 259 // OpenSSL right shifts excess bits from the number if the hash is too large 260 // and we mirror that too. 261 // This is borrowed from crypto/ecdsa. 262 func hashToInt(hash []byte, c elliptic.Curve) *big.Int { 263 orderBits := c.Params().N.BitLen() 264 orderBytes := (orderBits + 7) / 8 265 if len(hash) > orderBytes { 266 hash = hash[:orderBytes] 267 } 268 269 ret := new(big.Int).SetBytes(hash) 270 excess := len(hash)*8 - orderBits 271 if excess > 0 { 272 ret.Rsh(ret, uint(excess)) 273 } 274 return ret 275 } 276 277 // recoverKeyFromSignature recovers a public key from the signature "sig" on the 278 // given message hash "msg". Based on the algorithm found in section 5.1.5 of 279 // SEC 1 Ver 2.0, page 47-48 (53 and 54 in the pdf). This performs the details 280 // in the inner loop in Step 1. The counter provided is actually the j parameter 281 // of the loop * 2 - on the first iteration of j we do the R case, else the -R 282 // case in step 1.6. This counter is used in the bitcoin compressed signature 283 // format and thus we match bitcoind's behaviour here. 284 func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte, 285 iter int, doChecks bool) (*PublicKey, error) { 286 // 1.1 x = (n * i) + r 287 Rx := new(big.Int).Mul(curve.Params().N, 288 new(big.Int).SetInt64(int64(iter/2))) 289 Rx.Add(Rx, sig.R) 290 if Rx.Cmp(curve.Params().P) != -1 { 291 return nil, errors.New("calculated Rx is larger than curve P") 292 } 293 294 // convert 02<Rx> to point R. (step 1.2 and 1.3). If we are on an odd 295 // iteration then 1.6 will be done with -R, so we calculate the other 296 // term when uncompressing the point. 297 Ry, err := decompressPoint(curve, Rx, iter%2 == 1) 298 if err != nil { 299 return nil, err 300 } 301 302 // 1.4 Check n*R is point at infinity 303 if doChecks { 304 nRx, nRy := curve.ScalarMult(Rx, Ry, curve.Params().N.Bytes()) 305 if nRx.Sign() != 0 || nRy.Sign() != 0 { 306 return nil, errors.New("n*R does not equal the point at infinity") 307 } 308 } 309 310 // 1.5 calculate e from message using the same algorithm as ecdsa 311 // signature calculation. 312 e := hashToInt(msg, curve) 313 314 // Step 1.6.1: 315 // We calculate the two terms sR and eG separately multiplied by the 316 // inverse of r (from the signature). We then add them to calculate 317 // Q = r^-1(sR-eG) 318 invr := new(big.Int).ModInverse(sig.R, curve.Params().N) 319 320 // first term. 321 invrS := new(big.Int).Mul(invr, sig.S) 322 invrS.Mod(invrS, curve.Params().N) 323 sRx, sRy := curve.ScalarMult(Rx, Ry, invrS.Bytes()) 324 325 // second term. 326 e.Neg(e) 327 e.Mod(e, curve.Params().N) 328 e.Mul(e, invr) 329 e.Mod(e, curve.Params().N) 330 minuseGx, minuseGy := curve.ScalarBaseMult(e.Bytes()) 331 332 // TODO(oga) this would be faster if we did a mult and add in one 333 // step to prevent the jacobian conversion back and forth. 334 Qx, Qy := curve.Add(sRx, sRy, minuseGx, minuseGy) 335 336 return &PublicKey{ 337 Curve: curve, 338 X: Qx, 339 Y: Qy, 340 }, nil 341 } 342 343 // SignCompact produces a compact signature of the data in hash with the given 344 // private key on the given koblitz curve. The isCompressed parameter should 345 // be used to detail if the given signature should reference a compressed 346 // public key or not. If successful the bytes of the compact signature will be 347 // returned in the format: 348 // <(byte of 27+public key solution)+4 if compressed >< padded bytes for signature R><padded bytes for signature S> 349 // where the R and S parameters are padde up to the bitlengh of the curve. 350 func SignCompact(curve *KoblitzCurve, key *PrivateKey, 351 hash []byte, isCompressedKey bool) ([]byte, error) { 352 sig, err := key.Sign(hash) 353 if err != nil { 354 return nil, err 355 } 356 357 // bitcoind checks the bit length of R and S here. The ecdsa signature 358 // algorithm returns R and S mod N therefore they will be the bitsize of 359 // the curve, and thus correctly sized. 360 for i := 0; i < (curve.H+1)*2; i++ { 361 pk, err := recoverKeyFromSignature(curve, sig, hash, i, true) 362 if err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 { 363 result := make([]byte, 1, 2*curve.byteSize+1) 364 result[0] = 27 + byte(i) 365 if isCompressedKey { 366 result[0] += 4 367 } 368 // Not sure this needs rounding but safer to do so. 369 curvelen := (curve.BitSize + 7) / 8 370 371 // Pad R and S to curvelen if needed. 372 bytelen := (sig.R.BitLen() + 7) / 8 373 if bytelen < curvelen { 374 result = append(result, 375 make([]byte, curvelen-bytelen)...) 376 } 377 result = append(result, sig.R.Bytes()...) 378 379 bytelen = (sig.S.BitLen() + 7) / 8 380 if bytelen < curvelen { 381 result = append(result, 382 make([]byte, curvelen-bytelen)...) 383 } 384 result = append(result, sig.S.Bytes()...) 385 386 return result, nil 387 } 388 } 389 390 return nil, errors.New("no valid solution for pubkey found") 391 } 392 393 // RecoverCompact verifies the compact signature "signature" of "hash" for the 394 // Koblitz curve in "curve". If the signature matches then the recovered public 395 // key will be returned as well as a boolen if the original key was compressed 396 // or not, else an error will be returned. 397 func RecoverCompact(curve *KoblitzCurve, signature, 398 hash []byte) (*PublicKey, bool, error) { 399 bitlen := (curve.BitSize + 7) / 8 400 if len(signature) != 1+bitlen*2 { 401 return nil, false, errors.New("invalid compact signature size") 402 } 403 404 iteration := int((signature[0] - 27) & ^byte(4)) 405 406 // format is <header byte><bitlen R><bitlen S> 407 sig := &Signature{ 408 R: new(big.Int).SetBytes(signature[1 : bitlen+1]), 409 S: new(big.Int).SetBytes(signature[bitlen+1:]), 410 } 411 // The iteration used here was encoded 412 key, err := recoverKeyFromSignature(curve, sig, hash, iteration, false) 413 if err != nil { 414 return nil, false, err 415 } 416 417 return key, ((signature[0] - 27) & 4) == 4, nil 418 } 419 420 // signRFC6979 generates a deterministic ECDSA signature according to RFC 6979 and BIP 62. 421 func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) { 422 423 privkey := privateKey.ToECDSA() 424 N := order 425 k := nonceRFC6979(privkey.D, hash) 426 inv := new(big.Int).ModInverse(k, N) 427 r, _ := privkey.Curve.ScalarBaseMult(k.Bytes()) 428 if r.Cmp(N) == 1 { 429 r.Sub(r, N) 430 } 431 432 if r.Sign() == 0 { 433 return nil, errors.New("calculated R is zero") 434 } 435 436 e := hashToInt(hash, privkey.Curve) 437 s := new(big.Int).Mul(privkey.D, r) 438 s.Add(s, e) 439 s.Mul(s, inv) 440 s.Mod(s, N) 441 442 if s.Cmp(halforder) == 1 { 443 s.Sub(N, s) 444 } 445 if s.Sign() == 0 { 446 return nil, errors.New("calculated S is zero") 447 } 448 return &Signature{R: r, S: s}, nil 449 } 450 451 // nonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to RFC 6979. 452 // It takes a 32-byte hash as an input and returns 32-byte nonce to be used in ECDSA algorithm. 453 func nonceRFC6979(privkey *big.Int, hash []byte) *big.Int { 454 455 curve := S256() 456 q := curve.Params().N 457 x := privkey 458 alg := fastsha256.New 459 460 qlen := q.BitLen() 461 holen := alg().Size() 462 rolen := (qlen + 7) >> 3 463 bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...) 464 465 // Step B 466 v := bytes.Repeat(oneInitializer, holen) 467 468 // Step C (Go zeroes the all allocated memory) 469 k := make([]byte, holen) 470 471 // Step D 472 k = mac(alg, k, append(append(v, 0x00), bx...)) 473 474 // Step E 475 v = mac(alg, k, v) 476 477 // Step F 478 k = mac(alg, k, append(append(v, 0x01), bx...)) 479 480 // Step G 481 v = mac(alg, k, v) 482 483 // Step H 484 for { 485 // Step H1 486 var t []byte 487 488 // Step H2 489 for len(t)*8 < qlen { 490 v = mac(alg, k, v) 491 t = append(t, v...) 492 } 493 494 // Step H3 495 secret := hashToInt(t, curve) 496 if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 { 497 return secret 498 } 499 k = mac(alg, k, append(v, 0x00)) 500 v = mac(alg, k, v) 501 } 502 } 503 504 // mac returns an HMAC of the given key and message. 505 func mac(alg func() hash.Hash, k, m []byte) []byte { 506 h := hmac.New(alg, k) 507 h.Write(m) 508 return h.Sum(nil) 509 } 510 511 // https://tools.ietf.org/html/rfc6979#section-2.3.3 512 func int2octets(v *big.Int, rolen int) []byte { 513 out := v.Bytes() 514 515 // left pad with zeros if it's too short 516 if len(out) < rolen { 517 out2 := make([]byte, rolen) 518 copy(out2[rolen-len(out):], out) 519 return out2 520 } 521 522 // drop most significant bytes if it's too long 523 if len(out) > rolen { 524 out2 := make([]byte, rolen) 525 copy(out2, out[len(out)-rolen:]) 526 return out2 527 } 528 529 return out 530 } 531 532 // https://tools.ietf.org/html/rfc6979#section-2.3.4 533 func bits2octets(in []byte, curve elliptic.Curve, rolen int) []byte { 534 z1 := hashToInt(in, curve) 535 z2 := new(big.Int).Sub(z1, curve.Params().N) 536 if z2.Sign() < 0 { 537 return int2octets(z1, rolen) 538 } 539 return int2octets(z2, rolen) 540 }