Example #1
0
  public BDD varRange(BigInteger lo, BigInteger hi) {
    if (lo.signum() < 0 || hi.compareTo(size()) >= 0 || lo.compareTo(hi) > 0) {
      throw new BDDException("range <" + lo + ", " + hi + "> is invalid");
    }

    BDDFactory factory = getFactory();
    BDD result = factory.zero();
    int[] ivar = this.vars();
    while (lo.compareTo(hi) <= 0) {
      BDD v = factory.universe();
      for (int n = ivar.length - 1; ; n--) {
        if (lo.testBit(n)) {
          v.andWith(factory.ithVar(ivar[n]));
        } else {
          v.andWith(factory.nithVar(ivar[n]));
        }
        BigInteger mask = BigInteger.ONE.shiftLeft(n).subtract(BigInteger.ONE);
        if (!lo.testBit(n) && lo.or(mask).compareTo(hi) <= 0) {
          lo = lo.or(mask).add(BigInteger.ONE);
          break;
        }
      }
      result.orWith(v);
    }
    return result;
  }
Example #2
0
  public NPCI(ByteQueue queue) {
    version = queue.popU1B();
    control = BigInteger.valueOf(queue.popU1B());

    if (control.testBit(5)) {
      destinationNetwork = queue.popU2B();
      destinationLength = queue.popU1B();
      if (destinationLength > 0) {
        destinationAddress = new byte[destinationLength];
        queue.pop(destinationAddress);
      }
    }

    if (control.testBit(3)) {
      sourceNetwork = queue.popU2B();
      sourceLength = queue.popU1B();
      sourceAddress = new byte[sourceLength];
      queue.pop(sourceAddress);
    }

    if (control.testBit(5)) hopCount = queue.popU1B();

    if (control.testBit(7)) {
      messageType = queue.popU1B();
      if (messageType >= 80) vendorId = queue.popU2B();
    }
  }
 /** @tests java.math.BigInteger#not() */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "not",
     args = {})
 public void test_not() {
   for (BigInteger[] element : booleanPairs) {
     BigInteger i1 = element[0];
     BigInteger res = i1.not();
     int len = i1.bitLength() + 66;
     for (int i = 0; i < len; i++) {
       assertTrue("not", !i1.testBit(i) == res.testBit(i));
     }
   }
 }
Example #4
0
  private static BigInteger[] LucasSequence(
      BigInteger p, BigInteger X, BigInteger Y, BigInteger k) {
    int n = k.bitLength();
    int s = k.getLowestSetBit();

    BigInteger D = X.multiply(X).subtract(Y.shiftLeft(2));
    BigInteger U = BigInteger.ONE;
    BigInteger V = X;
    for (int j = n - 1; j >= s; j--) {
      if (k.testBit(j)) {
        BigInteger T = X.multiply(U).add(V).shiftRight(1).mod(p);
        V = X.multiply(V).add(D.multiply(U)).shiftRight(1).mod(p);
        U = T;
      } else {
        BigInteger T = U.multiply(V).mod(p);
        V = V.multiply(V).add(D.multiply(U.multiply(U))).shiftRight(1).mod(p);
        U = T;
      }
    }
    for (int j = 1; j <= s; j++) {
      BigInteger T = U.multiply(V).mod(p);
      V = V.multiply(V).add(D.multiply(U.multiply(U))).shiftRight(1).mod(p);
      U = T;
    }
    return new BigInteger[] {U, V};
  }
 /** @tests java.math.BigInteger#xor(java.math.BigInteger) */
 @TestTargetNew(
     level = TestLevel.COMPLETE,
     notes = "",
     method = "xor",
     args = {java.math.BigInteger.class})
 public void test_xorLjava_math_BigInteger() {
   for (BigInteger[] element : booleanPairs) {
     BigInteger i1 = element[0], i2 = element[1];
     BigInteger res = i1.xor(i2);
     assertTrue("symmetry of xor", res.equals(i2.xor(i1)));
     int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
     for (int i = 0; i < len; i++) {
       assertTrue("xor", (i1.testBit(i) ^ i2.testBit(i)) == res.testBit(i));
     }
   }
 }
  /**
   * Find the number in between the high and the low value with the most zeroes.
   *
   * @param value the lower bound for the number
   * @param highValue the upper bound for the nubmer
   * @return the value for the number with the most zeroes between the two bounds
   */
  private BigInteger maxZeroes(BigInteger value, BigInteger highValue) {
    // Find the highest bit that would be possible to add one to before
    // going over the high value.
    int i = highValue.xor(value).bitLength();
    int j;
    while (--i >= 0) {
      // If you hit a zero bit...
      if (!value.testBit(i)) {
        // ...change that bit to a 1.
        value = value.setBit(i);

        // Create a bit mask to compare with.
        byte[] comparatorBytes = value.toByteArray();
        Arrays.fill(comparatorBytes, (byte) 0xFF);
        BigInteger comparator = new BigInteger(comparatorBytes);
        comparator = comparator.shiftLeft(i);

        // And the value with the bit mask. Everything after the changed
        // bit will be cleared en masse. Way faster than clearing bits
        // individually.
        value = value.and(comparator);
        break;
      }
    }
    return value;
  }
 /** Postl's algorithm to compute V_k(P, 1) */
 private BigInteger lucas(BigInteger P, BigInteger k) {
   BigInteger d_1 = P;
   BigInteger d_2 = P.multiply(P).subtract(_2).mod(p);
   int l = k.bitLength() - 1; // k = \sum_{j=0}^l{k_j*2^j}
   for (int j = l - 1; j >= 1; j--) {
     if (k.testBit(j)) {
       d_1 = d_1.multiply(d_2).subtract(P).mod(p);
       d_2 = d_2.multiply(d_2).subtract(_2).mod(p);
     } else {
       d_2 = d_1.multiply(d_2).subtract(P).mod(p);
       d_1 = d_1.multiply(d_1).subtract(_2).mod(p);
     }
   }
   return (k.testBit(0))
       ? d_1.multiply(d_2).subtract(P).mod(p)
       : d_1.multiply(d_1).subtract(_2).mod(p);
 }
Example #8
0
 @Override
 public ASTNode transform(BitVector bitVector) {
   StringBuilder sb = new StringBuilder();
   sb.append("#b");
   for (int i = bitVector.bitwidth() - 1; i >= 0; --i) {
     BigInteger value = bitVector.unsignedValue();
     sb.append(value.testBit(i) ? "1" : "0");
   }
   return new SMTLibTerm(sb.toString());
 }
Example #9
0
  public static void bitOps(int order) {
    int failCount1 = 0, failCount2 = 0, failCount3 = 0;

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);
      BigInteger y;

      /* Test setBit and clearBit (and testBit) */
      if (x.signum() < 0) {
        y = BigInteger.valueOf(-1);
        for (int j = 0; j < x.bitLength(); j++) if (!x.testBit(j)) y = y.clearBit(j);
      } else {
        y = BigInteger.ZERO;
        for (int j = 0; j < x.bitLength(); j++) if (x.testBit(j)) y = y.setBit(j);
      }
      if (!x.equals(y)) failCount1++;

      /* Test flipBit (and testBit) */
      y = BigInteger.valueOf(x.signum() < 0 ? -1 : 0);
      for (int j = 0; j < x.bitLength(); j++) if (x.signum() < 0 ^ x.testBit(j)) y = y.flipBit(j);
      if (!x.equals(y)) failCount2++;
    }
    report("clearBit/testBit", failCount1);
    report("flipBit/testBit", failCount2);

    for (int i = 0; i < size * 5; i++) {
      BigInteger x = fetchNumber(order);

      /* Test getLowestSetBit() */
      int k = x.getLowestSetBit();
      if (x.signum() == 0) {
        if (k != -1) failCount3++;
      } else {
        BigInteger z = x.and(x.negate());
        int j;
        for (j = 0; j < z.bitLength() && !z.testBit(j); j++) ;
        if (k != j) failCount3++;
      }
    }
    report("getLowestSetBit", failCount3);
  }
Example #10
0
  private static boolean isPrime(BigInteger n) {
    BigInteger sqrt = bigIntSqRootFloor(n).add(BigInteger.ONE);
    BigInteger TWO = BigInteger.valueOf(2);

    if (!n.testBit(0)) return false; // even number

    for (BigInteger i = BigInteger.valueOf(3); i.compareTo(sqrt) <= 0; i = i.add(TWO)) {
      if (n.mod(i).compareTo(BigInteger.ZERO) == 0) return false;
    }

    return true;
  }
  /** @tests java.math.BigInteger#andNot(java.math.BigInteger) */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "andNot",
      args = {java.math.BigInteger.class})
  public void test_andNotLjava_math_BigInteger() {
    for (BigInteger[] element : booleanPairs) {
      BigInteger i1 = element[0], i2 = element[1];
      BigInteger res = i1.andNot(i2);
      int len = Math.max(i1.bitLength(), i2.bitLength()) + 66;
      for (int i = 0; i < len; i++) {
        assertTrue("andNot", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
      // asymmetrical
      i1 = element[1];
      i2 = element[0];
      res = i1.andNot(i2);
      for (int i = 0; i < len; i++) {
        assertTrue("andNot reversed", (i1.testBit(i) && !i2.testBit(i)) == res.testBit(i));
      }
    }

    // regression for HARMONY-4653
    try {
      BigInteger.ZERO.andNot(null);
      fail("should throw NPE");
    } catch (Exception e) {
      // expected
    }
    BigInteger bi = new BigInteger(0, new byte[] {});
    assertEquals(BigInteger.ZERO, bi.andNot(BigInteger.ZERO));
  }
Example #12
0
  public ECFieldElement Sqrt() {
    if (!this.q.testBit(0)) {
      throw new UnsupportedOperationException("even value of q");
    }
    if (this.q.testBit(1)) {
      ECFieldElement z =
          new FpFieldElement(
              this.q, this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE), this.q));
      return z.Square().equals(this) ? z : null;
    }
    BigInteger u = this.q.shiftRight(3);
    if (this.q.testBit(2)) {
      BigInteger z = this.x.modPow(u.shiftLeft(1).add(BigInteger.ONE), this.q);
      if (z.equals(BigInteger.ONE)) {
        return new FpFieldElement(this.q, this.x.modPow(u.add(BigInteger.ONE), this.q));
      }
      if (z.equals(this.q.subtract(BigInteger.ONE))) {
        return new FpFieldElement(
            this.q,
            this.x.shiftLeft(1).multiply(this.x.shiftLeft(2).modPow(u, this.q)).mod(this.q));
      }
      return null;
    }
    BigInteger qMinusOne = this.q.subtract(BigInteger.ONE);

    BigInteger legendreExponent = qMinusOne.shiftRight(1);
    if (!this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE)) {
      return null;
    }
    BigInteger k = legendreExponent.add(BigInteger.ONE);
    BigInteger fourY = this.x.shiftLeft(2).mod(this.q);

    Random rand = new Random();
    BigInteger U;
    do {
      BigInteger r;
      do {
        r = new BigInteger(this.q.bitLength(), rand);
      } while ((r.compareTo(this.q) >= 0)
          || (!r.multiply(r).subtract(fourY).modPow(legendreExponent, this.q).equals(qMinusOne)));
      BigInteger[] result = LucasSequence(this.q, r, this.x, k);
      U = result[0];
      BigInteger V = result[1];
      if (V.multiply(V).mod(this.q).equals(fourY)) {
        if (V.testBit(0)) {
          V = V.add(this.q);
        }
        return new FpFieldElement(this.q, V.shiftRight(1).mod(this.q));
      }
    } while ((U.equals(BigInteger.ONE)) || (U.equals(qMinusOne)));
    return null;
  }
Example #13
0
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    BigInteger one = BigInteger.ONE;
    BigInteger two = BigInteger.valueOf(2);
    BigInteger three = BigInteger.valueOf(3);

    System.out.print("Enter a natural number: ");
    BigInteger number = new BigInteger(input.nextLine());
    if (number.compareTo(one) <= 0) return; // check number <= 1

    boolean allPrime = true;
    LinkedList<BigInteger> primes = new LinkedList<BigInteger>();

    while (number.compareTo(one) != 0) { // while number != 1
      if (allPrime && number.testBit(0) && number.compareTo(BigInteger.ONE) != 0) {
        if (!isPrime(number)) {
          System.out.println(number + " isn't prime!");
          allPrime = false;
          primes = null;
        } else primes.add(number);
      }

      if (number.testBit(0)) { // check if odd
        number = number.multiply(three).add(one);
      } else {
        number = number.divide(two);
      }

      System.out.println(number);
    }

    if (allPrime) {
      System.out.printf("\nAll %d odd numbers were prime!\n", primes.size() + 1);
      for (BigInteger n : primes) {
        System.out.println(n);
      }
      System.out.println(1);
    }
  }
Example #14
0
  /**
   * Returns what corresponds to a disjunction of all possible values of this domain. This is more
   * efficient than doing ithVar(0) OR ithVar(1) ... explicitly for all values in the domain.
   *
   * <p>Compare to fdd_domain.
   */
  public BDD domain() {
    BDDFactory factory = getFactory();

    /* Encode V<=X-1. V is the variables in 'var' and X is the domain size */
    BigInteger val = size().subtract(BigInteger.ONE);
    BDD d = factory.universe();
    int[] ivar = vars();
    for (int n = 0; n < this.varNum(); n++) {
      if (val.testBit(0)) d.orWith(factory.nithVar(ivar[n]));
      else d.andWith(factory.nithVar(ivar[n]));
      val = val.shiftRight(1);
    }
    return d;
  }
Example #15
0
 /**
  * This is a k-extend field power method in F2(4m).
  *
  * @param inputField k-extend field from polynomials.
  * @param pow FieldElement value to power fieldArray.
  * @return [fieldArrayA[]]^[pow] mod(modulus).
  */
 @Override
 public FieldElement[] extendPow(final FieldElement[] inputField, final BigInteger pow) {
   FieldElement[] returnArray = {
     this.modulus.getONE(), this.modulus.getZERO(), this.modulus.getZERO(), this.modulus.getZERO()
   };
   FieldElement[] field = inputField.clone();
   for (int i = 0; i < pow.bitLength(); i++) {
     if (pow.testBit(i)) {
       returnArray = this.extendMul(returnArray, field);
     }
     field = this.extendSquaring(field);
   }
   return returnArray;
 }
Example #16
0
  @Test
  public void testRandom() throws IOException {
    int numBytes = 1024;

    byte[] bits = new byte[numBytes];
    ThreadLocalRandom.current().nextBytes(bits);
    BigInteger n = new BigInteger(bits);
    InputStream src = new ByteArrayInputStream(Bits.swapEndian(n.toByteArray()));
    BitInputStream in = new BitInputStream(src);

    int numBits = numBytes * 8;
    for (int i = 0; i < numBits; i++) {
      Assert.assertEquals(n.testBit(i), in.readBit());
    }
  }
Example #17
0
  public BDD ithVar(BigInteger val) {
    if (val.signum() < 0 || val.compareTo(size()) >= 0) {
      throw new BDDException(val + " is out of range");
    }

    BDDFactory factory = getFactory();
    BDD v = factory.universe();
    int[] ivar = this.vars();
    for (int n = 0; n < ivar.length; n++) {
      if (val.testBit(0)) v.andWith(factory.ithVar(ivar[n]));
      else v.andWith(factory.nithVar(ivar[n]));
      val = val.shiftRight(1);
    }

    return v;
  }
  public RSAKeyGenerationParameters(
      BigInteger publicExponent, SecureRandom random, int strength, int certainty) {
    super(random, strength);

    if (strength < 12) {
      throw new IllegalArgumentException("key strength too small");
    }

    //
    // public exponent cannot be even
    //
    if (!publicExponent.testBit(0)) {
      throw new IllegalArgumentException("public exponent cannot be even");
    }

    this.publicExponent = publicExponent;
    this.certainty = certainty;
  }
Example #19
0
    private BigInteger[] lucasSequence(BigInteger P, BigInteger Q, BigInteger k) {
      // TODO Research and apply "common-multiplicand multiplication here"

      int n = k.bitLength();
      int s = k.getLowestSetBit();

      // assert k.testBit(s);

      BigInteger Uh = ECConstants.ONE;
      BigInteger Vl = ECConstants.TWO;
      BigInteger Vh = P;
      BigInteger Ql = ECConstants.ONE;
      BigInteger Qh = ECConstants.ONE;

      for (int j = n - 1; j >= s + 1; --j) {
        Ql = modMult(Ql, Qh);

        if (k.testBit(j)) {
          Qh = modMult(Ql, Q);
          Uh = modMult(Uh, Vh);
          Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
          Vh = modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
        } else {
          Qh = Ql;
          Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
          Vh = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
          Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        }
      }

      Ql = modMult(Ql, Qh);
      Qh = modMult(Ql, Q);
      Uh = modReduce(Uh.multiply(Vl).subtract(Ql));
      Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
      Ql = modMult(Ql, Qh);

      for (int j = 1; j <= s; ++j) {
        Uh = modMult(Uh, Vl);
        Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
        Ql = modMult(Ql, Ql);
      }

      return new BigInteger[] {Uh, Vl};
    }
Example #20
0
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    BigInteger one = BigInteger.ONE;
    BigInteger two = new BigInteger("2");
    BigInteger three = new BigInteger("3");

    System.out.print("Enter a natural number: ");
    BigInteger number = new BigInteger(input.nextLine());
    if (number.compareTo(one) <= 0) return; // check number <= 1

    while (number.compareTo(one) != 0) { // while number != 1
      if (number.testBit(0)) { // check if odd
        number = number.multiply(three).add(one);
      } else {
        number = number.divide(two);
      }
      System.out.println(number);
    }
  }
Example #21
0
    private static BigInteger[] lucasSequence(
        BigInteger p, BigInteger P, BigInteger Q, BigInteger k) {
      int n = k.bitLength();
      int s = k.getLowestSetBit();

      BigInteger Uh = ECConstants.ONE;
      BigInteger Vl = ECConstants.TWO;
      BigInteger Vh = P;
      BigInteger Ql = ECConstants.ONE;
      BigInteger Qh = ECConstants.ONE;

      for (int j = n - 1; j >= s + 1; --j) {
        Ql = Ql.multiply(Qh).mod(p);

        if (k.testBit(j)) {
          Qh = Ql.multiply(Q).mod(p);
          Uh = Uh.multiply(Vh).mod(p);
          Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
          Vh = Vh.multiply(Vh).subtract(Qh.shiftLeft(1)).mod(p);
        } else {
          Qh = Ql;
          Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
          Vh = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
          Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        }
      }

      Ql = Ql.multiply(Qh).mod(p);
      Qh = Ql.multiply(Q).mod(p);
      Uh = Uh.multiply(Vl).subtract(Ql).mod(p);
      Vl = Vh.multiply(Vl).subtract(P.multiply(Ql)).mod(p);
      Ql = Ql.multiply(Qh).mod(p);

      for (int j = 1; j <= s; ++j) {
        Uh = Uh.multiply(Vl).mod(p);
        Vl = Vl.multiply(Vl).subtract(Ql.shiftLeft(1)).mod(p);
        Ql = Ql.multiply(Ql).mod(p);
      }

      return new BigInteger[] {Uh, Vl};
    }
Example #22
0
  protected BigInteger compute() {

    if (n.compareTo(TWO) < 1) {
      return BigInteger.ONE;
    }

    BigInteger k = n.shiftRight(1); // n.divide(TWO);
    FibRecursiveTask f1 = new FibRecursiveTask(k.add(BigInteger.ONE));
    f1.fork();
    FibRecursiveTask f2 = new FibRecursiveTask(k);
    BigInteger b = f2.compute();
    BigInteger a = f1.join();
    // is n odd
    if (n.testBit(0)) {
      // return a*a + b*b;
      // return KaratsubaMultiplication.multiply(a, a).add(KaratsubaMultiplication.multiply(b, b));
      return a.multiply(a).add(b.multiply(b));
    }
    // return b*(2*a - b);
    // return KaratsubaMultiplication.multiply(b,a.shiftLeft(1).subtract(b));
    return b.multiply(a.shiftLeft(1).subtract(b));
  }
  /**
   * left-to-right exponentiation with k-bit window. NB. must have k >= 1.
   *
   * @param n
   */
  protected void elementPowWind(BigInteger n) {
    /* early abort if raising to power 0 */
    if (n.signum() == 0) {
      setToOne();
      return;
    }

    int word = 0; /* the word to look up. 0<word<base */
    int wbits = 0; /* # of bits so far in word. wbits<=k. */
    int k = optimalPowWindowSize(n);
    List<Element> lookup = buildPowWindow(k);
    Element result = field.newElement().setToOne();

    for (int inword = 0, s = n.bitLength() - 1; s >= 0; s--) {
      result.square();
      int bit = n.testBit(s) ? 1 : 0;

      if (inword == 0 && bit == 0) continue; /* keep scanning. note continue. */

      if (inword == 0) {
        /* was scanning, just found word */
        inword = 1; /* so, start new word */
        word = 1;
        wbits = 1;
      } else {
        word = (word << 1) + bit;
        wbits++; /* continue word */
      }

      if (wbits == k || s == 0) {
        result.mul(lookup.get(word));
        inword = 0;
      }
    }

    set(result);
  }
 /**
  * Compute a square root of v (mod p).
  *
  * @return a square root of v (mod p) if one exists, or null otherwise.
  */
 BigInteger sqrt(BigInteger v) {
   if (v.signum() == 0) {
     return _0;
   }
   // case I: p = 3 (mod 4):
   if (p.testBit(1)) {
     BigInteger r = v.modPow(p.shiftRight(2).add(_1), p);
     // test solution:
     return r.multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
   }
   // case II: p = 5 (mod 8):
   if (p.testBit(2)) {
     BigInteger twog = v.shiftLeft(1).mod(p);
     BigInteger gamma = twog.modPow(p.shiftRight(3), p);
     BigInteger i = twog.multiply(gamma).multiply(gamma).mod(p);
     BigInteger r = v.multiply(gamma).multiply(i.subtract(_1)).mod(p);
     // test solution:
     return r.multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
   }
   // case III: p = 9 (mod 16):
   if (p.testBit(3)) {
     BigInteger twou = p.shiftRight(2); // (p-1)/4
     BigInteger s0 = v.shiftLeft(1).modPow(twou, p); // (2v)^(2u) mod p
     BigInteger s = s0;
     BigInteger d = _1;
     BigInteger fouru = twou.shiftLeft(1);
     while (s.add(_1).compareTo(p) != 0) {
       d = d.add(_2);
       s = d.modPow(fouru, p).multiply(s0).mod(p);
     }
     BigInteger w = d.multiply(d).multiply(v).shiftLeft(1).mod(p);
     // assert (w.modPow(twou, p).add(_1).compareTo(p) == 0);
     BigInteger z = w.modPow(p.shiftRight(4), p); // w^((p-9)/16)
     BigInteger i = z.multiply(z).multiply(w).mod(p);
     BigInteger r = z.multiply(d).multiply(v).multiply(i.subtract(_1)).mod(p);
     // test solution:
     return r.multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
   }
   // case IV: p = 17 (mod 32):
   if (p.testBit(4)) {
     BigInteger twou = p.shiftRight(3); // (p-1)/8
     BigInteger s0 = v.shiftLeft(1).modPow(twou, p); // (2v)^(2u) mod p
     BigInteger s = s0;
     BigInteger d = _1;
     BigInteger fouru = twou.shiftLeft(1); // (p-1)/4
     while (s.add(_1).compareTo(p) != 0) {
       d = d.add(_2);
       s = d.modPow(fouru, p).multiply(s0).mod(p);
     }
     BigInteger w = d.multiply(d).multiply(v).shiftLeft(1).mod(p);
     // assert (w.modPow(twou, p).add(_1).compareTo(p) == 0);
     BigInteger z = w.modPow(p.shiftRight(5), p); // w^((p-17)/32)
     BigInteger i = z.multiply(z).multiply(w).mod(p);
     BigInteger r = z.multiply(d).multiply(v).multiply(i.subtract(_1)).mod(p);
     // test solution:
     return r.multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
   }
   // case V: p = 1 (mod 4, 8, 16, 32):
   if (v.compareTo(_4) == 0) {
     return _2;
   }
   BigInteger z = v.subtract(_4).mod(p);
   BigInteger t = _1;
   while (legendre(z) >= 0) {
     t = t.add(_1);
     z = v.multiply(t).multiply(t).subtract(_4).mod(p);
   }
   z = v.multiply(t).multiply(t).subtract(_2).mod(p);
   BigInteger r = lucas(z, p.shiftRight(2)).multiply(t.modInverse(p)).mod(p);
   // test solution:
   return r.multiply(r).subtract(v).mod(p).signum() == 0 ? r : null;
 }
 /** Compute the quadratic character of v, i.e. (v/p) for prime p. */
 public int legendre(BigInteger v) {
   // return v.modPow(p.shiftRight(1), p).add(_1).compareTo(p) == 0 ? -1 : 1; // v^((p-1)/2) mod p
   // = (v/p) for prime p
   int J = 1;
   BigInteger x = v, y = p;
   if (x.signum() < 0) {
     x = x.negate();
     if (y.testBit(0) && y.testBit(1)) { // y = 3 (mod 4)
       J = -J;
     }
   }
   while (y.compareTo(_1) > 0) {
     x = x.mod(y);
     if (x.compareTo(y.shiftRight(1)) > 0) {
       x = y.subtract(x);
       if (y.testBit(0) && y.testBit(1)) { // y = 3 (mod 4)
         J = -J;
       }
     }
     if (x.signum() == 0) {
       x = _1;
       y = _0;
       J = 0;
       break;
     }
     while (!x.testBit(0) && !x.testBit(1)) { // 4 divides x
       x = x.shiftRight(2);
     }
     if (!x.testBit(0)) { // 2 divides x
       x = x.shiftRight(1);
       if (y.testBit(0) && (y.testBit(1) == !y.testBit(2))) { // y = �3 (mod 8)
         J = -J;
       }
     }
     if (x.testBit(0) && x.testBit(1) && y.testBit(0) && y.testBit(1)) { // x = y = 3 (mod 4)
       J = -J;
     }
     BigInteger t = x;
     x = y;
     y = t; // switch x and y
   }
   return J;
 }
Example #26
0
 protected BigInteger modHalfAbs(BigInteger x) {
   if (x.testBit(0)) {
     x = q.subtract(x);
   }
   return x.shiftRight(1);
 }
Example #27
0
 protected BigInteger modHalf(BigInteger x) {
   if (x.testBit(0)) {
     x = q.add(x);
   }
   return x.shiftRight(1);
 }
Example #28
0
    /**
     * return a sqrt root - the routine verifies that the calculation returns the right value - if
     * none exists it returns null.
     */
    public ECFieldElement sqrt() {
      if (this.isZero() || this.isOne()) // earlier JDK compatibility
      {
        return this;
      }

      if (!q.testBit(0)) {
        throw new RuntimeException("not done yet");
      }

      // note: even though this class implements ECConstants don't be tempted to
      // remove the explicit declaration, some J2ME environments don't cope.

      if (q.testBit(1)) // q == 4m + 3
      {
        BigInteger e = q.shiftRight(2).add(ECConstants.ONE);
        return checkSqrt(new Fp(q, r, x.modPow(e, q)));
      }

      if (q.testBit(2)) // q == 8m + 5
      {
        BigInteger t1 = x.modPow(q.shiftRight(3), q);
        BigInteger t2 = modMult(t1, x);
        BigInteger t3 = modMult(t2, t1);

        if (t3.equals(ECConstants.ONE)) {
          return checkSqrt(new Fp(q, r, t2));
        }

        // TODO This is constant and could be precomputed
        BigInteger t4 = ECConstants.TWO.modPow(q.shiftRight(2), q);

        BigInteger y = modMult(t2, t4);

        return checkSqrt(new Fp(q, r, y));
      }

      // q == 8m + 1

      BigInteger legendreExponent = q.shiftRight(1);
      if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) {
        return null;
      }

      BigInteger X = this.x;
      BigInteger fourX = modDouble(modDouble(X));

      BigInteger k = legendreExponent.add(ECConstants.ONE), qMinusOne = q.subtract(ECConstants.ONE);

      BigInteger U, V;
      Random rand = new Random();
      do {
        BigInteger P;
        do {
          P = new BigInteger(q.bitLength(), rand);
        } while (P.compareTo(q) >= 0
            || !modReduce(P.multiply(P).subtract(fourX))
                .modPow(legendreExponent, q)
                .equals(qMinusOne));

        BigInteger[] result = lucasSequence(P, X, k);
        U = result[0];
        V = result[1];

        if (modMult(V, V).equals(fourX)) {
          return new ECFieldElement.Fp(q, r, modHalfAbs(V));
        }
      } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne));

      return null;
    }
Example #29
0
    /**
     * return a sqrt root - the routine verifies that the calculation returns the right value - if
     * none exists it returns null.
     */
    public ECFieldElement sqrt() {
      if (!q.testBit(0)) {
        throw new RuntimeException("not done yet");
      }

      // p mod 4 == 3
      if (q.testBit(1)) {
        // z = g^(u+1) + p, p = 4u + 3
        ECFieldElement z = new Fp(q, x.modPow(q.shiftRight(2).add(ONE), q));

        return z.square().equals(this) ? z : null;
      }

      // p mod 4 == 1
      BigInteger qMinusOne = q.subtract(ECConstants.ONE);

      BigInteger legendreExponent = qMinusOne.shiftRight(1);
      if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) {
        return null;
      }

      BigInteger u = qMinusOne.shiftRight(2);
      BigInteger k = u.shiftLeft(1).add(ECConstants.ONE);

      BigInteger Q = this.x;
      BigInteger fourQ = Q.shiftLeft(2).mod(q);

      BigInteger U, V;
      Random rand = new Random();
      do {
        BigInteger P;
        do {
          P = new BigInteger(q.bitLength(), rand);
        } while (P.compareTo(q) >= 0
            || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne)));

        BigInteger[] result = lucasSequence(q, P, Q, k);
        U = result[0];
        V = result[1];

        if (V.multiply(V).mod(q).equals(fourQ)) {
          // Integer division by 2, mod q
          if (V.testBit(0)) {
            V = V.add(q);
          }

          V = V.shiftRight(1);

          // assert V.multiply(V).mod(q).equals(x);

          return new ECFieldElement.Fp(q, V);
        }
      } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne));

      return null;

      // BigInteger qMinusOne = q.subtract(ECConstants.ONE);
      // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO);
      // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE)))
      // {
      // return null;
      // }
      //
      // Random rand = new Random();
      // BigInteger fourX = x.shiftLeft(2);
      //
      // BigInteger r;
      // do
      // {
      // r = new BigInteger(q.bitLength(), rand);
      // }
      // while (r.compareTo(q) >= 0
      // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne)));
      //
      // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR);
      // BigInteger n2 = n1.add(ECConstants.ONE);
      // //q.add(ECConstants.THREE).divide(ECConstants.FOUR);
      //
      // BigInteger wOne = WOne(r, x, q);
      // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q);
      // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r);
      //
      // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q)
      // .multiply(x).mod(q)
      // .multiply(wSum).mod(q);
      //
      // return new Fp(q, root);
    }
Example #30
0
 /**
  * 测试是否具有指定编码的权限
  *
  * @param sum
  * @param targetRights
  * @return
  */
 public static boolean testRights(BigInteger sum, int targetRights) {
   return sum.testBit(targetRights);
 }