Diffie-Hellman is a key exchange that allows 2 people to share a symmetric key without interaction before hand, first, a person shares an equation, in this case, we use:
$$3^x \mod{17}$$
Next, each person generates a random, usually prime, number. Then, they plug it in for in the equation, let's use 5 and 7:
- Alice: \$3^5 \mod{17} \equiv 9 \$
- Bob: \$3^7 \mod{17} \equiv 6 \$
Finally, they share their generated numbers and calculate a "Shared Secret", this is done by (\$U\$ represents your private number):
\$\text{Public}^U \mod{17}\$
In this case:
- Alice: \$6^5 \mod{17} \equiv 2\$
- Bob: \$9^7 \mod{17} \equiv 2\$
Resulting in both parties having the same number. Confused? See this video.
I've implemented a function to generate that key. Thoughts?
function KeyGen(p1, p2, n){
// Get a binary string, reverse it
var bin = String((n).toString(2)).split("").reverse().join("");
// Base for growth
var grow = n;
// Holds values for totals
var tota = [];
var total = 1;
// The main loop
for(var i = 0; i < bin.length; i++){
tota[i] = 1;
if(bin.substring(i, i + 1) === "1"){
for (var l = grow; l > 0;l--){
tota[i] *= p1;
tota[i] %= p2;
}
}
total *= tota[i];
total %= p2;
grow *= n;
}
return total;
}
// Example of gen
var gen = KeyGen(3, 17, 5);
n
an integer and forget all about the string and array. Replacestring.substring(i, i+1)
andarray[i]
with(number >> i) & 1
. Putn = n | 0;
near the top, too. – sqykly yesterday