Diffie-Hellman
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
input,
button {
margin: 10px 0;
padding: 10px;
}
.result {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Diffie-Hellman Key Exchange</h1>
<label for="alicePrivateKey">Enter Alice's Private Key:</label>
<input type="number" id="alicePrivateKey" placeholder="Private Key" />
<button onclick="performKeyExchange()">Perform Key Exchange</button>
<div class="result">
<p id="alicePublicKey"></p>
<p id="bobPublicKey"></p>
<p id="sharedSecretAlice"></p>
<p id="sharedSecretBob"></p>
</div>
<script>
const p = 23;
const g = 5;
const bobPrivateKey = Math.floor(Math.random() * (p - 1)) + 1;
function modExp(base, exponent, mod) {
let result = 1;
base = base % mod;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % mod;
}
exponent = Math.floor(exponent / 2);
base = (base * base) % mod;
}
return result;
}
function performKeyExchange() {
const alicePrivateKey = parseInt(document.getElementById("alicePrivateKey").value);
const alicePublicKey = modExp(g, alicePrivateKey, p);
document.getElementById("alicePublicKey").innerText = `Alice's Public Key:
${alicePublicKey}`;
const bobPublicKey = modExp(g, bobPrivateKey, p);
document.getElementById("bobPublicKey").innerText = `Bob's Public Key:
${bobPublicKey}`;
const sharedSecretAlice = modExp(bobPublicKey, alicePrivateKey, p);
document.getElementById("sharedSecretAlice").innerText = `Shared Secret (Alice):
${sharedSecretAlice}`;
const sharedSecretBob = modExp(alicePublicKey, bobPrivateKey, p);
document.getElementById("sharedSecretBob").innerText = `Shared Secret (Bob):
${sharedSecretBob}`;
}
</script>
</body>
</html>
Output: