Search code examples
pythoncryptographyrsamodulowolframalpha

Python modulo result differs from wolfram alpha?


When I run my python 3 program:

exp = 211
p = 199
q = 337

d = (exp ** (-1)) % ((p - 1)*(q - 1))

results in 211^(-1).

But when I run the calculation in wolfram alpha I get the result I was expecting.

I did some test outputs and the variables exp, p and q in the program are all the integer values I used in wolfram alpha.

My goal is to derive a private key from a (weakly) encrypted integer. If I test my wolfram alpha result, I can decrypt the encrypted message correctly.


Solution

  • Wolfram Alpha is computing the modular inverse. That is, it's finding the integer x such that

    exp*x == 1 mod (p - 1)*(q - 1)
    

    This is not the same as the modulo operator %. Here, Python is simply calculating the remainder when 1/exp is divided by (p - 1)*(q - 1) when given the expression in your question.

    Copying the Python code from this answer, you can compute the desired value with Python too:

    >>> modinv(exp, (p - 1)*(q - 1))
    45403