Ns Exercise 2
Ns Exercise 2
953622205039
EXPERIMENT-2
<!DOCTYPE html>
<html>
<head>
<title>RSA Encryption</title>
<script>
function gcd(a, b) {
while (b) {
let temp = b;
b = a % b;
a = temp;}
return a; }
function modInverse(e, phi) {
for (let d = 1; d < phi; d++) {
if ((e * d) % phi === 1) {
return d;}
}
return -1; }
function encrypt() {
let p = parseInt(document.getElementById("p").value);
let q = parseInt(document.getElementById("q").value);
let msg = parseInt(document.getElementById("msg").value);
if (isNaN(p) || isNaN(q) || isNaN(msg)) {
alert("Please enter valid numbers!");
return; }
let n = p * q;
let phi = (p - 1) * (q - 1);
let e = 2;
while (e < phi && gcd(e, phi) !== 1) {
SHANMUGA PRIYA V
953622205039
e++; }
let d = modInverse(e, phi);
if (d === -1) {
alert("Error computing modular inverse");
return; }
let cipher = Math.pow(msg, e) % n;
let decrypted = Math.pow(cipher, d) % n;
document.getElementById("publicKey").innerText = "Public Key: (" + e + ", " + n + ")";
document.getElementById("privateKey").innerText = "Private Key: " + d;
document.getElementById("cipherText").innerText = "Cipher Text: " + cipher;
document.getElementById("decryptedText").innerText = "Decrypted Message: " +
decrypted; }
</script>
</head>
<body>
<h2>RSA Encryption Algorithm</h2>
<label>Enter First Prime Number (p):</label>
<input type="number" id="p"><br>
<label>Enter Second Prime Number (q):</label>
<input type="number" id="q"><br>
<label>Enter the Message (as a number):</label>
<input type="number" id="msg"><br>
<button onclick="encrypt()">Apply RSA</button>
<p id="publicKey"></p>
<p id="privateKey"></p>
<p id="cipherText"></p>
<p id="decryptedText"></p>
</body>
</html>
SHANMUGA PRIYA V
953622205039
OUTPUT:
long g = scanner.nextLong();
System.out.print("Enter Alice's Private Key (x): ");
long x = scanner.nextLong();
System.out.print("Enter Bob's Private Key (y): ");
long y = scanner.nextLong();
long A = modExp(g, x, p); // Alice's public key
long B = modExp(g, y, p); // Bob's public key
long S_A = modExp(B, x, p); // Alice computes shared secret
long S_B = modExp(A, y, p); // Bob computes shared secret
System.out.println("\nAlice Sends: " + A);
System.out.println("Bob Computes: " + S_B);
System.out.println("Bob Sends: " + B);
System.out.println("Alice Computes: " + S_A);
System.out.println("Shared Secret: " + S_A);
if (S_A == S_B) {
System.out.println("Success: Shared Secrets Match! " + S_A);
}
else {
System.out.println("Error: Shared Secrets do not match!");
}
scanner.close();
}
}
OUTPUT: