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.

Community
  • 1
  • 1
Hmmmmm
  • 778
  • 9
  • 20
  • 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? – Artur Biesiadowski Sep 03 '16 at 06:26
  • 1
    Take a look at [the answer I gave to a similar qustion](http://stackoverflow.com/questions/38918190/how-to-get-the-2s-complement-value-of-a-biginteger-of-arbitrary-length/38931124#38931124). – Rudy Velthuis Sep 03 '16 at 07:26
  • In other words, this is a duplicate of http://stackoverflow.com/q/38918190/95954 – Rudy Velthuis Sep 03 '16 at 07:30
  • Short answer:prepend a 0 byte to the byte array and load it back into a BigInteger. Then it is positive. – Rudy Velthuis Sep 03 '16 at 07:32

1 Answers1

2

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;
    }
Mark Jeronimus
  • 9,278
  • 3
  • 37
  • 50
Jekin Kalariya
  • 3,475
  • 2
  • 20
  • 32