3

I need to convert a BigInteger to an unsigned integer encoded in big-endian format but I am having issues since BigInteger.toByteArray returns a signed representation. How can I convert this value to an unsigned format?

(Relatively) Helpful Background

I am working on some code that uses JNI to have c++ call some Java methods to handle some cryptographic functionality (this is a Microsoft CNG provider that offloads some functionality to Java). I have the public key in Java and the BigInteger values that I need to convert are the coordinates of the Elliptic Curve Public Key. According to the CNG documentation I need to provide these points as "unsigned integers encoded in big-endian format".

Edit

In hindsight, this might have been a silly post. I was getting confused with negative and positive numbers and how to handle that (and because it's late and my mind has turned to mush) but it turns out that I don't need to deal with that since the elliptic curve points won't be negative. Thank you to everyone who responded on here! I will leave this up in case it helps anyone else.

4
  • 2
    If integer in question is positive, what is the difference? If it is negative, then what should be the result of conversion to unsigned? Commented Sep 3, 2016 at 6:26
  • 1
    Take a look at the answer I gave to a similar qustion. Commented Sep 3, 2016 at 7:26
  • In other words, this is a duplicate of stackoverflow.com/q/38918190/95954 Commented Sep 3, 2016 at 7:30
  • Short answer:prepend a 0 byte to the byte array and load it back into a BigInteger. Then it is positive. Commented Sep 3, 2016 at 7:32

1 Answer 1

1

With the help of a 2's complement reference value we can do this like below

private static final BigInteger TWO_COMPL_REF = BigInteger.ONE.shiftLeft(64);

    public static byte[] parseBigIntegerPositive(BigInteger b) {
        if (b.compareTo(BigInteger.ZERO) < 0)
            b = b.add(TWO_COMPL_REF);

       byte[] unsignedbyteArray= b.toByteArray();
        return unsignedbyteArray;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

That does not return the same value, does it?
@rudy I think yes beacause it will just give unsigned version of byte array
By adding 1^64 to a negative BigInteger? Yes, well, if you truncate it to an unsiged integer, then perhaps. Otherwise, certainly not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.