Search code examples
javascriptcryptographydiffie-hellman

Diffie Hellman Key Exhange not working (Javascript)


I tried to create the Diffie Hellman key exchange system in javascript without plugins. My code unfortunately doesn't work and often creates 2 different secret keys.

Code:

var g = next_Prime_num(Math.ceil(Math.random() * 50));
var n = next_Prime_num(Math.ceil(Math.random() * 50) + 50);
    
var a = Math.ceil(Math.random() * (n - 1));
var b = Math.ceil(Math.random() * (n - 1));

var A = mod(Math.pow(g, a), n);
var B = mod(Math.pow(g, b), n);
    
var Ka = mod(Math.pow(B, a), n);
var Kb = mod(Math.pow(A, b), n);
    
    

function next_Prime_num(num) {
    for (var i = num + 1;; i++) {
        var isPrime = true;
        for (var d = 2; d * d <= i; d++) {
            if (i % d === 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            return i;
        }
    }
}
    
function mod(n, m) {
    return n%m;
}

Solution

  • n: must be a prime number yes, but g: must be a primitive root of n, and not a just prime number this is your mistake, you have to add another function to get a primitive root from the givin prim number