Example #1
1
 public static BigInteger combinations(BigInteger n, BigInteger k) {
   if (k.compareTo(n) > 0) {
     return BigInteger.ZERO;
   } else {
     return factorial(n).divide(factorial(k)).divide(factorial(n.subtract(k)));
   }
 }
Example #2
0
 protected BigInteger modReduce(BigInteger x) {
   if (r != null) {
     boolean negative = x.signum() < 0;
     if (negative) {
       x = x.abs();
     }
     int qLen = q.bitLength();
     boolean rIsOne = r.equals(ECConstants.ONE);
     while (x.bitLength() > (qLen + 1)) {
       BigInteger u = x.shiftRight(qLen);
       BigInteger v = x.subtract(u.shiftLeft(qLen));
       if (!rIsOne) {
         u = u.multiply(r);
       }
       x = u.add(v);
     }
     while (x.compareTo(q) >= 0) {
       x = x.subtract(q);
     }
     if (negative && x.signum() != 0) {
       x = q.subtract(x);
     }
   } else {
     x = x.mod(q);
   }
   return x;
 }
Example #3
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);
  }
  public void finalTestPreparation() {
    BigInteger p = new BigInteger("292634146651759944677438112396289238593");
    BigInteger q = new BigInteger("259951719401515993224438940898363904593");
    BigInteger n = p.multiply(q);
    BigInteger d =
        new BigInteger(
            "19230821527409863624078497539913356864126656509482952467658625658635184671529");
    BigInteger e =
        new BigInteger(
            "27475944712397552787445445104954180296036650677717137281603953463917489674521");

    BigInteger phin = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
    System.out.println("Check: " + e.multiply(d).mod(phin));

    RSAEncryptor rsaenc = new RSAEncryptor(n, e);
    RSADecryptor rsadec = new RSADecryptor(p, q, d);
    Vector<BigInteger> cipher;

    String plain =
        "Congratulations!\nYou have successfuly completed the programming exercise!!\nWell done!!!\n";

    cipher = rsaenc.encrypt(plain);

    String result = rsadec.decrypt(cipher);

    System.out.println(result + "\n\n");

    System.out.println("Vector<BigInteger> cipher = new Vector<BigInteger>();\n");
    for (BigInteger i : cipher) {
      System.out.println("cipher.add(new BigInteger(\"" + i + "\"));");
    }
  }
Example #5
0
  public void initialize() {
    e = BigInteger.valueOf(65537);
    SecureRandom sr = new SecureRandom();

    BigInteger diff = BigInteger.valueOf(2).pow(256);

    /*
    generate 2 prime numbers greater than 512 bits and that have difference of 2^256
    */
    do {
      sr.generateSeed(size);
      p = new BigInteger(size, 256, sr);
      sr.generateSeed(size);
      q = new BigInteger(size, 256, sr);

    } while (p.bitLength() < size
        || q.bitLength() < size
        || !p.isProbablePrime(256)
        || !q.isProbablePrime(256)
        || p.subtract(q).abs().compareTo(diff) != 1);

    n = p.multiply(q);
    phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
    d = e.modInverse(phi_n);
  }
 private static float getProgressForRange(
     final ByteSequence start, final ByteSequence end, final ByteSequence position) {
   final int maxDepth = Math.min(Math.max(end.length(), start.length()), position.length());
   final BigInteger startBI = new BigInteger(AccumuloMRUtils.extractBytes(start, maxDepth));
   final BigInteger endBI = new BigInteger(AccumuloMRUtils.extractBytes(end, maxDepth));
   final BigInteger positionBI = new BigInteger(AccumuloMRUtils.extractBytes(position, maxDepth));
   return (float)
       (positionBI.subtract(startBI).doubleValue() / endBI.subtract(startBI).doubleValue());
 }
Example #7
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);
  }
  public static BigInteger fib(BigInteger n) throws Throwable {
    if (n.equals(BigInteger.ZERO)) return BigInteger.ZERO;

    if (n.equals(BigInteger.ONE)) return BigInteger.ONE;

    // return fib(n - 1) + fib(n - 2);
    return ((BigInteger) mhDynamic.invokeExact(n.subtract(BigInteger.ONE)))
        .add((BigInteger) mhDynamic.invokeExact(n.subtract(BigInteger.valueOf(2))));
  }
Example #9
0
  public RSA(Random random) {
    savedRandom = random;

    p = getPrime(random); // p and q are arbitrary large primes
    q = getPrime(random);
    n = p.multiply(q);
    phiN = (p.subtract(ONE)).multiply(q.subtract(ONE));

    S = getPrime(random); // s is an arbitrary secret; we'll use a prime
    V = S.modPow(new BigInteger("2"), n);
  }
 /**
  * Los valores han sido calculados matemáticamente. p --> un número primo; q --> numero primo
  * menor que p; e --> numero coPrimo de y menor que n
  */
 public EncriptacionRSA() {
   p = new BigInteger("37111475501984423786707");
   q = new BigInteger("22457587554291135069157");
   // n = p * q
   n = p.multiply(q);
   e = new BigInteger("376816953197990800115868480017153452275607211");
   totient = p.subtract(BigInteger.valueOf(1));
   totient = totient.multiply(q.subtract(BigInteger.valueOf(1)));
   // d = e^1 mod totient
   d = e.modInverse(totient);
 }
 /** Generate a new public and private key set. */
 public synchronized void generateKeys() {
   SecureRandom r = new SecureRandom();
   BigInteger p = new BigInteger(bitlen / 2, 100, r);
   BigInteger q = new BigInteger(bitlen / 2, 100, r);
   n = p.multiply(q);
   BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
   e = new BigInteger("3");
   while (m.gcd(e).intValue() > 1) {
     e = e.add(new BigInteger("2"));
   }
   d = e.modInverse(m);
 }
  /*
    See IEEE P1363 A.15.5 (10/05/98 Draft)
  */
  public static BigInteger generateRandomPrime(
      BigInteger r, BigInteger a, int pmin, int pmax, BigInteger f) {
    BigInteger d, w;

    // Step 1 - generate prime
    BigInteger p = new BigInteger((pmax + pmin) / 2, new Random());

    steptwo:
    { // Step 2
      w = p.mod(r.multiply(BigInteger.valueOf(2)));

      // Step 3
      p = p.add(r.multiply(BigInteger.valueOf(2)));
      p = p.subtract(w);
      p = p.add(a);

      // Step 4 - test for even
      if (p.mod(BigInteger.valueOf(2)).compareTo(BigInteger.valueOf(0)) == 0) p = p.add(r);

      for (; ; ) {
        // Step 5
        if (p.compareTo(BigInteger.valueOf(1).shiftLeft(pmax)) > 0) {
          // Step 5.1
          p = p.subtract(BigInteger.valueOf(1).shiftLeft(pmax));
          p = p.add(BigInteger.valueOf(1).shiftLeft(pmin));
          p = p.subtract(BigInteger.valueOf(1));

          // Step 5.2 - goto to Step 2
          break steptwo;
        }

        // Step 6
        d = p.subtract(BigInteger.valueOf(1));
        d = d.gcd(f);

        // Step 7 - test d
        if (d.compareTo(BigInteger.valueOf(1)) == 0) {
          // Step 7.1 - test primality
          if (p.isProbablePrime(1) == true) {
            // Step 7.2;
            return p;
          }
        }
        // Step 8
        p = p.add(r.multiply(BigInteger.valueOf(2)));

        // Step 9
      }
    }
    // Should never reach here but makes the compiler happy
    return BigInteger.valueOf(0);
  }
Example #13
0
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final B64 b64 = toB64(exprs[0], qc, true);
    long by = toLong(exprs[1], qc);
    if (b64 == null) return null;
    if (by == 0) return b64;

    byte[] bytes = b64.binary(info);
    final int bl = bytes.length;

    byte[] tmp = new byte[bl];
    int r = 0;
    if (by > 7) {
      tmp = new BigInteger(bytes).shiftLeft((int) by).toByteArray();
      if (tmp.length != bl) {
        bytes = tmp;
        tmp = new byte[bl];
        System.arraycopy(bytes, bytes.length - bl, tmp, 0, bl);
      }
    } else if (by > 0) {
      for (int i = bl - 1; i >= 0; i--) {
        final byte b = bytes[i];
        tmp[i] = (byte) (b << by | r);
        r = b >>> 32 - by;
      }
    } else if (by > -8) {
      by = -by;
      for (int i = 0; i < bl; i++) {
        final int b = bytes[i] & 0xFF;
        tmp[i] = (byte) (b >>> by | r);
        r = b << 32 - by;
      }
    } else {
      by = -by;
      BigInteger bi = new BigInteger(bytes);
      if (bi.signum() >= 0) {
        bi = bi.shiftRight((int) by);
      } else {
        final BigInteger o = BigInteger.ONE.shiftLeft(bl * 8 + 1);
        final BigInteger m = o.subtract(BigInteger.ONE).shiftRight((int) by + 1);
        bi = bi.subtract(o).shiftRight((int) by).and(m);
      }
      tmp = bi.toByteArray();
      final int tl = tmp.length;
      if (tl != bl) {
        bytes = tmp;
        tmp = new byte[bl];
        System.arraycopy(bytes, 0, tmp, bl - tl, tl);
      }
    }
    return new B64(tmp);
  }
  private static BigInteger calculateGenerator_FIPS186_2(
      BigInteger p, BigInteger q, SecureRandom r) {
    BigInteger e = p.subtract(ONE).divide(q);
    BigInteger pSub2 = p.subtract(TWO);

    for (; ; ) {
      BigInteger h = BigIntegers.createRandomInRange(TWO, pSub2, r);
      BigInteger g = h.modPow(e, p);
      if (g.bitLength() > 1) {
        return g;
      }
    }
  }
 /** Create an instance that can both encrypt and decrypt. */
 public RSA(int bits) {
   bitlen = bits;
   SecureRandom r = new SecureRandom();
   BigInteger p = new BigInteger(bitlen / 2, 100, r);
   BigInteger q = new BigInteger(bitlen / 2, 100, r);
   n = p.multiply(q);
   BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
   e = new BigInteger("3");
   while (m.gcd(e).intValue() > 1) {
     e = e.add(new BigInteger("2"));
   }
   d = e.modInverse(m);
 }
  /**
   * 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);
  }
  /**
   * 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);
  }
    public boolean isPrime(BigInteger n, int iteration) {
      if (n.equals(BigInteger.ZERO) || n.equals(BigInteger.ONE)) return false;

      BigInteger two = BigInteger.valueOf(2);

      if (n.equals(two)) return true;

      if (n.mod(two).equals(BigInteger.ZERO)) return false;

      //			long s = n - 1;
      BigInteger s = n.subtract(BigInteger.ONE);

      //			while (s % 2 == 0)
      while (s.mod(two).equals(BigInteger.ZERO)) s = s.divide(two);
      //				s /= 2;

      Random rand = new Random();

      for (int i = 0; i < iteration; i++) {
        /*				long r = Math.abs(rand.nextLong());
        long a = r % (n - 1) + 1, temp = s;
        long mod = modPow(a, temp, n);*/

        BigInteger r, a, temp, mod;

        r = BigInteger.valueOf(Math.abs(rand.nextLong()));
        a = r.mod(n.subtract(BigInteger.ONE)).add(BigInteger.ONE);
        temp = new BigInteger(s.toString());
        mod = modPow(a, temp, n);

        while (!temp.equals(n.subtract(BigInteger.ONE))
            && !mod.equals(BigInteger.ONE)
            && !mod.equals(n.subtract(BigInteger.ONE))) {
          mod = mulMod(mod, mod, n);
          temp = temp.multiply(two);
        }

        /*				while (temp != n - 1 && mod != 1 && mod != n - 1)
        {
        	mod = mulMod(mod, mod, n);
        	temp *= 2;
        }*/

        /*				if (mod != n - 1 && temp % 2 == 0)
        return false;*/

        if (!mod.equals(n.subtract(BigInteger.ONE)) && temp.mod(two).equals(BigInteger.ZERO))
          return false;
      }
      return true;
    }
Example #19
0
 public static Set fill(Set n) {
   BigInteger a = new BigInteger("100");
   BigInteger b = new BigInteger("100");
   while (b.compareTo(BigInteger.ONE) > 0) {
     while (a.compareTo(BigInteger.ONE) > 0) {
       int exp = (int) b.longValue();
       n.add(a.pow(exp));
       a = a.subtract(BigInteger.ONE);
     }
     a = BigInteger.valueOf(100);
     b = b.subtract(BigInteger.ONE);
   }
   return n;
 }
Example #20
0
  public static ArrayList<BigInteger> generatePublicKeyOfBitLength(int bitLength) {
    ArrayList<BigInteger> pAndQ = findPAndQ(bitLength);
    BigInteger p = pAndQ.get(0);
    BigInteger q = pAndQ.get(1);
    // Find PQ and phiPQ
    BigInteger pq = p.multiply(q);
    BigInteger phiPQ = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
    BigInteger e = findE(phiPQ);

    ArrayList<BigInteger> publicKey = new ArrayList<BigInteger>();
    publicKey.add(pq);
    publicKey.add(e);
    return publicKey;
  }
  /**
   * Create public and private keys. Doesn't check if parameters are suitable. It is done by
   * testInputEligibility() method.
   *
   * @param p Prime p.
   * @param q Prime q.
   * @param e Public exponent.
   */
  public void createKeys(BigInteger p, BigInteger q, BigInteger e) {
    // Calculate the Euler's function.
    BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

    // Compute private exponent
    BigInteger d = e.modInverse(phi);

    // Calculate modulo
    BigInteger n = p.multiply(q);

    // Create keys
    publicKey = new RsaPublicKey(n, e);
    privateKey = new RsaPrivateKey(p, q, e, d);
  }
Example #22
0
  public BigPoint multiply(BigInteger Factor) {
    // Punkt mit sich selbst addieren

    if (Factor.compareTo(BigInteger.ONE) == 0) return this;

    if (Configuration._ellipticCurvePointY.compareTo(BigInteger.ZERO) == 0)
      throw new IllegalArgumentException(
          "Der Y-Wert des Generatorpunktes darf für eine Punktverdopplung nicht 0 sein!");

    BigInteger s, xR, yR;
    // ((3x^2 + a) * 2y_p^-1 mod p
    s =
        X.pow(2)
            .multiply(new BigInteger("3"))
            .add(Configuration._ellipticCurveParamA)
            .multiply(
                ECCField.GetInverseValue(
                    Y.multiply(new BigInteger("2")), Configuration._ellipticCurveParamP))
            .mod(Configuration._ellipticCurveParamP);

    // Normalisieren
    if (s.compareTo(BigInteger.ZERO) < 0) s = s.add(Configuration._ellipticCurveParamP);

    xR =
        s.modPow(new BigInteger("2"), Configuration._ellipticCurveParamP)
            .subtract(X.multiply(new BigInteger("2")))
            .mod(Configuration._ellipticCurveParamP);

    // Normalisieren
    if (xR.compareTo(BigInteger.ZERO) < 0) xR = xR.add(Configuration._ellipticCurveParamP);

    yR = Y.negate().add(s.multiply(X.subtract(xR))).mod(Configuration._ellipticCurveParamP);

    // Normalisieren
    if (yR.compareTo(BigInteger.ZERO) < 0) yR = yR.add(Configuration._ellipticCurveParamP);

    Factor = Factor.subtract(BigInteger.ONE);

    BigPoint res = new BigPoint(xR, yR);

    // 3P = 2P + P
    // x * P = 2P + P + P + ... + P

    while (Factor.compareTo(BigInteger.ONE) > 0) {
      res = addPoint(this, res);
      Factor = Factor.subtract(BigInteger.ONE);
    }
    return res;
  }
Example #23
0
 protected BigInteger modSubtract(BigInteger x1, BigInteger x2) {
   BigInteger x3 = x1.subtract(x2);
   if (x3.signum() < 0) {
     x3 = x3.add(q);
   }
   return x3;
 }
Example #24
0
  private static void checkNormaliseBaseTenResult(ExpandedDouble orig, NormalisedDecimal result) {
    String sigDigs = result.getSignificantDecimalDigits();
    BigInteger frac = orig.getSignificand();
    while (frac.bitLength() + orig.getBinaryExponent() < 200) {
      frac = frac.multiply(BIG_POW_10);
    }
    int binaryExp = orig.getBinaryExponent() - orig.getSignificand().bitLength();

    String origDigs = frac.shiftLeft(binaryExp + 1).toString(10);

    if (!origDigs.startsWith(sigDigs)) {
      throw new AssertionFailedError("Expected '" + origDigs + "' but got '" + sigDigs + "'.");
    }

    double dO = Double.parseDouble("0." + origDigs.substring(sigDigs.length()));
    double d1 = Double.parseDouble(result.getFractionalPart().toPlainString());
    BigInteger subDigsO = BigInteger.valueOf((int) (dO * 32768 + 0.5));
    BigInteger subDigsB = BigInteger.valueOf((int) (d1 * 32768 + 0.5));

    if (subDigsO.equals(subDigsB)) {
      return;
    }
    BigInteger diff = subDigsB.subtract(subDigsO).abs();
    if (diff.intValue() > 100) {
      // 100/32768 ~= 0.003
      throw new AssertionFailedError("minor mistake");
    }
  }
 private BigInteger previousTransactionId(BigInteger id) {
   if (id.equals(INIT_TXID)) {
     return null;
   } else {
     return id.subtract(BigInteger.ONE);
   }
 }
Example #26
0
 /** Create an instance that can both encrypt and decrypt. */
 public RSA(int bits) {
   bitlen = bits;
   // Standartowe obliczenie n
   /*
   BigInteger p = new BigInteger(MillerRabin.ZnajdzPierwsza(bitlen/2));
   BigInteger q = new BigInteger(MillerRabin.ZnajdzPierwsza(bitlen/2));
   n = p.multiply(q);
   */
   // N dla k liczb
   n = new BigInteger("1");
   for (BigInteger e : Lista.liczbyp) {
     n = n.multiply(e);
   }
   // obliczanie funkcji Eulera m=f(n)=(p-1)*(q-1)
   /*
   BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
       .subtract(BigInteger.ONE));
       */
   m = new BigInteger("1");
   for (BigInteger e : Lista.liczbyp) {
     m = m.multiply(e.subtract(new BigInteger("1")));
   }
   // int zakresE = 2^(bits-2);
   e =
       new BigInteger(2 ^ (bitlen * Lista.liczbyp.size() - 2), rnd)
           .shiftLeft(1)
           .add(new BigInteger("1"));
   while (m.gcd(e).intValue() > 1) {
     e = e.add(new BigInteger("2"));
   }
   d = e.modInverse(m);
 }
Example #27
0
 public ECFieldElement multiplyMinusProduct(
     ECFieldElement b, ECFieldElement x, ECFieldElement y) {
   BigInteger ax = this.x, bx = b.toBigInteger(), xx = x.toBigInteger(), yx = y.toBigInteger();
   BigInteger ab = ax.multiply(bx);
   BigInteger xy = xx.multiply(yx);
   return new Fp(q, r, modReduce(ab.subtract(xy)));
 }
Example #28
0
  public void calculate_S() {
    S =
        B.subtract(k.multiply(g.modPow(x, N)))
            .modPow(a.add(u.multiply(x)), N); // S = (B - (k*g^x))^(a+ux)

    System.out.println("S in Client: " + S.toString());
  }
Example #29
0
 protected BigInteger modAdd(BigInteger x1, BigInteger x2) {
   BigInteger x3 = x1.add(x2);
   if (x3.compareTo(q) >= 0) {
     x3 = x3.subtract(q);
   }
   return x3;
 }
Example #30
0
 protected BigInteger modDouble(BigInteger x) {
   BigInteger _2x = x.shiftLeft(1);
   if (_2x.compareTo(q) >= 0) {
     _2x = _2x.subtract(q);
   }
   return _2x;
 }