CNS Codes For Practical
CNS Codes For Practical
Euclidean
import java.util.Scanner;
public class EuclideanGCD {
public static int gcd(int a, int b) {
while (b != 0) {
int remainder = a % b;
a = b;
b = remainder;
}
return a;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int result = gcd(num1, num2);
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + result);
scanner.close();
}
}
2. Extended Euclidean:
import java.util.Scanner;
3. Euler Totient
import java.util.Scanner;
4. Miller Rabin
import java.util.*;
while (d != n - 1) {.
x = (x * x) % n;
d *= 2;
if (x == 1) return false;
if (x == n - 1) return true;
}
return false;
}
return true;
}
5. Caesar Cipher
import java.util.Scanner;
6. Playfair Cipher
import java.util.*;
7. Hill Cipher
import java.util.*;
8. Vignere Cipher
import java.util.*;
import java.util.*;
import java.util.*;
import java.util.*;
import java.math.BigInteger;
import java.security.SecureRandom;
private BigInteger n, d, e;
private int bitlen = 2048;
// Key Generation
public void generateKeys() {
SecureRandom rand = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitlen / 2, rand);
BigInteger q = BigInteger.probablePrime(bitlen / 2, rand);
n = p.multiply(q);
BigInteger phi =
(p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
e = new BigInteger("65537"); // Common choice for e
d = e.modInverse(phi); // d is the modular inverse of e (mod phi)
}
// Encryption
public BigInteger encrypt(BigInteger message) {
return message.modPow(e, n); // m^e mod n
}
// Decryption
public BigInteger decrypt(BigInteger cipherText) {
return cipherText.modPow(d, n); // c^d mod n
}
// Helper Methods
public BigInteger getPublicKey() {
return e;
}
import java.math.BigInteger;
import java.security.SecureRandom;
// Output results
System.out.println("Prime number (p): " + p);
System.out.println("Base (g): " + g);
System.out.println("Party 1's private key (a): " + a);
System.out.println("Party 2's private key (b): " + b);
System.out.println("Party 1's public value (A): " + A);
System.out.println("Party 2's public value (B): " + B);
System.out.println("Shared secret (Party 1): " + secret1);
System.out.println("Shared secret (Party 2): " + secret2);
}
}
import java.security.*;
import java.util.Base64;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;