phpencryptiondiffie-hellman

How does the computer calculate or store Diffie-Hellman values?


So usually the Diffie-Hellman key is 2048 bits as I understand but my computer can barely calculate a 10 digit number. What are some common numbers in Diffie-Hellman?

Here is my code that's suuuper slow:

    $gen = 77;
    $mod = 517165;
    
    $saltA = 1233217;
    $saltB = 5173123;
    
    $calculatedSecretKeyA = gmp_mod(gmp_pow($gen, $saltA), $mod);
    
    $calculatedSecretKeyB = gmp_mod(gmp_pow($gen, $saltB), $mod);

    $calcKeyA = gmp_mod(gmp_pow($calculatedSecretKeyB, $saltA), $mod);
    echo $calculatedSecretKeyB . "^" . $saltA . "" . " mod " . $mod . " = " . $calcKeyA;
    
    
    $calcKeyB = gmp_mod(gmp_pow($calculatedSecretKeyA, $saltB), $mod);
    echo $calculatedSecretKeyA . "^" . $saltB . "" . " mod " . $mod . " = " . $calcKeyB;

Solution

  • Use gmp_powm

    gmp_powm ( GMP|int|string $num , GMP|int|string $exponent , GMP|int|string $modulus ) : GMP

    for the below lines.

    $calculatedSecretKeyA = gmp_powm($gen, $saltA, $mod);
    
    $calculatedSecretKeyB = gmp_powm($gen, $saltB, $mod);
    
    $calcKeyA = gmp_powm($calculatedSecretKeyB, $saltA, $mod);
        
    $calcKeyB = gmp_powm($calculatedSecretKeyA, $saltB, $mod);
    
    

    It uses the modular form of square-and-multiply technique. The intermediate values will never exceed mod^2. Also, it has O(log n) complexity.