File: primes.go

package info (click to toggle)
golang-github-cloudflare-circl 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,064 kB
  • sloc: asm: 20,492; ansic: 1,292; makefile: 68
file content (34 lines) | stat: -rw-r--r-- 954 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package math

import (
	"crypto/rand"
	"io"
	"math/big"
)

// IsSafePrime reports whether p is (probably) a safe prime.
// The prime p=2*q+1 is safe prime if both p and q are primes.
// Note that ProbablyPrime is not suitable for judging primes
// that an adversary may have crafted to fool the test.
func IsSafePrime(p *big.Int) bool {
	pdiv2 := new(big.Int).Rsh(p, 1)
	return p.ProbablyPrime(20) && pdiv2.ProbablyPrime(20)
}

// SafePrime returns a number of the given bit length that is a safe prime with high probability.
// The number returned p=2*q+1 is a safe prime if both p and q are primes.
// SafePrime will return error for any error returned by rand.Read or if bits < 2.
func SafePrime(random io.Reader, bits int) (*big.Int, error) {
	one := big.NewInt(1)
	p := new(big.Int)
	for {
		q, err := rand.Prime(random, bits-1)
		if err != nil {
			return nil, err
		}
		p.Lsh(q, 1).Add(p, one)
		if p.ProbablyPrime(20) {
			return p, nil
		}
	}
}