0% found this document useful (0 votes)
15 views13 pages

CNS Codes For Practical

The document contains Java implementations of various algorithms including Euclidean GCD, Extended Euclidean, Euler's Totient, Miller-Rabin primality test, and several encryption methods such as Caesar Cipher, Playfair Cipher, Hill Cipher, Vigenere Cipher, One Time Pad Cipher, Rail Fence Cipher, Row and Column Transformation Cipher, and S-DES algorithm. Each algorithm is provided with a main method that allows user input for testing purposes. The document serves as a comprehensive guide to understanding and implementing these mathematical and cryptographic algorithms in Java.

Uploaded by

2022cs0136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views13 pages

CNS Codes For Practical

The document contains Java implementations of various algorithms including Euclidean GCD, Extended Euclidean, Euler's Totient, Miller-Rabin primality test, and several encryption methods such as Caesar Cipher, Playfair Cipher, Hill Cipher, Vigenere Cipher, One Time Pad Cipher, Rail Fence Cipher, Row and Column Transformation Cipher, and S-DES algorithm. Each algorithm is provided with a main method that allows user input for testing purposes. The document serves as a comprehensive guide to understanding and implementing these mathematical and cryptographic algorithms in Java.

Uploaded by

2022cs0136
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

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;

public class ExtendedEuclidean {


public static int modInverse(int a, int m) {
int[] r = extendedGCD(a, m);
return (r[0] != 1) ? -1 : (r[1] % m + m) % m;
}

public static int[] extendedGCD(int a, int b) {


if (b == 0) return new int[]{a, 1, 0};
int[] r = extendedGCD(b, a % b);
return new int[]{r[0], r[2], r[1] - (a / b) * r[2]};
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a number (a): ");
int a = sc.nextInt();
System.out.print("Enter modulo (m): ");
int m = sc.nextInt();
int inv = modInverse(a, m);
System.out.println(inv == -1 ? "Modular inverse does not exist" : "Modular
inverse: " + inv);
sc.close();
}
}

3. Euler Totient
import java.util.Scanner;

public class EulerTotient {


public static int phi(int n) {
int result = n;
for (int p = 2; p * p <= n; p++) {
if (n % p == 0) {
result -= result / p;
while (n % p == 0) n /= p;
}
}
if (n > 1) result -= result / n;
return result;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
System.out.println("Euler's Totient Function ϕ(" + n + ") = " + phi(n));
sc.close();
}
}

4. Miller Rabin

import java.util.*;

public class MillerRabin {

static long modPow(long base, long exp, long mod) {


long result = 1;
base %= mod;
while (exp > 0) {
if ((exp & 1) == 1) result = (result * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
return result;
}

static boolean isWitness(long d, long n) {


long a = 2 + new Random().nextInt((int)(n - 4));
long x = modPow(a, d, n);
if (x == 1 || x == n - 1) return true;

while (d != n - 1) {.
x = (x * x) % n;
d *= 2;
if (x == 1) return false;
if (x == n - 1) return true;
}
return false;
}

public static boolean isPrime(long n, int k) {


if (n < 2 || (n != 2 && n % 2 == 0)) return false;
long d = n - 1;
while (d % 2 == 0) d /= 2;

for (int i = 0; i < k; i++)


if (!isWitness(d, n)) return false;

return true;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
long num = sc.nextLong();
System.out.println(num + (isPrime(num, 5) ? " is probably prime." : " is
composite."));
sc.close();
}
}

5. Caesar Cipher

import java.util.Scanner;

public class CaesarCipher {


public static String encrypt(String text, int shift) {
StringBuilder res = new StringBuilder();
for (char ch : text.toCharArray()) {
if (Character.isUpperCase(ch))
res.append((char) ((ch - 'A' + shift) % 26 + 'A'));
else if (Character.isLowerCase(ch))
res.append((char) ((ch - 'a' + shift) % 26 + 'a'));
else res.append(ch);
}
return res.toString();
}

public static String decrypt(String text, int shift) {


return encrypt(text, 26 - shift);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine();
System.out.print("Enter shift: ");
int shift = sc.nextInt();
String enc = encrypt(text, shift), dec = decrypt(enc, shift);
System.out.println("Encrypted: " + enc);
System.out.println("Decrypted: " + dec);
sc.close();
}
}

6. Playfair Cipher

import java.util.*;

public class PlayfairCipher {


static char[][] keyMatrix(String key) {
key = key.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
LinkedHashSet<Character> set = new LinkedHashSet<>();
for (char c : key.toCharArray()) set.add(c);
for (char c = 'A'; c <= 'Z'; c++) if (c != 'J') set.add(c);
Iterator<Character> it = set.iterator();
char[][] m = new char[5][5];
for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) m[i][j] =
it.next();
return m;
}

static String encrypt(String text, char[][] m) {


text = text.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
if (text.length() % 2 != 0) text += "X";
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.length(); i += 2) {
char a = text.charAt(i), b = text.charAt(i + 1);
int[] pa = pos(m, a), pb = pos(m, b);
if (pa[0] == pb[0]) res.append(m[pa[0]][(pa[1] + 1) %
5]).append(m[pb[0]][(pb[1] + 1) % 5]);
else if (pa[1] == pb[1]) res.append(m[(pa[0] + 1) % 5]
[pa[1]]).append(m[(pb[0] + 1) % 5][pb[1]]);
else res.append(m[pa[0]][pb[1]]).append(m[pb[0]][pa[1]]);
}
return res.toString();
}

static int[] pos(char[][] m, char c) {


for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) if (m[i][j] == c)
return new int[]{i, j};
return null;
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter key: ");
char[][] m = keyMatrix(sc.nextLine());
System.out.print("Enter text: ");
System.out.println("Encrypted: " + encrypt(sc.nextLine(), m));
sc.close();
}
}

7. Hill Cipher

import java.util.*;

public class HillCipher {


static int[][] getKeyMatrix(String key) {
int[][] k = new int[2][2];
for (int i = 0; i < 4; i++) k[i / 2][i % 2] = key.charAt(i) - 'A';
return k;
}

static String encrypt(String text, int[][] k) {


if (text.length() % 2 != 0) text += "X";
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.length(); i += 2) {
int a = text.charAt(i) - 'A', b = text.charAt(i + 1) - 'A';
int x = (k[0][0]*a + k[0][1]*b) % 26;
int y = (k[1][0]*a + k[1][1]*b) % 26;
res.append((char)(x + 'A')).append((char)(y + 'A'));
}
return res.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter 4-letter key: ");
int[][] k = getKeyMatrix(sc.next().toUpperCase());
System.out.print("Enter text: ");
String txt = sc.next().toUpperCase().replaceAll("[^A-Z]", "");
System.out.println("Encrypted: " + encrypt(txt, k));
sc.close();
}
}

8. Vignere Cipher

import java.util.*;

public class VigenereCipher {


static String processText(String text, String key, boolean encrypt) {
StringBuilder result = new StringBuilder();
key = key.toUpperCase();
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isAlphabetic(c)) {
int shift = key.charAt(j % key.length()) - 'A';
result.append((char) ((c - (encrypt ? 'A' : 'A' - shift) + shift) %
26 + 'A'));
j++;
} else {
result.append(c); // Non-alphabetic characters remain unchanged
}
}
return result.toString();
}

static String encrypt(String text, String key) {


return processText(text, key, true);
}

static String decrypt(String text, String key) {


return processText(text, key, false);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine();
System.out.print("Enter key: ");
String key = sc.nextLine();
System.out.println("Encrypted: " + encrypt(text, key));
System.out.println("Decrypted: " + decrypt(encrypt(text, key), key));
sc.close();
}
}

9. One time pad Cipher

import java.util.*;

public class OneTimePadCipher {


static String xorOperation(String text, String key) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c1 = text.charAt(i), c2 = key.charAt(i);
result.append((char) ((c1 ^ c2) + 'A')); // XOR each character
}
return result.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter plaintext: ");
String text = sc.nextLine().toUpperCase().replaceAll("[^A-Z]", "");
System.out.print("Enter key (same length as plaintext): ");
String key = sc.nextLine().toUpperCase().replaceAll("[^A-Z]", "");
if (text.length() != key.length()) {
System.out.println("Error: Key must be the same length as plaintext.");
} else {
String encrypted = xorOperation(text, key);
String decrypted = xorOperation(encrypted, key);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
sc.close();
}
}

10. Rail Fence Cipher

import java.util.*;

public class RailFenceCipher {


static String encrypt(String text, int key) {
char[][] rail = new char[key][text.length()];
for (char[] row : rail) Arrays.fill(row, '\n');
int dir = 1, row = 0;
for (int i = 0; i < text.length(); i++) {
rail[row][i] = text.charAt(i);
if (row == 0 || row == key - 1) dir = -dir;
row += dir;
}
StringBuilder result = new StringBuilder();
for (char[] r : rail) for (char c : r) if (c != '\n') result.append(c);
return result.toString();
}

static String decrypt(String text, int key) {


char[][] rail = new char[key][text.length()];
for (char[] row : rail) Arrays.fill(row, '\n');
int dir = 1, row = 0;
for (int i = 0; i < text.length(); i++) {
rail[row][i] = '*';
if (row == 0 || row == key - 1) dir = -dir;
row += dir;
}
int index = 0;
for (int i = 0; i < key; i++) for (int j = 0; j < text.length(); j++) if
(rail[i][j] == '*') rail[i][j] = text.charAt(index++);
StringBuilder result = new StringBuilder();
row = 0; dir = 1;
for (int i = 0; i < text.length(); i++) {
result.append(rail[row][i]);
if (row == 0 || row == key - 1) dir = -dir;
row += dir;
}
return result.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine().replaceAll("[^A-Za-z]", "");
System.out.print("Enter key: ");
int key = sc.nextInt();
String encrypted = encrypt(text, key);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypt(encrypted, key));
sc.close();
}
}

11. ROW AND COLUMN TRANSFORMATION CIPHER

import java.util.*;

public class RowColumnTransformationCipher {


static String encrypt(String text, int rows, int cols) {
char[][] matrix = new char[rows][cols];
int index = 0;
for (int i = 0; i < rows; i++) for (int j = 0; j < cols && index <
text.length(); j++) matrix[i][j] = text.charAt(index++);
StringBuilder encrypted = new StringBuilder();
for (int j = 0; j < cols; j++) for (int i = 0; i < rows; i++) if (matrix[i]
[j] != 0) encrypted.append(matrix[i][j]);
return encrypted.toString();
}

static String decrypt(String text, int rows, int cols) {


char[][] matrix = new char[rows][cols];
int index = 0;
for (int j = 0; j < cols; j++) for (int i = 0; i < rows && index <
text.length(); i++) matrix[i][j] = text.charAt(index++);
StringBuilder decrypted = new StringBuilder();
for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if (matrix[i]
[j] != 0) decrypted.append(matrix[i][j]);
return decrypted.toString();
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter text: ");
String text = sc.nextLine().replaceAll("[^A-Za-z]", "");
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();
System.out.print("Enter number of columns: ");
int cols = sc.nextInt();
String encrypted = encrypt(text, rows, cols);
String decrypted = decrypt(encrypted, rows, cols);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
sc.close();
}
}

12. S-Des algorithm


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DESAlgorithm {


public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}

public static String decrypt(String encryptedData, String key) throws Exception


{
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData);
}

public static void main(String[] args) throws Exception {


String key = "12345678"; // 8-byte key for DES (56 bits)
String data = "HELLO WORLD";
String encrypted = encrypt(data, key);
System.out.println("Encrypted: " + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("Decrypted: " + decrypted);
}
}

13. RSA algorithm

import java.math.BigInteger;
import java.security.SecureRandom;

public class RSA {

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;
}

public BigInteger getPrivateKey() {


return d;
}

public BigInteger getN() {


return n;
}

public static void main(String[] args) {


RSA rsa = new RSA();
rsa.generateKeys();

String message = "HELLO RSA";


BigInteger msg = new BigInteger(message.getBytes());

System.out.println("Original message: " + message);

// Encrypt the message


BigInteger encryptedMessage = rsa.encrypt(msg);
System.out.println("Encrypted message: " + encryptedMessage);

// Decrypt the message


BigInteger decryptedMessage = rsa.decrypt(encryptedMessage);
String decryptedText = new String(decryptedMessage.toByteArray());
System.out.println("Decrypted message: " + decryptedText);
}
}

13. Diffie Hellman Algorithm

import java.math.BigInteger;
import java.security.SecureRandom;

public class DiffieHellman {


private static BigInteger p; // prime number
private static BigInteger g; // base (primitive root modulo p)

// Generate prime number p and base g


public static void initialize() {
SecureRandom rand = new SecureRandom();
p = BigInteger.probablePrime(512, rand); // Generate 512-bit prime
g = new BigInteger("2"); // A simple base, usually a small prime (2 or 5)
}

// Generate the public value A or B


public static BigInteger computePublicValue(BigInteger privateKey) {
return g.modPow(privateKey, p); // A = g^privateKey % p
}

// Compute the shared secret key


public static BigInteger computeSharedSecret(BigInteger publicValue, BigInteger
privateKey) {
return publicValue.modPow(privateKey, p); // Shared secret =
publicValue^privateKey % p
}

public static void main(String[] args) {


// Initialize Diffie-Hellman parameters
initialize();

// Generate private keys (a for Party 1, b for Party 2)


SecureRandom rand = new SecureRandom();
BigInteger a = new BigInteger(512, rand); // Party 1 private key
BigInteger b = new BigInteger(512, rand); // Party 2 private key

// Compute public values A and B


BigInteger A = computePublicValue(a);
BigInteger B = computePublicValue(b);

// Compute shared secrets


BigInteger secret1 = computeSharedSecret(B, a); // Party 1 computes shared
secret
BigInteger secret2 = computeSharedSecret(A, b); // Party 2 computes shared
secret

// 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);
}
}

14. Digital Signature Algorithm

import java.security.*;
import java.util.Base64;

public class DSAExample {


private static final String ALGORITHM = "DSA";

// Generate DSA keys


public static KeyPair generateKeys() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator =
KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(1024); // DSA key size
return keyPairGenerator.generateKeyPair();
}

// Sign the message with DSA private key


public static String signMessage(String message, PrivateKey privateKey) throws
Exception {
Signature signature = Signature.getInstance(ALGORITHM);
signature.initSign(privateKey);
signature.update(message.getBytes());
byte[] signedData = signature.sign();
return Base64.getEncoder().encodeToString(signedData);
}

// Verify the signature using DSA public key


public static boolean verifySignature(String message, String signedMessage,
PublicKey publicKey) throws Exception {
Signature signature = Signature.getInstance(ALGORITHM);
signature.initVerify(publicKey);
signature.update(message.getBytes());
byte[] signedData = Base64.getDecoder().decode(signedMessage);
return signature.verify(signedData);
}

public static void main(String[] args) throws Exception {


// Step 1: Generate public and private keys
KeyPair keyPair = generateKeys();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

// Step 2: Original message


String message = "This is a secret message.";

// Step 3: Sign the message


String signedMessage = signMessage(message, privateKey);
System.out.println("Signed Message: " + signedMessage);

// Step 4: Verify the signature


boolean isVerified = verifySignature(message, signedMessage, publicKey);
System.out.println("Signature Verified: " + isVerified);
}
}
15. MD5 tool file intergrity

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Verification {

// Method to compute the MD5 checksum of a file


public static String computeMD5(String filePath) throws
NoSuchAlgorithmException, IOException {
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] byteArray = new byte[1024];
int bytesRead = -1;

while ((bytesRead = fileInputStream.read(byteArray)) != -1) {


md5Digest.update(byteArray, 0, bytesRead);
}
fileInputStream.close();

byte[] digest = md5Digest.digest();

// Convert the byte array into a hexadecimal string


StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}

// Method to verify the MD5 checksum


public static boolean verifyMD5(String filePath, String expectedMD5) throws
NoSuchAlgorithmException, IOException {
String computedMD5 = computeMD5(filePath);
return computedMD5.equalsIgnoreCase(expectedMD5);
}

public static void main(String[] args) {


// Example usage
try {
String filePath = "path/to/your/file"; // Replace with the actual file
path
String expectedMD5 = "5d41402abc4b2a76b9719d911017c592"; // Example MD5
hash for "hello" (replace with actual hash)

boolean isValid = verifyMD5(filePath, expectedMD5);


if (isValid) {
System.out.println("File integrity is valid.");
} else {
System.out.println("File integrity is invalid.");
}
} catch (Exception e) {
System.out.println("Error during MD5 verification: " + e.getMessage());
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy