Exemple #1
0
  /**
   * Randomly generates an exponent with a given size.
   *
   * @param size the size of the exponent
   * @return the exponent which is an RSABigInteger
   */
  public RSARandomGen(int size) {

    this.size = size;

    BigInteger p, q, phiN;
    BigInteger e;

    // Two prime numbers q and p are randomly chosen
    p = BigInteger.probablePrime(size / 2, this.random);
    q = BigInteger.probablePrime(size / 2, this.random);

    // Then we calculate n, such that n = p * q
    // this.n = q.multiply(q);
    this.modulus = q.multiply(p);

    // phiN is calculated such as phiN=(p-1).(q-1)
    phiN = p.subtract(BigInteger.ONE);
    phiN = phiN.multiply(q.subtract(BigInteger.ONE));

    // A random e exponent is calculated such that
    do {
      e = new BigInteger(size, new Random());
    } while (phiN.compareTo(e) != 1 || e.gcd(phiN).compareTo(BigInteger.ONE) != 0);

    this.publicKey = e;
    this.privateKey = this.publicKey.modInverse(phiN);
  }
Exemple #2
0
  // generate an N-bit (roughly) public and private key
  RSA(int N) {
    BigInteger p = BigInteger.probablePrime(N / 2, random);
    BigInteger q = BigInteger.probablePrime(N / 2, random);
    BigInteger phi = (p.subtract(one)).multiply(q.subtract(one));

    modulus = p.multiply(q);
    publicKey = new BigInteger("65537"); // common value in practice = 2^16 + 1
    privateKey = publicKey.modInverse(phi);
  }
  /**
   * Calcola modulo, chiave pubblica e privata.
   *
   * @deprecated
   */
  public void prepare() {
    BigInteger p = BigInteger.probablePrime(512, new SecureRandom());
    BigInteger q = BigInteger.probablePrime(512, new SecureRandom());

    modulus = p.multiply(q);
    BigInteger one = BigInteger.ONE;

    BigInteger pMin1 = p.subtract(one);
    BigInteger qMin1 = q.subtract(one);
    BigInteger fi = pMin1.multiply(qMin1);
    publicKey = new BigInteger("65537");
    privateKey = publicKey.modInverse(fi);
  }
  /**
   * Costruttore della classe: Calcola modulo e chiave privata.
   *
   * @param key La chiave pubblica.
   */
  public RSA(BigInteger key) {
    BigInteger p = BigInteger.probablePrime(512, new SecureRandom());
    BigInteger q = BigInteger.probablePrime(512, new SecureRandom());

    modulus = p.multiply(q);
    BigInteger one = BigInteger.ONE;

    BigInteger pMin1 = p.subtract(one);
    BigInteger qMin1 = q.subtract(one);
    BigInteger fi = pMin1.multiply(qMin1);
    this.publicKey = key;
    privateKey = publicKey.modInverse(fi);
  }
Exemple #5
0
 public static int matches(byte[] input, byte[] pattern) {
   if (pattern.length > input.length) {
     return 0;
   }
   long p = BigInteger.probablePrime(63, r).longValue();
   long b = r.nextInt(1 << 16);
   long bpow = 1;
   long patternHash = 0;
   long inputHash = 0;
   int count = 0;
   for (int i = 1; i < pattern.length; i++) {
     bpow = (bpow * b) % p;
   }
   for (int i = 0; i < pattern.length; i++) {
     patternHash = (patternHash * b + pattern[i]) % p;
     inputHash = (inputHash * b + input[i]) % p;
   }
   if (inputHash == patternHash && isSubarray(input, pattern, 0)) {
     count++;
   }
   for (int i = pattern.length; i < input.length; i++) {
     byte oldChar = input[i - pattern.length];
     byte newChar = input[i];
     inputHash = ((inputHash - oldChar * bpow) * b + newChar) % p;
     if (inputHash == patternHash && isSubarray(input, pattern, i - pattern.length + 1)) {
       count++;
     }
   }
   return count;
 }
 private static void generateTestVectors(
     Random rng, ArrayList<TestVector> list, int bitLength, int wordLength, int max) {
   for (int i = 0; i < max; i++) {
     final long seed = rng.nextLong();
     rng.setSeed(seed);
     BigInteger m = BigInteger.probablePrime(bitLength, rng);
     BigInteger x = BigInteger.probablePrime(bitLength, rng);
     BigInteger e = BigInteger.probablePrime(bitLength, rng);
     BigInteger z = x.modPow(e, m);
     TestVector tv =
         Util.generateTestVector(
             "BASIC_" + bitLength, Long.toString(seed), wordLength, m, x, e, z);
     list.add(tv);
     System.out.printf(
         "%s Generated test: bits: %d seed: %d\n",
         TestGeneratorBasic.class.getName(), bitLength, seed);
   }
 }
  public KeyPair<RSAPublicKey, RSAPrivateKey> buildRSAKeyPair(int keysize) {

    RSAPublicKey pubk;
    RSAPrivateKey privk;
    SecureRandom sr = new SecureRandom();

    BigInteger p = BigInteger.probablePrime(keysize / 2, sr);
    BigInteger q = BigInteger.probablePrime(keysize / 2, sr);

    BigInteger n = p.multiply(q);
    BigInteger tot = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

    BigInteger e = BigInteger.valueOf(0x10001);
    BigInteger d = e.modInverse(tot);

    pubk = new RSAPublicKey(n, e);
    privk = new RSAPrivateKey(n, e, d);

    return new KeyPair<RSAPublicKey, RSAPrivateKey>(pubk, privk);
  }
Exemple #8
0
  private long burnTime(int burn_ms) {
    long prime = 2;
    long begin = System.currentTimeMillis();
    long endTime = begin + burn_ms;
    long last = 0;
    do {
      prime = BigInteger.probablePrime(64, new Random()).longValue();
      last = System.currentTimeMillis();
    } while (last < endTime);

    if (prime == 2) {
      throw new IllegalStateException("Not a prime!");
    }
    return last - begin;
  }
 /** @tests java.math.BigInteger#probablePrime(int, java.util.Random) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "probablePrime",
     args = {int.class, java.util.Random.class})
 public void test_probablePrime() {
   for (int bitLength = 50; bitLength <= 1050; bitLength += 100) {
     BigInteger a = BigInteger.probablePrime(bitLength, rand);
     assertTrue("isProbablePrime(probablePrime()) failed for: " + bi, a.isProbablePrime(80));
     //            System.out.println(a);
     //            BigInteger prime = a.nextProbablePrime();
     //            System.out.print("Next Probable Prime is ");
     //            System.out.println(prime);
   }
 }
  public static void nextProbablePrime() throws Exception {
    int failCount = 0;
    BigInteger p1, p2, p3;
    p1 = p2 = p3 = ZERO;

    // First test nextProbablePrime on the low range starting at zero
    for (int i = 0; i < primesTo100.length; i++) {
      p1 = p1.nextProbablePrime();
      if (p1.longValue() != primesTo100[i]) {
        System.err.println("low range primes failed");
        System.err.println("p1 is " + p1);
        System.err.println("expected " + primesTo100[i]);
        failCount++;
      }
    }

    // Test nextProbablePrime on a relatively small, known prime sequence
    p1 = BigInteger.valueOf(aPrimeSequence[0]);
    for (int i = 1; i < aPrimeSequence.length; i++) {
      p1 = p1.nextProbablePrime();
      if (p1.longValue() != aPrimeSequence[i]) {
        System.err.println("prime sequence failed");
        failCount++;
      }
    }

    // Next, pick some large primes, use nextProbablePrime to find the
    // next one, and make sure there are no primes in between
    for (int i = 0; i < 100; i += 10) {
      p1 = BigInteger.probablePrime(50 + i, rnd);
      p2 = p1.add(ONE);
      p3 = p1.nextProbablePrime();
      while (p2.compareTo(p3) < 0) {
        if (p2.isProbablePrime(100)) {
          System.err.println("nextProbablePrime failed");
          System.err.println("along range " + p1.toString(16));
          System.err.println("to " + p3.toString(16));
          failCount++;
          break;
        }
        p2 = p2.add(ONE);
      }
    }

    report("nextProbablePrime", failCount);
  }
Exemple #11
0
 /** Find an acceptable prime (equal to 3 mod 4) * */
 BigInteger makeBlumInt(int size) {
   for (; ; ) {
     BigInteger p = BigInteger.probablePrime(size, rand);
     if (p.mod(four).equals(three)) return p;
   }
 }
  public static void prime() {
    BigInteger p1, p2, c1;
    int failCount = 0;

    // Test consistency
    for (int i = 0; i < 10; i++) {
      p1 = BigInteger.probablePrime(100, rnd);
      if (!p1.isProbablePrime(100)) {
        System.err.println("Consistency " + p1.toString(16));
        failCount++;
      }
    }

    // Test some known Mersenne primes (2^n)-1
    // The array holds the exponents, not the numbers being tested
    for (int i = 0; i < NUM_MERSENNES_TO_TEST; i++) {
      p1 = new BigInteger("2");
      p1 = p1.pow(mersenne_powers[i]);
      p1 = p1.subtract(BigInteger.ONE);
      if (!p1.isProbablePrime(100)) {
        System.err.println("Mersenne prime " + i + " failed.");
        failCount++;
      }
    }

    // Test some primes reported by customers as failing in the past
    for (int i = 0; i < customer_primes.length; i++) {
      p1 = new BigInteger(customer_primes[i]);
      if (!p1.isProbablePrime(100)) {
        System.err.println("Customer prime " + i + " failed.");
        failCount++;
      }
    }

    // Test some known Carmichael numbers.
    for (int i = 0; i < carmichaels.length; i++) {
      c1 = BigInteger.valueOf(carmichaels[i]);
      if (c1.isProbablePrime(100)) {
        System.err.println("Carmichael " + i + " reported as prime.");
        failCount++;
      }
    }

    // Test some computed Carmichael numbers.
    // Numbers of the form (6k+1)(12k+1)(18k+1) are Carmichael numbers if
    // each of the factors is prime
    int found = 0;
    BigInteger f1 = new BigInteger(40, 100, rnd);
    while (found < NUM_CARMICHAELS_TO_TEST) {
      BigInteger k = null;
      BigInteger f2, f3;
      f1 = f1.nextProbablePrime();
      BigInteger[] result = f1.subtract(ONE).divideAndRemainder(SIX);
      if (result[1].equals(ZERO)) {
        k = result[0];
        f2 = k.multiply(TWELVE).add(ONE);
        if (f2.isProbablePrime(100)) {
          f3 = k.multiply(EIGHTEEN).add(ONE);
          if (f3.isProbablePrime(100)) {
            c1 = f1.multiply(f2).multiply(f3);
            if (c1.isProbablePrime(100)) {
              System.err.println("Computed Carmichael " + c1.toString(16));
              failCount++;
            }
            found++;
          }
        }
      }
      f1 = f1.add(TWO);
    }

    // Test some composites that are products of 2 primes
    for (int i = 0; i < 50; i++) {
      p1 = BigInteger.probablePrime(100, rnd);
      p2 = BigInteger.probablePrime(100, rnd);
      c1 = p1.multiply(p2);
      if (c1.isProbablePrime(100)) {
        System.err.println("Composite failed " + c1.toString(16));
        failCount++;
      }
    }

    for (int i = 0; i < 4; i++) {
      p1 = BigInteger.probablePrime(600, rnd);
      p2 = BigInteger.probablePrime(600, rnd);
      c1 = p1.multiply(p2);
      if (c1.isProbablePrime(100)) {
        System.err.println("Composite failed " + c1.toString(16));
        failCount++;
      }
    }

    report("Prime", failCount);
  }
  /** @tests java.math.BigInteger#isProbablePrime(int) */
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "isProbablePrime",
        args = {int.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "probablePrime",
        args = {int.class, java.util.Random.class})
  })
  public void test_isProbablePrimeI() {
    int fails = 0;
    bi = new BigInteger(20, 20, rand);
    if (!bi.isProbablePrime(17)) {
      fails++;
    }
    bi = new BigInteger("4", 10);
    if (bi.isProbablePrime(17)) {
      fail("isProbablePrime failed for: " + bi);
    }
    bi = BigInteger.valueOf(17L * 13L);
    if (bi.isProbablePrime(17)) {
      fail("isProbablePrime failed for: " + bi);
    }
    for (long a = 2; a < 1000; a++) {
      if (isPrime(a)) {
        assertTrue(
            "false negative on prime number <1000", BigInteger.valueOf(a).isProbablePrime(5));
      } else if (BigInteger.valueOf(a).isProbablePrime(17)) {
        System.out.println("isProbablePrime failed for: " + a);
        fails++;
      }
    }
    for (int a = 0; a < 1000; a++) {
      bi =
          BigInteger.valueOf(rand.nextInt(1000000))
              .multiply(BigInteger.valueOf(rand.nextInt(1000000)));
      if (bi.isProbablePrime(17)) {
        System.out.println("isProbablePrime failed for: " + bi);
        fails++;
      }
    }
    for (int a = 0; a < 200; a++) {
      bi = new BigInteger(70, rand).multiply(new BigInteger(70, rand));
      if (bi.isProbablePrime(17)) {
        System.out.println("isProbablePrime failed for: " + bi);
        fails++;
      }
    }
    assertTrue("Too many false positives - may indicate a problem", fails <= 1);

    //
    // And now some tests on real big integers:
    //
    bi =
        new BigInteger(
            "153890972191202256150310830154922163807316525358455215516067727076235016932726922093888770552128767458882963869421440585369743",
            10);
    if (!bi.isProbablePrime(80)) {
      fail("isProbablePrime failed for: " + bi);
    }
    bi =
        new BigInteger(
            "2090575416269141767246491983797422123741252476560371649798066134123893524014911825188890458270426076468664046568752890122415061377308817346303546688282957897504000216241497550243010257911214329646877810655164658470278901030511157372440751259674247310396158238588463284702737181653",
            10);
    if (!bi.isProbablePrime(80)) {
      fail("isProbablePrime failed for: " + bi);
    }
    //
    for (int bitLength = 100; bitLength <= 600; bitLength += 100) {
      BigInteger a = BigInteger.probablePrime(bitLength, rand);
      BigInteger b = BigInteger.probablePrime(bitLength, rand);
      BigInteger c = a.multiply(b);
      assertFalse(
          "isProbablePrime failed for product of two large primes"
              + a
              + " * "
              + b
              + " = "
              + c
              + " (bitLength = "
              + bitLength
              + ")",
          c.isProbablePrime(80));
    }
  }
Exemple #14
0
 private BigInteger getPrime(Random random) {
   return BigInteger.probablePrime(numberOfBits, random);
 }
Exemple #15
0
 /**
  * Returns a probably prime BigInteger having bitLength
  *
  * @param bitLength
  * @return prime number
  */
 public static BigInteger getProbablePrime(int bitLength) {
   return BigInteger.probablePrime(bitLength, new Random(System.nanoTime()));
 }
Exemple #16
0
 // some private methods
 private BigInteger generateRandomNumber() {
   return BigInteger.probablePrime(getPublicInfo().getNumBits() - 1, random);
   // return new BigInteger(getPublicInfo().getNumBits()-1,random);
 }
Exemple #17
0
 /** generate a random 31 bit prime * */
 private static long longRandomPrime() {
   BigInteger prime = BigInteger.probablePrime(31, new Random());
   return prime.longValue();
 }