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

社会主义新天地 提交于 2021-02-07 21:10:20

问题


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.


回答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;
    }


来源:https://stackoverflow.com/questions/39303843/how-to-get-an-unsigned-byte-array-from-a-biginteger-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!