原理
設p爲安全素數,即使p=2q+1,且q爲素數。由Fermat定理知g^(p-1) mod p=1,
即g^(2q) mod p=1,因而如果
w=min{t>0: g^t mod p=1}
則有w整除p-1=2q,因而由q是素數知,w只能是2或q,此時g是本原元等價於
g^2 mod p !=1 且 g ^q mod p !=1
編程步驟
1.隨機生成一個素數q
2.令p=2q+1,並判斷p是否是一個素數
3.如果是,那麼p就是一個安全素數,否則轉1
4.在安全素數p下,隨機選取g,1<g<p-1.
5.如果g^2 mod p!=1 且 g ^ q mod p!=1,那麼g就是本原元
代碼
public static BigInteger generator() {
Random rnd=new Random();
BigInteger p,q,g,x,y;
while(true) {
q=BigInteger.probablePrime(1024, rnd);
p=q.multiply(BigInteger.valueOf(2)).add(BigInteger.valueOf(1));
if(p.isProbablePrime(20)) break;
}
while(true) {
g=BigInteger.probablePrime(512, rnd);
x=g.multiply(g).mod(p);
y=pow(g,q,p);
if(x.equals(BigInteger.valueOf(1))==false && y.equals(BigInteger.valueOf(1))==false) {
break;
}
}
return g;
}