EXERCISE – 9
Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript. Consider the end user as one of the parties (Alice) and the JavaScript application as the other party (Bob).
Aim
To implement the Diffie-Hellman Key Exchange algorithm using HTML and JavaScript.
Description
Diffie-Hellman Key Exchange is a cryptographic technique used to securely share a secret key between two parties over a public network. In this program, the user acts as Alice and the JavaScript program acts as Bob. Both generate public keys and then compute a shared secret key.
Program
<!DOCTYPE html>
<html>
<head>
<title>Diffie-Hellman Key Exchange</title>
</head>
<body>
<h2>Diffie-Hellman Key Exchange Demo</h2>
<label>Prime Number (p):</label>
<input type="number" id="p" value="23"><br><br>
<label>Generator (g):</label>
<input type="number" id="g" value="5"><br><br>
<label>Alice Private Key (a):</label>
<input type="number" id="a"><br><br>
<button onclick="compute()">Generate Shared Key</button>
<h3>Results</h3>
<p id="alicePublic"></p>
<p id="bobPrivate"></p>
<p id="bobPublic"></p>
<p id="aliceSecret"></p>
<p id="bobSecret"></p>
<script>
function modExp(base, exp, mod){
let result = 1;
for(let i=0;i<exp;i++){
result = (result * base) % mod;
}
return result;
}
function compute(){
let p = parseInt(document.getElementById("p").value);
let g = parseInt(document.getElementById("g").value);
let a = parseInt(document.getElementById("a").value);
let b = Math.floor(Math.random()*10)+1;
let A = modExp(g,a,p);
let B = modExp(g,b,p);
let aliceSecret = modExp(B,a,p);
let bobSecret = modExp(A,b,p);
document.getElementById("alicePublic").innerHTML =
"Alice Public Key (A) = " + A;
document.getElementById("bobPrivate").innerHTML =
"Bob Private Key (b) = " + b;
document.getElementById("bobPublic").innerHTML =
"Bob Public Key (B) = " + B;
document.getElementById("aliceSecret").innerHTML =
"Alice Shared Secret = " + aliceSecret;
document.getElementById("bobSecret").innerHTML =
"Bob Shared Secret = " + bobSecret;
}
</script>
</body>
</html>
Steps to Execute the Program
Open Notepad
↓
Type the above HTML code and paste it in Notepad
↓
Save the file as diffie.html
↓
Open the file in any web browser (Chrome / Edge)
↓
Enter Alice Private Key value
↓
Click Generate Shared Key
↓
View the generated output
Sample Output
Alice Public Key (A) = 8
Bob Private Key (b) = 2
Bob Public Key (B) = 2
Alice Shared Secret = 18
Bob Shared Secret = 18
Result
Thus, the Diffie-Hellman Key Exchange mechanism was successfully implemented using HTML and JavaScript.