pythonnode.jsbigintegerdiffie-hellman

Calculating Diffie Hellman Challenge - Python vs NodeJS


I'm trying to calculate the Diffie-Hellman Challenge in Python based on the algorithm from a NodeJS client app. The code for the NodeJS client app is as follows:

var a = crypto.randomBytes(25).toString('hex');
var p = 'ffffffffffff55555555555555555aaaaaaaaaaaaaddddddddddddd888888888888999999999999ccccccccccc3333333333999999999900000002222222222222bbbbbbbbbbbbbbbb00000000000000ddddddddddddddddd12467382467321846732814672381647382647893216478326478912364897264781269afdcafdcafdcafdcafdcafdcafdacfdcafdcafdcafdcafdca4731829473847321890748392147328190478932748390274893012ffffffff55555555aaaaaaadddddddd8888888899999999cccccccc57856432785643756423786543786789fffff67867896789678967896786fffffccccaaaaa678678967fca67ee6789679cccc2222'
var g = 2
const A = bigInteger(g).modPow(bigInteger(a, 16), bigInteger(p, 16));

The NodeJS app successfully makes the calculation for A and prints the value out as a string in the browser console.

On the other hand, when I use the algorithm in my local Python server, the calculation for A doesn't finish in a timely manner (in fact, the browser has been spinning this whole time while writing this question). Here is the Python code:

 a = secrets.token_hex(25)
 A = (g**int(a, 16)) % int(p, 16)

Can someone tell me why NodeJS can finish the calculation but Python cannot? Should I be using some crypto library to handle Diffie-Hellman verification? How can I get past this issue?


Solution

  • The built-in function pow can be passed a third mod argument to get the modulus of number raised to the power of another, like the modPow function you are calling

    A = pow(g, int(a, 16), int(p, 16))