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

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

本文介绍了如何从Java中的BigInteger获取无符号字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换 BigInteger 转换为以big-endian格式编码的无符号整数,但由于 BigInteger.toByteArray 返回带符号的表示形式.如何将该值转换为无符号格式?

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?

(相对)有用的背景

我正在研究一些使用JNI的代码,以使c ++调用某些Java方法来处理某些加密功能(这是一个Microsoft CNG提供程序,它将Java的某些功能卸载了).我在Java中拥有公钥,我需要转换的BigInteger值是椭圆曲线公钥的坐标.根据 CNG文档我需要将这些点提供为以big-endian格式编码的无符号整数".

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".

修改

事后看来,这可能是一个愚蠢的帖子.我对负数和正数以及如何处理该数感到困惑(并且由于时间太晚了,我的思想转向糊涂了),但事实证明,由于.谢谢所有在这里做出回应的人!如果有其他帮助,我会保留.

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.

推荐答案

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

这篇关于如何从Java中的BigInteger获取无符号字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:07