如何从 Java 中的 BigInteger 获取无符号字节数组?

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

我需要将 BigInteger to an unsigned integer encoded in big-endian format but I am having issues since BigInteger.toByteArray returns 转换为签名表示。如何将此值转换为无符号格式?

(相对)有用的背景

我正在编写一些代码,这些代码使用 JNI 让 c++ 调用一些 Java 方法来处理一些加密功能(这是一个 Microsoft CNG 提供程序,它将一些功能卸载到 Java)。我在 Java 中有 public 键,我需要转换的 BigInteger 值是 coordinates of the Elliptic Curve Public Key. According to the CNG documentation 我需要将这些点提供为 "unsigned integers encoded in big-endian format".

编辑

事后看来,这可能是愚蠢的 post。我对负数和正数以及如何处理感到困惑(因为已经晚了,我的思绪已经变得混乱)但事实证明,自 elliptic curve points won't be negative 以来我不需要处理它。感谢所有在这里回复的人!我会留下这个以防它对其他人有帮助。

借助 2 的补码参考值,我们可以像下面这样进行操作

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