Search code examples
javabigintegerunsigned-integerunsigned-char

How to get an unsigned byte array from a BigInteger in Java?


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.


Solution

  • 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;
        }