简体   繁体   中英

Converting big-endian byte array BigInteger using .netstandard 2.0

I have a code that works with .netstandard2.1/netcore3.0 because of this constructor of BigInteger class. This ctor is not available for netstandard2.0, and I'd like to be able to achieve the same functionality without forcing netstandard2.1.

Here's the problem:

  • Convert a string to UTF8, and hash it using Sha256
  • Convert the byte array in BigInteger using big endian byte order

Here's my solution that works with .netstandard2.1

    static SHA256 sha256 = SHA256.Create();
    internal static string GetEncoded(string value)
    {
        var data = sha256.ComputeHash(value.GetUTF8Bytes());

        return new BigInteger(
            value: data,
            isUnsigned: true,
            isBigEndian: true).ToString();
    }

This is what the solution can be in netstandard2.0, unfortunately it doesn't produce the same result.

    internal static string GetEncoded(string value)
    {
        var data = sha256.ComputeHash(value.GetUTF8Bytes());

        return new BigInteger(value: data).ToString();
    }

Here are some sample values and their expected encoded outputs.

"encoded": "68086943237164982734333428280784300550565381723532936263016368251445461241953",
"raw": "101 Wilson Lane"

"encoded": "101327353979588246869873249766058188995681113722618593621043638294296500696424",
"raw": "SLC"

From what I understand, the BigInteger(byte[]) ctor expects a little endian byte array. The few solutions I tried didn't produce the expected results, so I'm turning to SO for answers. Any help would be great appreciated.

Related update issue to net core

Here is the code of the constructor you used: https://github.com/dotnet/corefx/blob/191ad0b5d52172366436322bf9d553dc770d23b1/src/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs#L256

You could adapt it in order to replace ReadOnlySpan by byte[].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM