带有 gmpy2 的简单 python 程序崩溃了(但我可以在 scala 中做???)-> mpz 类型溢出/中止(核心转储

问题描述 投票:0回答:1

我遇到了上述库的问题,运行了一个非常简单的示例——我可以在 JVM 领域使用类似的库(使用 Scala)来工作。

下面的 Scala 代码片段打印“good”,而 python 版本则因帖子标题中的错误而终止。

想知道这是否是一个已知的错误..或者我在Python版本的计算中做了一些愚蠢的事情?提前谢谢!

斯卡拉

import java.math.BigInteger

import java.nio.charset.StandardCharsets
import java.util.Base64


object Example extends App {
  val pstr: String ="134078079299425970995740249982058461274793658205923933" +
    "77723561443721764030073546976801874298166903427690031" +
    "858186486050853753882811946569946433649006084171"
  val gstr = "11717829880366207009516117596335367088558084999998952205"  +
    "59997945906392949973658374667057217647146031292859482967"  +
    "5428279466566527115212748467589894601965568"
  val hstr = "323947510405045044356526437872806578864909752095244"  +
    "952783479245297198197614329255807385693795855318053"  +
    "2878928001494706097394108577585732452307673444020333"


  val decodedBytes = Base64.getDecoder.decode("Mzc1Mzc0MjE3ODMw")
  val decodedString = new String(decodedBytes, StandardCharsets.UTF_8)     // obfuscated ... can't fall into wrong hands

  val p: BigInteger = new BigInteger(pstr)
  val g: BigInteger = new BigInteger(gstr)
  val h: BigInteger = new BigInteger(hstr)
  val exponent: BigInteger = new BigInteger(decodedString)

  val recover = g.modPow(exponent, p)

  if (recover == h)
    print("good")
  else
    print("bad")
}

Python版本

import gmpy2
import base64

pstr = "134078079299425970995740249982058461274793658205923933" + \
       "77723561443721764030073546976801874298166903427690031" + \
       "858186486050853753882811946569946433649006084171"

gstr = "11717829880366207009516117596335367088558084999998952205" + \
       "59997945906392949973658374667057217647146031292859482967" + \
       "5428279466566527115212748467589894601965568"

hstr = "323947510405045044356526437872806578864909752095244" + \
       "952783479245297198197614329255807385693795855318053" + \
       "2878928001494706097394108577585732452307673444020333"

p = gmpy2.mpz(pstr)
g = gmpy2.mpz(gstr)
h = gmpy2.mpz(hstr)

secret_exponent_encoded = base64.b64decode(b'Mzc1Mzc0MjE3ODMw').decode('utf-8')
exponent = gmpy2.mpz(secret_exponent_encoded)
recover = (g ** exponent) % p

if (recover == h):
    print("true")
else:
    print("false")

python largenumber
1个回答
0
投票

gmpy2
版本 2.2.0a1 下,我收到此错误:

   recover = (g** exponent)  % p
               ^^~~~~~~~~~
ValueError: pow() outrageous exponent

这是有道理的。地球上没有一台计算机有足够的 RAM 来计算这里的

g**exponent
。底层库 (GMP) 不会优雅地处理内存不足 - 它只是中止程序。

但是,通过以下更改,它可以正常运行并打印

True

    #recover = (g** exponent)  % p
    recover = gmpy2.powmod(g, exponent, p)
© www.soinside.com 2019 - 2024. All rights reserved.