github.com/cloudflare/circl@v1.5.0/math/primes.go (about)

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