// Vrati cisla n, e, d, p, q takova ze, pro nahodne vygenerovana ln-bitova // prvocisla p, q plati, ze e*d + (p-1)(q-1)*X = 1 (mod (p-1)(q-1)) a n = p*q. func GenerateKeys(ln int) (n, e, d, p, q *big.Int) { e = big.NewInt(17) // mělo by stačit n = new(big.Int) m := new(big.Int) t := new(big.Int) // tmp var r *big.Int for { p = NewPrime(ln) q = NewPrime(ln) if p.Cmp(q) == 0 { continue } n.Mul(p, q) // n = p*q m.Mul(t.Sub(p, big1), m.Sub(q, big1)) // m = (p-1)*(q-1) _, d, r = Euklid(m, e, m) if r.Cmp(big1) != 0 { continue } // je GCD(e,m) = 1 ? break } return }
// 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 }
/* Returns the appropriate base-two padded bytes (assuming the underlying big representation remains b2c) */ func BigBytes(i *big.Int) (buff []byte) { ib := i.Bytes() shift := 0 shiftbyte := byte(0) switch i.Cmp(big.NewInt(0)) { case 1: // Positive must be padded if high-bit is 1 if ib[0]&0x80 == 0x80 { shift = 1 } case -1: // Negative numbers with a leading high-bit will also need // to be padded, but with a single bit tagging its 'negativity' if ib[0]&0x80 == 0x80 { shift = 1 shiftbyte = 0x80 } } buff = make([]byte, len(ib)+shift) if shift == 1 { buff[0] = shiftbyte } copy(buff[shift:], ib) return }
// Generate3PrimeKey generates a 3-prime RSA keypair of the given bit size, as // suggested in [1]. Although the public keys are compatible (actually, // indistinguishable) from the 2-prime case, the private keys are not. Thus it // may not be possible to export 3-prime private keys in certain formats or to // subsequently import them into other code. // // Table 1 in [2] suggests that size should be >= 1024 when using 3 primes. // // [1] US patent 4405829 (1972, expired) // [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf func Generate3PrimeKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) { priv = new(PrivateKey) priv.E = 3 pminus1 := new(big.Int) qminus1 := new(big.Int) rminus1 := new(big.Int) totient := new(big.Int) for { p, err := randomPrime(rand, bits/3) if err != nil { return nil, err } todo := bits - p.BitLen() q, err := randomPrime(rand, todo/2) if err != nil { return nil, err } todo -= q.BitLen() r, err := randomPrime(rand, todo) if err != nil { return nil, err } if p.Cmp(q) == 0 || q.Cmp(r) == 0 || r.Cmp(p) == 0 { continue } n := new(big.Int).Mul(p, q) n.Mul(n, r) pminus1.Sub(p, bigOne) qminus1.Sub(q, bigOne) rminus1.Sub(r, bigOne) totient.Mul(pminus1, qminus1) totient.Mul(totient, rminus1) g := new(big.Int) priv.D = new(big.Int) y := new(big.Int) e := big.NewInt(int64(priv.E)) big.GcdInt(g, priv.D, y, e, totient) if g.Cmp(bigOne) == 0 { priv.D.Add(priv.D, totient) priv.P = p priv.Q = q priv.R = r priv.N = n break } } return }
func fibo(n *big.Int) *big.Int { s := n.String() if r, ok := fiboCache[s]; ok { return r } i0 := big.NewInt(0) if n.Cmp(i0) <= 0 { return i0 } if n.Cmp(big.NewInt(2)) <= 0 { return big.NewInt(1) } n1 := big.NewInt(-1) n1.Add(n1, n) n1 = fibo(n1) n2 := big.NewInt(-2) n2.Add(n2, n) n2 = fibo(n2) i0.Add(n1, n2) fiboCache[s] = i0 return i0 }
// Zjisti a0, b0, z tak aby: a0*x + b0*y = z (mod n) func Euklid(x, y, n *big.Int) (a0, b0, z *big.Int) { a0 = big1 a := big0 b0 = big0 b := big1 g := new(big.Int) t := new(big.Int) // tmp if x.Cmp(y) < 0 { x, y = y, x a0, a, b0, b = b0, b, a0, a } for { z = y _, y = g.Div(x, y) x = z a0, a = a, _Euklid_sub(a0, t.Mul(a, g), n) b0, b = b, _Euklid_sub(b0, t.Mul(b, g), n) if y.Cmp(big0) == 0 { break } } return }
// 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 }
func (h *Hash) l3(m []byte, iter int) []byte { i := 0 k1 := new(big.Int) k2 := new(big.Int) for need := iter + 1; need > 0; i++ { t := h.kdf(224, 128*(i+1))[16*i : 16*(i+1)] k1.SetBytes(t[:8]) k2.SetBytes(t[8:]) if k1.Cmp(p64) == -1 && k2.Cmp(p64) == -1 { need-- } } mint := newInt(m) m1 := new(big.Int).Div(mint, p64p32) m2 := new(big.Int).Mod(mint, p64p32) y := new(big.Int).Add(m1, k1) y.Mul(y, new(big.Int).Add(m2, k2)) y.Mod(y, p64) Y := make([]byte, 8) copy(Y[8-len(y.Bytes()):], y.Bytes()) return Y }
func Fact(n *big.Int) { ans := big.NewInt(0) if n.Cmp(1) != 0 { ans = factcalc(n) } else { ans.Set(1) } fmt.Printf("%d factorial is %d\n", n, ans) }
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit // size, as suggested in [1]. Although the public keys are compatible // (actually, indistinguishable) from the 2-prime case, the private keys are // not. Thus it may not be possible to export multi-prime private keys in // certain formats or to subsequently import them into other code. // // Table 1 in [2] suggests maximum numbers of primes for a given size. // // [1] US patent 4405829 (1972, expired) // [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) { priv = new(PrivateKey) priv.E = 65537 if nprimes < 2 { return nil, errors.New("rsa.GenerateMultiPrimeKey: nprimes must be >= 2") } primes := make([]*big.Int, nprimes) NextSetOfPrimes: for { todo := bits for i := 0; i < nprimes; i++ { primes[i], err = rand.Prime(random, todo/(nprimes-i)) if err != nil { return nil, err } todo -= primes[i].BitLen() } // Make sure that primes is pairwise unequal. for i, prime := range primes { for j := 0; j < i; j++ { if prime.Cmp(primes[j]) == 0 { continue NextSetOfPrimes } } } n := new(big.Int).Set(bigOne) totient := new(big.Int).Set(bigOne) pminus1 := new(big.Int) for _, prime := range primes { n.Mul(n, prime) pminus1.Sub(prime, bigOne) totient.Mul(totient, pminus1) } g := new(big.Int) priv.D = new(big.Int) y := new(big.Int) e := big.NewInt(int64(priv.E)) big.GcdInt(g, priv.D, y, e, totient) if g.Cmp(bigOne) == 0 { priv.D.Add(priv.D, totient) priv.Primes = primes priv.N = n break } } priv.Precompute() return }
// GenerateKeyPair generates an RSA keypair of the given bit size. func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) { priv = new(PrivateKey) // Smaller public exponents lead to faster public key // operations. Since the exponent must be coprime to // (p-1)(q-1), the smallest possible value is 3. Some have // suggested that a larger exponent (often 2**16+1) be used // since previous implementation bugs[1] were avoided when this // was the case. However, there are no current reasons not to use // small exponents. // [1] http://marc.info/?l=cryptography&m=115694833312008&w=2 priv.E = 3 pminus1 := new(big.Int) qminus1 := new(big.Int) totient := new(big.Int) for { p, err := randomPrime(rand, bits/2) if err != nil { return nil, err } q, err := randomPrime(rand, bits/2) if err != nil { return nil, err } if p.Cmp(q) == 0 { continue } n := new(big.Int).Mul(p, q) pminus1.Sub(p, bigOne) qminus1.Sub(q, bigOne) totient.Mul(pminus1, qminus1) g := new(big.Int) priv.D = new(big.Int) y := new(big.Int) e := big.NewInt(int64(priv.E)) big.GcdInt(g, priv.D, y, e, totient) if g.Cmp(bigOne) == 0 { priv.D.Add(priv.D, totient) priv.P = p priv.Q = q priv.N = n break } } return }
// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y) //y² y2.Mod(y2, BitCurve.P) //y²%P x3 := new(big.Int).Mul(x, x) //x² x3.Mul(x3, x) //x³ x3.Add(x3, BitCurve.B) //x³+B x3.Mod(x3, BitCurve.P) //(x³+B)%P return x3.Cmp(y2) == 0 }
// modInverse returns ia, the inverse of a in the multiplicative group of prime // order n. It requires that a be a member of the group (i.e. less than n). func modInverse(a, n *big.Int) (ia *big.Int) { g := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(g, x, y, a, n) if x.Cmp(bigOne) < 0 { // 0 is not the multiplicative inverse of any element so, if x // < 1, then x is negative. x.Add(x, n) } return x }
// 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 }
// Based on the value received from the remote side. // If either the provided input is too large (>P) or // the resultant check is invalid, an error is returned. // // Technically could be made to run faster if it didn't // validate, but easier here than elsewhere. func (self *DHData) ComputeShared(in *big.Int) (out *big.Int, err os.Error) { // Ensure 2 < in < self.P if in.Cmp(big.NewInt(2)) != 1 || in.Cmp(self.P) != -1 { err = os.NewError("Invalid DH Key (size)") return } out = big.NewInt(0) //q := self.ComputePublic() /*chk := big.NewInt(0) chk.Exp(in, q, self.P) if chk.Cmp(big.NewInt(1)) != 0 { err = os.NewError("Invalid DH Key (shape)") }*/ out.Exp(in, self.s, self.P) return }
func (curve *Curve) Add(p1, p2 *Point) *Point { fmt.Printf("a") if p1 == nil { return p2 } if p2 == nil { return p1 } lambda_numerator := new(big.Int) lambda_denominator := new(big.Int) lambda := new(big.Int) lambda_numerator.Sub(p2.Y, p1.Y) lambda_denominator.Sub(p2.X, p1.X) if lambda_denominator.Cmp(BigZero) == -1 { //if Y is negative lambda_denominator.Neg(lambda_denominator) lambda_denominator.Sub(curve.P, lambda_denominator) } lambda_denominator, ok := modInverse(lambda_denominator, curve.P) if !ok { fmt.Printf("Add : Not ok\n") return nil } lambda.Mul(lambda_numerator, lambda_denominator) lambda = lambda.Mod(lambda, curve.P) p3 := NewPoint() p3.X.Exp(lambda, BigTwo, curve.P) p3.X.Sub(p3.X, p1.X) p3.X.Sub(p3.X, p2.X) p3.X = p3.X.Mod(p3.X, curve.P) p3.Y.Sub(p1.X, p3.X) p3.Y.Mul(lambda, p3.Y) p3.Y.Sub(p3.Y, p1.Y) p3.Y = p3.Y.Mod(p3.Y, curve.P) if p3.X.Cmp(BigZero) == -1 { //if X is negative p3.X.Neg(p3.X) p3.X.Sub(curve.P, p3.X) } if p3.Y.Cmp(BigZero) == -1 { //if Y is negative p3.Y.Neg(p3.Y) p3.Y.Sub(curve.P, p3.Y) } return p3 }
// IsOnCurve returns true if the given (x,y) lies on the curve. func (curve *Curve) IsOnCurve(x, y *big.Int) bool { // y² = x³ - 3x + b y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.P) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) threeX := new(big.Int).Lsh(x, 1) threeX.Add(threeX, x) x3.Sub(x3, threeX) x3.Add(x3, curve.B) x3.Mod(x3, curve.P) return x3.Cmp(y2) == 0 }
// 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) } m = new(big.Int).Exp(c, priv.D, priv.N) if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, priv.N) } return }
//encodes big.Int to base58 string func Big2Base58(val *big.Int) Base58 { answer := "" valCopy := new(big.Int).Abs(val) //copies big.Int if val.Cmp(big.NewInt(0)) <= 0 { //if it is less than 0, returns empty string return Base58("") } tmpStr := "" tmp := new(big.Int) for valCopy.Cmp(big.NewInt(0)) > 0 { //converts the number into base58 tmp.Mod(valCopy, big.NewInt(58)) //takes modulo 58 value valCopy.Div(valCopy, big.NewInt(58)) //divides the rest by 58 tmpStr += alphabet[tmp.Int64() : tmp.Int64()+1] //encodes } for i := (len(tmpStr) - 1); i > -1; i-- { answer += tmpStr[i : i+1] //reverses the order } return Base58(answer) //returns }
// modInverse returns ia, the inverse of a in the multiplicative group of prime // order n. It requires that a be a member of the group (i.e. less than n). func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { g := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(g, x, y, a, n) if g.Cmp(bigOne) != 0 { // In this case, a and n aren't coprime and we cannot calculate // the inverse. This happens because the values of n are nearly // prime (being the product of two primes) rather than truly // prime. return } if x.Cmp(bigOne) < 0 { // 0 is not the multiplicative inverse of any element so, if x // < 1, then x is negative. x.Add(x, n) } return x, true }
func RabinMiller(p *big.Int) bool { pdec := new(big.Int).Sub(p, big.NewInt(1)) // = p - 1 big2 := big.NewInt(2) for i := 0; i < 20; i++ { x := RandNumSmaller(p) stg := new(big.Int).Exp(x, pdec, p) // = x^(p-1) mod p if stg.Cmp(big1) != 0 { return false } // test na Carmichaelova cisla (kontrola zda x^[(p-1)/2] je +1 nebo -1) p2 := new(big.Int).Rsh(p, 1) // = (p - 1)/2 for { stg.Exp(x, p2, p) if stg.Cmp(pdec) == 0 { break } if stg.Cmp(big1) != 0 { return false } _, res := p2.Div(p2, big2) if res.Cmp(big1) == 0 { break } } } return true }
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) }
func recursive(in int64, value *big.Int, v vector.IntVector, primeIndex int, primes []*big.Int, winner *big.Int, winner2 *vector.IntVector) { if in > 4000000 { if value.Cmp(winner) < 0 || winner.Cmp(big.NewInt(-1)) == 0 { winner.Set(value) *winner2 = v fmt.Println(in, winner, *winner2) //fmt.Print(in, winner, *winner2, " (") //for k, v := range *winner2 { // fmt.Print(primes[k], "**", v, " * ") //} //fmt.Println(")") } return } for i := int64(15); i >= 1; i -= 1 { var factor big.Int factor.Exp(primes[primeIndex], big.NewInt(i), nil) //fmt.Println(factor, i, primes[primeIndex]) newV := v.Copy() newV.Push(int(i)) var newValue big.Int newValue.Mul(value, &factor) recursive(in*(2*i+1)-i, &newValue, newV, primeIndex+1, primes, winner, winner2) } }
// 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 (priv *PrivateKey) Validate() os.Error { // Check that p, q and, maybe, r are prime. Note that this is just a // sanity check. Since the random witnesses chosen by ProbablyPrime are // deterministic, given the candidate number, it's easy for an attack // to generate composites that pass this test. if !big.ProbablyPrime(priv.P, 20) { return os.ErrorString("P is composite") } if !big.ProbablyPrime(priv.Q, 20) { return os.ErrorString("Q is composite") } if priv.R != nil && !big.ProbablyPrime(priv.R, 20) { return os.ErrorString("R is composite") } // Check that p*q*r == n. modulus := new(big.Int).Mul(priv.P, priv.Q) if priv.R != nil { modulus.Mul(modulus, priv.R) } if modulus.Cmp(priv.N) != 0 { return os.ErrorString("invalid modulus") } // Check that e and totient(p, q, r) are coprime. pminus1 := new(big.Int).Sub(priv.P, bigOne) qminus1 := new(big.Int).Sub(priv.Q, bigOne) totient := new(big.Int).Mul(pminus1, qminus1) if priv.R != nil { rminus1 := new(big.Int).Sub(priv.R, bigOne) totient.Mul(totient, rminus1) } e := big.NewInt(int64(priv.E)) gcd := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(gcd, x, y, totient, e) if gcd.Cmp(bigOne) != 0 { return os.ErrorString("invalid public exponent E") } // Check that de ≡ 1 (mod totient(p, q, r)) de := new(big.Int).Mul(priv.D, e) de.Mod(de, totient) if de.Cmp(bigOne) != 0 { return os.ErrorString("invalid private exponent D") } return nil }
func (priv *PrivateKey) Validate() os.Error { // Check that the prime factors are actually prime. Note that this is // just a sanity check. Since the random witnesses chosen by // ProbablyPrime are deterministic, given the candidate number, it's // easy for an attack to generate composites that pass this test. for _, prime := range priv.Primes { if !big.ProbablyPrime(prime, 20) { return os.ErrorString("Prime factor is composite") } } // Check that Πprimes == n. modulus := new(big.Int).Set(bigOne) for _, prime := range priv.Primes { modulus.Mul(modulus, prime) } if modulus.Cmp(priv.N) != 0 { return os.ErrorString("invalid modulus") } // Check that e and totient(Πprimes) are coprime. totient := new(big.Int).Set(bigOne) for _, prime := range priv.Primes { pminus1 := new(big.Int).Sub(prime, bigOne) totient.Mul(totient, pminus1) } e := big.NewInt(int64(priv.E)) gcd := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(gcd, x, y, totient, e) if gcd.Cmp(bigOne) != 0 { return os.ErrorString("invalid public exponent E") } // Check that de ≡ 1 (mod totient(Πprimes)) de := new(big.Int).Mul(priv.D, e) de.Mod(de, totient) if de.Cmp(bigOne) != 0 { return os.ErrorString("invalid private exponent D") } return nil }
// GenerateParameters puts a random, valid set of DSA parameters into params. // This function takes many seconds, even on fast machines. func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err os.Error) { // This function doesn't follow FIPS 186-3 exactly in that it doesn't // use a verification seed to generate the primes. The verification // seed doesn't appear to be exported or used by other code and // omitting it makes the code cleaner. var L, N int switch sizes { case L1024N160: L = 1024 N = 160 case L2048N224: L = 2048 N = 224 case L2048N256: L = 2048 N = 256 case L3072N256: L = 3072 N = 256 default: return os.ErrorString("crypto/dsa: invalid ParameterSizes") } qBytes := make([]byte, N/8) pBytes := make([]byte, L/8) q := new(big.Int) p := new(big.Int) rem := new(big.Int) one := new(big.Int) one.SetInt64(1) GeneratePrimes: for { _, err = io.ReadFull(rand, qBytes) if err != nil { return } qBytes[len(qBytes)-1] |= 1 qBytes[0] |= 0x80 q.SetBytes(qBytes) if !big.ProbablyPrime(q, numMRTests) { continue } for i := 0; i < 4*L; i++ { _, err = io.ReadFull(rand, pBytes) if err != nil { return } pBytes[len(pBytes)-1] |= 1 pBytes[0] |= 0x80 p.SetBytes(pBytes) rem.Mod(p, q) rem.Sub(rem, one) p.Sub(p, rem) if p.BitLen() < L { continue } if !big.ProbablyPrime(p, numMRTests) { continue } params.P = p params.Q = q break GeneratePrimes } } h := new(big.Int) h.SetInt64(2) g := new(big.Int) pm1 := new(big.Int).Sub(p, one) e := new(big.Int).Div(pm1, q) for { g.Exp(h, e, p) if g.Cmp(one) == 0 { h.Add(h, one) continue } params.G = g return } panic("unreachable") }
// 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 }
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit // size, as suggested in [1]. Although the public keys are compatible // (actually, indistinguishable) from the 2-prime case, the private keys are // not. Thus it may not be possible to export multi-prime private keys in // certain formats or to subsequently import them into other code. // // Table 1 in [2] suggests maximum numbers of primes for a given size. // // [1] US patent 4405829 (1972, expired) // [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err os.Error) { priv = new(PrivateKey) // Smaller public exponents lead to faster public key // operations. Since the exponent must be coprime to // (p-1)(q-1), the smallest possible value is 3. Some have // suggested that a larger exponent (often 2**16+1) be used // since previous implementation bugs[1] were avoided when this // was the case. However, there are no current reasons not to use // small exponents. // [1] http://marc.info/?l=cryptography&m=115694833312008&w=2 priv.E = 3 if nprimes < 2 { return nil, os.ErrorString("rsa.GenerateMultiPrimeKey: nprimes must be >= 2") } primes := make([]*big.Int, nprimes) NextSetOfPrimes: for { todo := bits for i := 0; i < nprimes; i++ { primes[i], err = rand.Prime(random, todo/(nprimes-i)) if err != nil { return nil, err } todo -= primes[i].BitLen() } // Make sure that primes is pairwise unequal. for i, prime := range primes { for j := 0; j < i; j++ { if prime.Cmp(primes[j]) == 0 { continue NextSetOfPrimes } } } n := new(big.Int).Set(bigOne) totient := new(big.Int).Set(bigOne) pminus1 := new(big.Int) for _, prime := range primes { n.Mul(n, prime) pminus1.Sub(prime, bigOne) totient.Mul(totient, pminus1) } g := new(big.Int) priv.D = new(big.Int) y := new(big.Int) e := big.NewInt(int64(priv.E)) big.GcdInt(g, priv.D, y, e, totient) if g.Cmp(bigOne) == 0 { priv.D.Add(priv.D, totient) priv.Primes = primes priv.N = n break } } priv.Precompute() return }
func factcalc(f *big.Int) *big.Int { if f.Cmp(1) != 0 { return big.Mul(f, factcalc(f.Sub(f, 1))) } return big.NewInt(1) }