// Verify verifies the signature in r, s of hash using the public key, pub. It // returns true iff the signature is valid. func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { // See [NSA] 3.4.2 c := pub.Curve if r.Sign() == 0 || s.Sign() == 0 { return false } if r.Cmp(c.N) >= 0 || s.Cmp(c.N) >= 0 { return false } e := hashToInt(hash, c) w := new(big.Int).ModInverse(s, c.N) u1 := e.Mul(e, w) u2 := w.Mul(r, w) x1, y1 := c.ScalarBaseMult(u1.Bytes()) x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes()) if x1.Cmp(x2) == 0 { return false } x, _ := c.Add(x1, y1, x2, y2) x.Mod(x, c.N) return x.Cmp(r) == 0 }
// Verify verifies the signature in r, s of hash using the public key, pub. It // returns true iff the signature is valid. func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { // FIPS 186-3, section 4.7 if r.Sign() < 1 || r.Cmp(pub.Q) >= 0 { return false } if s.Sign() < 1 || s.Cmp(pub.Q) >= 0 { return false } w := new(big.Int).ModInverse(s, pub.Q) n := pub.Q.BitLen() if n&7 != 0 { return false } n >>= 3 if n > len(hash) { n = len(hash) } z := new(big.Int).SetBytes(hash[:n]) u1 := new(big.Int).Mul(z, w) u1.Mod(u1, pub.Q) u2 := w.Mul(r, w) u2.Mod(u2, pub.Q) v := u1.Exp(pub.G, u1, pub.P) u2.Exp(pub.Y, u2, pub.P) v.Mul(v, u2) v.Mod(v, pub.P) v.Mod(v, pub.Q) return v.Cmp(r) == 0 }
// rawValueForBig returns an asn1.RawValue which represents the given integer. func rawValueForBig(n *big.Int) asn1.RawValue { b := n.Bytes() if n.Sign() >= 0 && len(b) > 0 && b[0]&0x80 != 0 { // This positive number would be interpreted as a negative // number in ASN.1 because the MSB is set. padded := make([]byte, len(b)+1) copy(padded[1:], b) b = padded } return asn1.RawValue{Tag: 2, Bytes: b} }
// Sign signs an arbitrary length hash (which should be the result of hashing a // larger message) using the private key, priv. It returns the signature as a // pair of integers. The security of the private key depends on the entropy of // rand. func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err os.Error) { // FIPS 186-3, section 4.6 n := priv.Q.BitLen() if n&7 != 0 { err = InvalidPublicKeyError return } n >>= 3 for { k := new(big.Int) buf := make([]byte, n) for { _, err = io.ReadFull(rand, buf) if err != nil { return } k.SetBytes(buf) if k.Sign() > 0 && k.Cmp(priv.Q) < 0 { break } } kInv := new(big.Int).ModInverse(k, priv.Q) r = new(big.Int).Exp(priv.G, k, priv.P) r.Mod(r, priv.Q) if r.Sign() == 0 { continue } if n > len(hash) { n = len(hash) } z := k.SetBytes(hash[:n]) s = new(big.Int).Mul(priv.X, r) s.Add(s, z) s.Mod(s, priv.Q) s.Mul(s, kInv) s.Mod(s, priv.Q) if s.Sign() != 0 { break } } return }
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. func (curve *Curve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b delta := new(big.Int).Mul(z, z) delta.Mod(delta, curve.P) gamma := new(big.Int).Mul(y, y) gamma.Mod(gamma, curve.P) alpha := new(big.Int).Sub(x, delta) if alpha.Sign() == -1 { alpha.Add(alpha, curve.P) } alpha2 := new(big.Int).Add(x, delta) alpha.Mul(alpha, alpha2) alpha2.Set(alpha) alpha.Lsh(alpha, 1) alpha.Add(alpha, alpha2) beta := alpha2.Mul(x, gamma) x3 := new(big.Int).Mul(alpha, alpha) beta8 := new(big.Int).Lsh(beta, 3) x3.Sub(x3, beta8) for x3.Sign() == -1 { x3.Add(x3, curve.P) } x3.Mod(x3, curve.P) z3 := new(big.Int).Add(y, z) z3.Mul(z3, z3) z3.Sub(z3, gamma) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Sub(z3, delta) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Mod(z3, curve.P) beta.Lsh(beta, 2) beta.Sub(beta, x3) if beta.Sign() == -1 { beta.Add(beta, curve.P) } y3 := alpha.Mul(alpha, beta) gamma.Mul(gamma, gamma) gamma.Lsh(gamma, 3) gamma.Mod(gamma, curve.P) y3.Sub(y3, gamma) if y3.Sign() == -1 { y3.Add(y3, curve.P) } y3.Mod(y3, curve.P) return x3, y3, z3 }
func marshalInt(to []byte, n *big.Int) []byte { lengthBytes := to to = to[4:] length := 0 if n.Sign() < 0 { // A negative number has to be converted to two's-complement // form. So we'll subtract 1 and invert. If the // most-significant-bit isn't set then we'll need to pad the // beginning with 0xff in order to keep the number negative. nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bytes := nMinus1.Bytes() for i := range bytes { bytes[i] ^= 0xff } if len(bytes) == 0 || bytes[0]&0x80 == 0 { to[0] = 0xff to = to[1:] length++ } nBytes := copy(to, bytes) to = to[nBytes:] length += nBytes } else if n.Sign() == 0 { // A zero is the zero length string } else { bytes := n.Bytes() if len(bytes) > 0 && bytes[0]&0x80 != 0 { // We'll have to pad this with a 0x00 in order to // stop it looking like a negative number. to[0] = 0 to = to[1:] length++ } nBytes := copy(to, bytes) to = to[nBytes:] length += nBytes } lengthBytes[0] = byte(length >> 24) lengthBytes[1] = byte(length >> 16) lengthBytes[2] = byte(length >> 8) lengthBytes[3] = byte(length) return to }
func testParameterGeneration(t *testing.T, sizes ParameterSizes, L, N int) { var priv PrivateKey params := &priv.Parameters err := GenerateParameters(params, rand.Reader, sizes) if err != nil { t.Errorf("%d: %s", int(sizes), err) return } if params.P.BitLen() != L { t.Errorf("%d: params.BitLen got:%d want:%d", int(sizes), params.P.BitLen(), L) } if params.Q.BitLen() != N { t.Errorf("%d: q.BitLen got:%d want:%d", int(sizes), params.Q.BitLen(), L) } one := new(big.Int) one.SetInt64(1) pm1 := new(big.Int).Sub(params.P, one) quo, rem := new(big.Int).DivMod(pm1, params.Q, new(big.Int)) if rem.Sign() != 0 { t.Errorf("%d: p-1 mod q != 0", int(sizes)) } x := new(big.Int).Exp(params.G, quo, params.P) if x.Cmp(one) == 0 { t.Errorf("%d: invalid generator", int(sizes)) } err = GenerateKey(&priv, rand.Reader) if err != nil { t.Errorf("error generating key: %s", err) return } testSignAndVerify(t, int(sizes), &priv) }
// GenerateKey generates a public&private key pair. The Parameters of the // PrivateKey must already be valid (see GenerateParameters). func GenerateKey(priv *PrivateKey, rand io.Reader) os.Error { if priv.P == nil || priv.Q == nil || priv.G == nil { return os.ErrorString("crypto/dsa: parameters not set up before generating key") } x := new(big.Int) xBytes := make([]byte, priv.Q.BitLen()/8) for { _, err := io.ReadFull(rand, xBytes) if err != nil { return err } x.SetBytes(xBytes) if x.Sign() != 0 && x.Cmp(priv.Q) < 0 { break } } priv.X = x priv.Y = new(big.Int) priv.Y.Exp(priv.G, x, priv.P) return nil }
func marshalBigInt(out *forkableWriter, n *big.Int) (err os.Error) { if n.Sign() < 0 { // A negative number has to be converted to two's-complement // form. So we'll subtract 1 and invert. If the // most-significant-bit isn't set then we'll need to pad the // beginning with 0xff in order to keep the number negative. nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bytes := nMinus1.Bytes() for i := range bytes { bytes[i] ^= 0xff } if len(bytes) == 0 || bytes[0]&0x80 == 0 { err = out.WriteByte(0xff) if err != nil { return } } _, err = out.Write(bytes) } else if n.Sign() == 0 { // Zero is written as a single 0 zero rather than no bytes. err = out.WriteByte(0x00) } else { bytes := n.Bytes() if len(bytes) > 0 && bytes[0]&0x80 != 0 { // We'll have to pad this with 0x00 in order to stop it // looking like a negative number. err = out.WriteByte(0) if err != nil { return } } _, err = out.Write(bytes) } return }
func intLength(n *big.Int) int { length := 4 /* length bytes */ if n.Sign() < 0 { nMinus1 := new(big.Int).Neg(n) nMinus1.Sub(nMinus1, bigOne) bitLen := nMinus1.BitLen() if bitLen%8 == 0 { // The number will need 0xff padding length++ } length += (bitLen + 7) / 8 } else if n.Sign() == 0 { // A zero is the zero length string } else { bitLen := n.BitLen() if bitLen%8 == 0 { // The number will need 0x00 padding length++ } length += (bitLen + 7) / 8 } return length }
// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. func (curve *Curve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) z1z1.Mod(z1z1, curve.P) z2z2 := new(big.Int).Mul(z2, z2) z2z2.Mod(z2z2, curve.P) u1 := new(big.Int).Mul(x1, z2z2) u1.Mod(u1, curve.P) u2 := new(big.Int).Mul(x2, z1z1) u2.Mod(u2, curve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { h.Add(h, curve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) j := new(big.Int).Mul(h, i) s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) s1.Mod(s1, curve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) s2.Mod(s2, curve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { r.Add(r, curve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) x3 := new(big.Int).Set(r) x3.Mul(x3, x3) x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) x3.Mod(x3, curve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) y3.Mul(y3, v) s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) y3.Mod(y3, curve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Mul(z3, h) z3.Mod(z3, curve.P) return x3, y3, z3 }
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a // random source is given, RSA blinding is used. func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) { // TODO(agl): can we get away with reusing blinds? if c.Cmp(priv.N) > 0 { err = DecryptionError{} return } var ir *big.Int if random != nil { // Blinding enabled. Blinding involves multiplying c by r^e. // Then the decryption operation performs (m^e * r^e)^d mod n // which equals mr mod n. The factor of r can then be removed // by multiplying by the multiplicative inverse of r. var r *big.Int for { r, err = rand.Int(random, priv.N) if err != nil { return } if r.Cmp(bigZero) == 0 { r = bigOne } var ok bool ir, ok = modInverse(r, priv.N) if ok { break } } bigE := big.NewInt(int64(priv.E)) rpowe := new(big.Int).Exp(r, bigE, priv.N) cCopy := new(big.Int).Set(c) cCopy.Mul(cCopy, rpowe) cCopy.Mod(cCopy, priv.N) c = cCopy } if priv.Precomputed.Dp == nil { m = new(big.Int).Exp(c, priv.D, priv.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, priv.Primes[0]) } m.Mul(m, priv.Precomputed.Qinv) m.Mod(m, priv.Primes[0]) m.Mul(m, priv.Primes[1]) m.Add(m, m2) for i, values := range priv.Precomputed.CRTValues { prime := priv.Primes[2+i] m2.Exp(c, values.Exp, prime) m2.Sub(m2, m) m2.Mul(m2, values.Coeff) m2.Mod(m2, prime) if m2.Sign() < 0 { m2.Add(m2, prime) } m2.Mul(m2, values.R) m.Add(m, m2) } } if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, priv.N) } return }
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a // random source is given, RSA blinding is used. func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) { // TODO(agl): can we get away with reusing blinds? if c.Cmp(priv.N) > 0 { err = DecryptionError{} return } var ir *big.Int if rand != nil { // Blinding enabled. Blinding involves multiplying c by r^e. // Then the decryption operation performs (m^e * r^e)^d mod n // which equals mr mod n. The factor of r can then be removed // by multipling by the multiplicative inverse of r. var r *big.Int for { r, err = randomNumber(rand, priv.N) if err != nil { return } if r.Cmp(bigZero) == 0 { r = bigOne } var ok bool ir, ok = modInverse(r, priv.N) if ok { break } } bigE := big.NewInt(int64(priv.E)) rpowe := new(big.Int).Exp(r, bigE, priv.N) c.Mul(c, rpowe) c.Mod(c, priv.N) } priv.rwMutex.RLock() if priv.dP == nil && priv.P != nil { priv.rwMutex.RUnlock() priv.rwMutex.Lock() if priv.dP == nil && priv.P != nil { priv.precompute() } priv.rwMutex.Unlock() priv.rwMutex.RLock() } if priv.dP == nil { m = new(big.Int).Exp(c, priv.D, priv.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, priv.dP, priv.P) m2 := new(big.Int).Exp(c, priv.dQ, priv.Q) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, priv.P) } m.Mul(m, priv.qInv) m.Mod(m, priv.P) m.Mul(m, priv.Q) m.Add(m, m2) if priv.dR != nil { // 3-prime CRT. m2.Exp(c, priv.dR, priv.R) m2.Sub(m2, m) m2.Mul(m2, priv.tr) m2.Mod(m2, priv.R) if m2.Sign() < 0 { m2.Add(m2, priv.R) } m2.Mul(m2, priv.pq) m.Add(m, m2) } } priv.rwMutex.RUnlock() if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, priv.N) } return }