primes.go 954 B

12345678910111213141516171819202122232425262728293031323334
  1. package math
  2. import (
  3. "crypto/rand"
  4. "io"
  5. "math/big"
  6. )
  7. // IsSafePrime reports whether p is (probably) a safe prime.
  8. // The prime p=2*q+1 is safe prime if both p and q are primes.
  9. // Note that ProbablyPrime is not suitable for judging primes
  10. // that an adversary may have crafted to fool the test.
  11. func IsSafePrime(p *big.Int) bool {
  12. pdiv2 := new(big.Int).Rsh(p, 1)
  13. return p.ProbablyPrime(20) && pdiv2.ProbablyPrime(20)
  14. }
  15. // SafePrime returns a number of the given bit length that is a safe prime with high probability.
  16. // The number returned p=2*q+1 is a safe prime if both p and q are primes.
  17. // SafePrime will return error for any error returned by rand.Read or if bits < 2.
  18. func SafePrime(random io.Reader, bits int) (*big.Int, error) {
  19. one := big.NewInt(1)
  20. p := new(big.Int)
  21. for {
  22. q, err := rand.Prime(random, bits-1)
  23. if err != nil {
  24. return nil, err
  25. }
  26. p.Lsh(q, 1).Add(p, one)
  27. if p.ProbablyPrime(20) {
  28. return p, nil
  29. }
  30. }
  31. }