【问题标题】:In C#, how do I store large prime number?在 C# 中,如何存储大素数?
【发布时间】:2021-06-28 14:47:26
【问题描述】:

大家好,

我正在尝试在 C# 中实现 Diffie-Hellman 密钥交换协议。 首先,这是一个测试项目。我知道我应该将它用于任何实际应用程序。我这样做只是为了进一步了解它。

现在,根据这个 RFC (3526),我需要使用素数 P=2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } 和生成器 G=2

https://datatracker.ietf.org/doc/html/rfc3526#page-6

但是素数太大了!即使是 BigInteger !

我现在该怎么做?

编辑:

我认为它太大了,因为这段代码返回一个负值:

string hexString = "...";
BigInteger number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier);
Console.WriteLine("Converted 0x{0}\nto\n{1}.", hexString, number);

https://dotnetfiddle.net/Ffr7Ip

【问题讨论】:

  • "BigInteger 类型是一个不可变类型,表示一个任意大的整数,其值在理论上没有上限或下限" -- 你确定 i> 对于 BigInteger 来说太大了吗?
  • 好吧,这段代码是这样说的:string hexString = "..."; BigInteger number = BigInteger.Parse(hexString, NumberStyles.AllowHexSpecifier); Console.WriteLine("Converted 0x{0}\nto\n{1}.", hexString, number); hexString 是十六进制数,可以在主帖的链接中找到。
  • 你能把工作复制到dotnetfiddle.net吗?
  • 看起来不错?它将它解释为一个有符号的数字,但坚持一个前导 0 并且它被解释为一个无符号的数字:dotnetfiddle.net/Cme8lI

标签: c# cryptography key diffie-hellman


【解决方案1】:

BigInteger.Parse 将十六进制字符串转换为二进制。如果二进制数以1 开头,则表示该数字已签名。这就是为什么它给你一个负数。正如@canton7 所说,只需在前面加上0 就可以了。

【讨论】:

  • 另一种方式(可能最好),检查它是否为负数,如果是则否定它
  • 我不认为这会起作用,因为有符号的数字使用二的恭维。
猜你喜欢
  • 2011-08-05
  • 2011-02-08
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2019-02-28
  • 1970-01-01
相关资源
最近更新 更多