- 小费马
func fmod(a *big.Int,p int64) bool {
one,_ := new(big.Int).SetString("1",10)
a_ := new(big.Int).Sub(a,one)
result := new(big.Int).Exp(new(big.Int).SetInt64(p),a_,a)
if result.String()!="1" {
return false
}
return true
}
- 素性检验
func MillerRabbin(a *big.Int) bool {
p := new(big.Int).Set(a)
rand.Seed(time.Now().UnixNano())
for i := 1; i < 100; i++ {
n := rand.Int63()
if new(big.Int).SetInt64(n).Cmp(p) == 1 {
n = rand.Int63n(p.Int64() - 1) + 1
}
if !fmod(p, n) {
return false
}
}
return true
}
- 生成所需要的长度参数(素数要多大)
func GenerateBigRange(n int64) *big.Int {
length := new(big.Int).SetInt64(n)
re,_ := new(big.Int).SetString("10",10)
re.Exp(re,length,nil)
return re
}
- 生成素数
func GenerateBigPrimeP(n int64) *big.Int {
numRange := GenerateBigRange(n)
ran := rand.New(rand.NewSource(time.Now().UnixNano()))
ran.Seed(time.Now().UnixNano())
p := new(big.Int).Rand(ran,numRange)
for !MillerRabbin(p) {
p.Rand(ran,numRange)
}
return p
}
|