generate Solinas Prime - Java java.math

Java examples for java.math:BigInteger

Description

generate Solinas Prime

Demo Code


import java.math.BigInteger;
import java.util.Random;

public class Main {
  public static BigInteger generateSolinasPrime(int bits, Random random) {
    // r is picked to be a Solinas prime, that is,
    // r has the form 2a +- 2b +- 1 for some integers 0 < b < a.
    BigInteger r, q;/* ww  w.j a  v  a  2 s.  c  o m*/
    int exp2, sign1;

    while (true) {
      r = BigInteger.ZERO;

      if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
        exp2 = bits - 1;
        sign1 = 1;
      } else {
        exp2 = bits;
        sign1 = -1;
      }
      r = r.setBit(exp2);

      q = BigInteger.ZERO.setBit((random.nextInt(Integer.MAX_VALUE) % (exp2 - 1)) + 1);

      if (sign1 > 0) {
        r = r.add(q);
      } else {
        r = r.subtract(q);
      }

      if (random.nextInt(Integer.MAX_VALUE) % 2 != 0) {
        r = r.add(BigInteger.ONE);
      } else {
        r = r.subtract(BigInteger.ONE);
      }

      if (r.isProbablePrime(10))
        return r;
    }

  }
}

Related Tutorials