简体   繁体   中英

Cycling through the individual bits in a java BigInteger

I'm trying to implement some Montgomery math code for an encryption assignment; I have most of it working except for the step where I need to compare each individual bit in the BigInteger to One.

The math algorithm I've been using , from Step 4 is

for i = k - 1 down to 0 do
xBar = MonPro(xBar, xBar)
if e[i] = 1 then xBar = MonPro(MBar, xBar)

i is just an index, k is the number of bits in the BIgInteger, and b is the exponent. My attempt is:

for(int i = n.bitLength() - 1; i > 0 ; i--) {
    xBar = monPro(xBar, xBar, r, nPrime, n);
    if (n.testBit(i) == true)
         xBar = monPro(mBar, xBar, r, nPrime, n);
}
return monPro(xBar, BigINteger.ONE, r, nPrime, n); 

monPro is a helper function that is definitely working. Likewise, the steps omitted before that code snippet definitely work. So the main question is, how do I bitwise iterate through a BigInteger? Unless I'm wrong about e[i], see below.

I've done an enormous amount of reading on this over the last while and resources are scant with regards to actual implementations. Some of the math papers published on the subject are purely mystifying.

I'm also unsure about is the e[i] above. In the book, it's e with a little i below it, the same way Log2 generally has the 2 written as a small number below it. Can anyone clarify?

I've tried casting the BigInteger to a base 2 string and making a char array out of and doing the compare to 1 on it. I also tried just BigInteger.toString(2) to make a base 2 string and cycle through that using charAt[i] == 1.

I'm certain that all the steps above the e[i] are correct because I've checked them with a lot of different values.

If I'm off the track on the E[i] aspect then could someone explain what it actually means? And if not could anyone point out any errors or slight direction?

This is a homework assignment so please don't list any code beyond snippets.

Any direction or advice would be very much appreciated.

for(int i = n.bitLength() - 1; i > 0 ; i--) { ... }

This will miss bit 0 (because when i==0 the loop terminates.)
Try using >= instead of > :

for(int i = n.bitLength() - 1; i >= 0 ; i--) { ... }

Alternatively, if you are using Java 7 and you know that n is positive, then you can convert it to a BitSet and iterate through its '1' bits:

static void showBitsOf(BigInteger n) {
    if (n.compareTo(BigInteger.ZERO) < 0) {
        throw new IllegalArgumentException("n must not be negative");
    }
    BitSet bs = BitSet.valueOf(n.toByteArray());
    for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
        System.out.println(i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM