func LCM(a *big.Int, b *big.Int) (c *big.Int) { x := big.Int{} c = big.NewInt(1) c.Mul(a, b) x.GCD(nil, nil, a, b) c.Div(c, &x) 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 error) { priv = new(PrivateKey) priv.E = 65537 if nprimes < 2 { return nil, errors.New("crypto/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)) g.GCD(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 }
// Returns (N, e, d) of the given size that encrypts decBytes to encBytes func chosenEncrytion(decBytes, encBytes []byte, keySize int) (N, e, d *big.Int) { padM := new(big.Int).SetBytes(encBytes) sig := new(big.Int).SetBytes(decBytes) eveP, evePFactors := choosePrime(keySize/2, padM, sig, nil) eveQ, eveQFactors := choosePrime(keySize/2, padM, sig, evePFactors) eveN := new(big.Int).Mul(eveP, eveQ) ep := pohlig(padM, sig, eveP, evePFactors) eq := pohlig(padM, sig, eveQ, eveQFactors) evePhi := new(big.Int).Set(eveN) evePhi.Sub(evePhi, eveP) evePhi.Sub(evePhi, eveQ) evePhi.Add(evePhi, big.NewInt(1)) // From Wikipedia CRT page eveModuli := make(map[*big.Int]*big.Int) newP := new(big.Int).Sub(eveP, big.NewInt(1)) newQ := new(big.Int).Sub(eveQ, big.NewInt(1)) // Remove "2" factor so CRT works. newP.Div(newP, big.NewInt(2)) newQ.Div(newQ, big.NewInt(2)) eveModuli[newP] = new(big.Int).Mod(ep, newP) eveModuli[newQ] = new(big.Int).Mod(eq, newQ) if new(big.Int).Mod(eq, big.NewInt(2)).Cmp(new(big.Int).Mod(ep, big.NewInt(2))) != 0 { log.Fatal("ep and eq are not compatible and CRT won't work") } eveModuli[big.NewInt(4)] = new(big.Int).Mod(eq, big.NewInt(4)) eveE := new(big.Int) for n, a := range eveModuli { N := new(big.Int).Set(evePhi) scratch := new(big.Int) scratch.Mod(N, n) if scratch.Cmp(new(big.Int)) != 0 { log.Fatalf("hmm %d / %d", N, n) } N.Div(N, n) scratch.GCD(nil, nil, N, n) if scratch.Cmp(big.NewInt(1)) != 0 { log.Fatalf("GCD: %d", scratch) } N.ModInverse(N, n) N.Mul(N, evePhi) N.Div(N, n) N.Mul(N, a) eveE.Add(eveE, N) eveE.Mod(eveE, evePhi) } return eveN, eveE, new(big.Int).ModInverse(eveE, evePhi) }
/*从crypto/rsa复制 */ func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { g := new(big.Int) x := new(big.Int) y := new(big.Int) g.GCD(x, y, a, n) if g.Cmp(bigOne) != 0 { return } if x.Cmp(bigOne) < 0 { x.Add(x, n) } return x, true }
// SmallPrimeTest determins if N is a small prime // or divisible by a small prime. func SmallPrimeTest(N *big.Int) int { if N.Sign() <= 0 { panic("SmallPrimeTest for positive integers only") } if N.BitLen() <= 10 { n := uint16(N.Uint64()) i := sort.Search(len(primes10), func(i int) bool { return primes10[i] >= n }) if i >= len(primes10) || n != primes10[i] { return IsComposite } return IsPrime } // quick test for N even if N.Bits()[0]&1 == 0 { return IsComposite } // compare several small gcds for efficency z := new(big.Int) if z.GCD(nil, nil, N, prodPrimes10A).Cmp(one) == 1 { return IsComposite } if z.GCD(nil, nil, N, prodPrimes10B).Cmp(one) == 1 { return IsComposite } if z.GCD(nil, nil, N, prodPrimes10C).Cmp(one) == 1 { return IsComposite } if z.GCD(nil, nil, N, prodPrimes10D).Cmp(one) == 1 { return IsComposite } return Undetermined }
func moBachShallit58(a, n *big.Int, pf []pExp) *big.Int { n1 := new(big.Int).Sub(n, one) var x, y, o1, g big.Int mo := big.NewInt(1) for _, pe := range pf { y.Quo(n1, y.Exp(pe.prime, big.NewInt(pe.exp), nil)) var o int64 for x.Exp(a, &y, n); x.Cmp(one) > 0; o++ { x.Exp(&x, pe.prime, n) } o1.Exp(pe.prime, o1.SetInt64(o), nil) mo.Mul(mo, o1.Quo(&o1, g.GCD(nil, nil, mo, &o1))) } return mo }
func pollardRho(task *Task, toFactor *big.Int, constant int64) (*big.Int, bool) { //~ x := new(big.Int).Set(TWO) c := big.NewInt(constant) y := big.NewInt(2) y.Add(y, c) x := c.Add(c, TWO) //~ //~ dprint(toFactor) //~ dprint(ZERO) //~ sub1 := new(big.Int).Sub(toFactor, ONE) //~ x := new(big.Int).Rand(rng, sub1) //~ y := new(big.Int).Rand(rng, sub1) d := big.NewInt(1) r := new(big.Int) rand_const := ONE //r.Rand(rng, toFactor) if r.Mod(toFactor, TWO).Cmp(ZERO) == 0 { return TWO, false } i := 0 for d.Cmp(ONE) == 0 { /* */ //~ x = x.Set(y) // x = f(x) x = x.Mul(x, x).Add(x, rand_const).Mod(x, toFactor) // y = f(f(y)) y = y.Mul(y, y).Add(y, rand_const).Mod(y, toFactor) y = y.Mul(y, y).Add(y, rand_const).Mod(y, toFactor) r.Sub(x, y).Abs(r) d = r.GCD(nil, nil, r, toFactor) i++ if d.Cmp(toFactor) == 0 { //~ dprint("failed. retrying") return d, true } else if task.ShouldStop() { return d, true } } return d, false }
func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil }
func Rho(n *big.Int) (*big.Int, *big.Int) { c := big.NewInt(10) a0 := big.NewInt(1) a1 := new(big.Int) a1 = a1.Mul(a0, a0).Add(a1, c) a2 := new(big.Int) a2 = a2.Mul(a1, a1).Add(a2, c) d := new(big.Int) g := new(big.Int) for Equal(g.GCD(nil, nil, n, d.Sub(a2, a1).Abs(d)), big1) { a1.Mul(a1, a1).Add(a1, c).Mod(a1, n) a2.Mul(a2, a2).Add(a2, c).Mod(a2, n) a2.Mul(a2, a2).Add(a2, c).Mod(a2, n) } return g, n.Div(n, g) }
// ModInverse calculates the modular inverse of a over P func (curve Curve) ModInverse(a *big.Int) (*big.Int, error) { // since P should be a prime, any GCD calculation is really a waste if a != P if a.Cmp(curve.Params.N) == 0 { return nil, ErrNotRelPrime } if a.Cmp(big.NewInt(1)) == 0 { // this should never happen return nil, ErrNotRelPrime } if a.Cmp(big.NewInt(0)) == 0 { // this should never happen return nil, ErrNotRelPrime } z := new(big.Int) z = z.GCD(nil, nil, a, curve.Params.N) if z.Cmp(big.NewInt(1)) == 0 { z = z.ModInverse(a, curve.Params.N) return z, nil } return nil, ErrNotRelPrime }
// Join takes k shares that resulted from Split and recovers the original // secret. The shares can be presented in any order, however the (zero based) // index of each share must be known and provided in shareNumbers. func Join(shares []*big.Int, shareNumbers []int, modulus *big.Int) (*big.Int, error) { if len(shares) != len(shareNumbers) { return nil, errors.New("lengths of shares and shareNumbers must match") } secret := new(big.Int) zero := new(big.Int) for i := 0; i < len(shares); i++ { if shareNumbers[i] < 0 { return nil, errors.New("found negative share number") } c := big.NewInt(1) for j := 0; j < len(shares); j++ { if i == j { continue } bigJ := big.NewInt(int64(shareNumbers[j] + 1)) c.Mul(c, bigJ) bigJ.Sub(bigJ, big.NewInt(int64(shareNumbers[i]+1))) if bigJ.Cmp(zero) < 0 { bigJ.Add(bigJ, modulus) } d := new(big.Int) x := new(big.Int) y := new(big.Int) d.GCD(x, y, bigJ, modulus) if x.Cmp(zero) < 0 { x.Add(x, modulus) } c.Mul(c, x) c.Mod(c, modulus) } c.Mul(c, shares[i]) secret.Add(secret, c) } secret.Mod(secret, modulus) return secret, nil }
func checkGCD(n, g *big.Int) (newN, newG *big.Int, ok bool) { var z big.Int g.Abs(g) z.GCD(nil, nil, n, g) if z.Cmp(n) == 0 { return nil, nil, false } if z.Cmp(one) == 0 { return nil, nil, false } n.Div(n, &z) return n, &z, true }
// Validate performs basic sanity checks on the key. // It returns nil if the key is valid, or else an error describing a problem. func (priv *PrivateKey) Validate() 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 !prime.ProbablyPrime(20) { return errors.New("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 errors.New("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) gcd.GCD(x, y, totient, e) if gcd.Cmp(bigOne) != 0 { return errors.New("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 errors.New("invalid private exponent D") } return nil }
// 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) g.GCD(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 }
// 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("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") } primes := make([]*big.Int, nprimes) NextSetOfPrimes: for { todo := bits // crypto/rand should set the top two bits in each prime. // Thus each prime has the form // p_i = 2^bitlen(p_i) × 0.11... (in base 2). // And the product is: // P = 2^todo × α // where α is the product of nprimes numbers of the form 0.11... // // If α < 1/2 (which can happen for nprimes > 2), we need to // shift todo to compensate for lost bits: the mean value of 0.11... // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 // will give good results. if nprimes >= 7 { todo += (nprimes - 2) / 5 } 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) } if n.BitLen() != bits { // This should never happen for nprimes == 2 because // crypto/rand should set the top two bits in each prime. // For nprimes > 2 we hope it does not happen often. continue NextSetOfPrimes } g := new(big.Int) priv.D = new(big.Int) y := new(big.Int) e := big.NewInt(int64(priv.E)) g.GCD(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 main() { scanner := bufio.NewScanner(os.Stdin) var z big.Int var a, b, c big.Int var r big.Int two := big.NewInt(2) var n_add, n_sub, n_mul2, n_div2, n_gcd, n_sqr, n_invmod, n_exptmod int for scanner.Scan() { cmd := scanner.Text() fmt.Println(n_add, n_sub, n_mul2, n_div2, n_gcd, n_sqr, n_invmod) switch cmd { case "add_d", "add": n_add++ next(scanner, &a) next(scanner, &b) next(scanner, &r) z.Add(&a, &b) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "sub_d", "sub": n_sub++ next(scanner, &a) next(scanner, &b) next(scanner, &r) z.Sub(&a, &b) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "mul2": n_mul2++ next(scanner, &a) next(scanner, &r) z.Mul(&a, two) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "div2": n_div2++ next(scanner, &a) next(scanner, &r) z.Div(&a, two) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "sqr": n_sqr++ next(scanner, &a) next(scanner, &r) z.Mul(&a, &a) if false && z.Cmp(&r) != 0 { fmt.Printf("sqr: %s %s %s\n", a.String(), r.String(), z.String()) } case "gcd": n_gcd++ next(scanner, &a) next(scanner, &b) next(scanner, &r) z.GCD(nil, nil, &a, &b) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "invmod": n_invmod++ next(scanner, &a) next(scanner, &b) next(scanner, &r) z.ModInverse(&a, &b) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } case "exptmod": n_exptmod++ next(scanner, &a) next(scanner, &b) next(scanner, &c) next(scanner, &r) z.Exp(&a, &b, &c) if z.Cmp(&r) != 0 { fmt.Println(a, b, r, z) } default: // nothing } } }
// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit // size and the given random source, 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) (*PrivateKey, error) { priv := new(PrivateKey) priv.E = 65537 if nprimes < 2 { return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") } if bits < 64 { primeLimit := float64(uint64(1) << uint(bits/nprimes)) // pi approximates the number of primes less than primeLimit pi := primeLimit / (math.Log(primeLimit) - 1) // Generated primes start with 11 (in binary) so we can only // use a quarter of them. pi /= 4 // Use a factor of two to ensure that key generation terminates // in a reasonable amount of time. pi /= 2 if pi <= float64(nprimes) { return nil, errors.New("crypto/rsa: too few primes of given length to generate an RSA key") } } primes := make([]*big.Int, nprimes) NextSetOfPrimes: for { todo := bits // crypto/rand should set the top two bits in each prime. // Thus each prime has the form // p_i = 2^bitlen(p_i) × 0.11... (in base 2). // And the product is: // P = 2^todo × α // where α is the product of nprimes numbers of the form 0.11... // // If α < 1/2 (which can happen for nprimes > 2), we need to // shift todo to compensate for lost bits: the mean value of 0.11... // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 // will give good results. if nprimes >= 7 { todo += (nprimes - 2) / 5 } for i := 0; i < nprimes; i++ { var err error 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) } if n.BitLen() != bits { // This should never happen for nprimes == 2 because // crypto/rand should set the top two bits in each prime. // For nprimes > 2 we hope it does not happen often. continue NextSetOfPrimes } g := new(big.Int) priv.D = new(big.Int) e := big.NewInt(int64(priv.E)) g.GCD(priv.D, nil, e, totient) if g.Cmp(bigOne) == 0 { if priv.D.Sign() < 0 { priv.D.Add(priv.D, totient) } priv.Primes = primes priv.N = n break } } priv.Precompute() return priv, nil }
// CalculateBlindingParams generates the w,z,e,d,a,b privateParams blinding parameters and calculates r1,r2 (included in privateParams) func (client BlindingClient) CalculateBlindingParams(params *SignRequestPublicInt) (privateParams *BlindingParamsPrivateInt, err error) { var loopcount int for { if loopcount > eccutil.MaxLoopCount { return nil, eccutil.ErrMaxLoop } ScalarRs1, err := client.curve.ExtractR(params.PointRs1) if err != nil { return nil, err } ScalarRs2, err := client.curve.ExtractR(params.PointRs2) if err != nil { return nil, err } loopcount++ ScalarW, err := client.curve.GenNVint() // This limits W substantially and is likely unnecessary if err != nil { continue } ScalarZ, err := client.curve.GenNVint() // This limits Z substantially and is likely unnecessary if err != nil { continue } ScalarE := new(big.Int) ScalarD := new(big.Int) gcd := new(big.Int) gcd = gcd.GCD(ScalarE, ScalarD, ScalarW, ScalarZ) // Int.GCD(w, z, e, d) == 1 if gcd.Cmp(eccutil.TestOne) != 0 { continue } ScalarA, err := client.curve.GenNVint() // This limits A substantially and is likely unnecessary if err != nil { continue } ScalarB, err := client.curve.GenNVint() // This limits B substantially and is likely unnecessary if err != nil { continue } _, _ = ScalarA, ScalarB ta := eccutil.ManyMult(ScalarW, ScalarA, params.ScalarLs1).Bytes() // w * a * ls1 -> byte ta tb := eccutil.ManyMult(ScalarZ, ScalarB, params.ScalarLs2).Bytes() // z * b * ls2 -> byte tb PointR1 := client.curve.ScalarMult(params.PointRs1, ta) PointR2 := client.curve.ScalarMult(params.PointRs2, tb) ScalarR1, err := client.curve.ExtractR(PointR1) // scalarmult(ta,R1).x mod P != 0 if err != nil { continue } ScalarR2, err := client.curve.ExtractR(PointR2) // scalarmult(tb,R2).x mod P != 0 if err != nil { continue } // Probably useless test _, err = client.curve.TestParams(ScalarW, ScalarZ, ScalarE, ScalarD, ScalarA, ScalarB, ScalarR1, ScalarR2, ScalarRs1, ScalarRs2, params.ScalarLs1, params.ScalarLs2) if err != nil { continue } bp := new(BlindingParamsPrivateInt) bp.ScalarW, bp.ScalarZ = ScalarW, ScalarZ bp.ScalarE, bp.ScalarD = ScalarE, ScalarD bp.ScalarA, bp.ScalarB = ScalarA, ScalarB bp.PointR1, bp.PointR2 = PointR1, PointR2 bp.ScalarR1, bp.ScalarR2 = ScalarR1, ScalarR2 bp.ScalarRs1, bp.ScalarRs2 = ScalarRs1, ScalarRs2 bp.IsUsed = false return bp, nil } }
func LeastCommonMultiple(a, b big.Int) big.Int { var z big.Int z.Mul(z.Div(&a, z.GCD(nil, nil, &a, &b)), &b) return z }