0

I'm trying to convert a LargeInteger into a byte[] of unknown length using bitLength() with

static byte[] encodeint(LargeInteger y) {
    //byte[] in = y.toByteArray();
    byte[] in = new byte[(int)Math.ceil((double)y.bitLength() / 8.0)];
    y.toByteArray(in, 0);
    //
    byte[] out = new byte[in.length];
    for (int i=0;i<in.length;i++) {
        out[i] = in[in.length-1-i];
    }
    return out;
}

but the executor returns

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

which points to y.toByteArray(in, 0);.

How can the length of in be properly set?

(The commented code is leftover from converted BigInteger code.)

1 Answers1

2

The javadoc for toByteArray tells you

java.lang.IndexOutOfBoundsException - if bytes.length < (bitLength() >> 3) + 1

Thus in should be >= (bitLength() >> 3) + 1

What you have done is nearly the same except you have not added the 1.

So (int)Math.ceil((double)y.bitLength() / 8.0) -1

but easier to use the documented version y.(bitLength() >> 3) + 1

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
  • Thank you Mark! I was thinking it was due to the remainder. I think for this code (ed25519), it should be as precise as possible, but I don't know. Would you mind adding a snippet to add `1` if there's a remainder? –  Jan 22 '14 at 18:07
  • @Gracchus = the documented version is a precise as possible as if any less you will get the exception – mmmmmm Jan 22 '14 at 18:08