gpt4 book ai didi

c# - 如何在 C# 中实现 BN_num_bytes() (和 BN_num_bits() )?

转载 作者:IT老高 更新时间:2023-10-28 22:30:25 30 4
gpt4 key购买 nike

我是 porting this line from C++ to C#,,不是经验丰富的 C++ 程序员:

 unsigned int nSize = BN_num_bytes(this); 

在 .NET 中我是 using System.Numerics.BigInteger

 BigInteger num = originalBigNumber;
byte[] numAsBytes = num.ToByteArray();
uint compactBitsRepresentation = 0;
uint size2 = (uint)numAsBytes.Length;

我认为它们在内部的操作方式存在根本差异,因为如果 BigInt 等于 the sources' unit tests' results 则不匹配:

  • 0
  • 任何负数
  • 0x00123456

我对 BN_num_bytes 一无所知(编辑:评论告诉我它是 BN_num_bits 的宏)

问题

你能验证这些关于代码的猜测吗:

  • 我需要移植 BN_num_bytes 这是 ((BN_num_bits(bn)+7)/8) 的宏(谢谢@WhozCraig)

  • 我需要移植 BN_num_bitsfloor(log2(w))+1

那么,如果存在不计算前导字节和尾随字节的可能性,那么在 Big/Little endian 机器上会发生什么?有关系吗?

基于 these answers on Security.StackExchange, 并且我的应用程序不是性能关键,我可以使用 .NET 中的默认实现,而不使用可能已经实现类似解决方法的替代库。


编辑:到目前为止,我的实现看起来像这样,但我不确定评论中提到的“LookupTable”是什么。

   private static int BN_num_bytes(byte[] numAsBytes)
{
int bits = BN_num_bits(numAsBytes);
return (bits + 7) / 8;
}

private static int BN_num_bits(byte[] numAsBytes)
{
var log2 = Math.Log(numAsBytes.Length, 2);
var floor = Math.Floor(log2);
return (uint)floor + 1;
}

编辑 2:

经过一番搜索,I found that:

BN_num_bits does not return the number of significant bits of a given bignum, but rather the position of the most significant 1 bit, which is not necessarily the same thing

虽然我仍然不知道它的来源是什么样的......

最佳答案

man page BN_num_bits 的(OpenSSL 项目)说“基本上,除了零,它返回 floor(log2(w))+1。”。所以这些是 .Net 的 BigIntegerBN_num_bytesBN_num_bits 函数的正确实现。

public static int BN_num_bytes(BigInteger number) {
if (number == 0) {
return 0;
}
return 1 + (int)Math.Floor(BigInteger.Log(BigInteger.Abs(number), 2)) / 8;
}

public static int BN_num_bits(BigInteger number) {
if (number == 0) {
return 0;
}
return 1 + (int)Math.Floor(BigInteger.Log(BigInteger.Abs(number), 2));
}

为方便起见,您可能应该将这些更改为扩展方法。

您应该了解,这些函数测量表示给定整数所需的最小位数/字节数。声明为 int (System.Int32) 的变量占用 4 个字节的内存,但您只需要 1 个字节(或 3 位)来表示整数 7。这就是BN_num_bytes 和 BN_num_bits 计算 - 具体数字所需的最小存储大小。

您可以在 official OpenSSL repository 中找到函数的原始实现的源代码。 .

关于c# - 如何在 C# 中实现 BN_num_bytes() (和 BN_num_bits() )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15213853/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com