INS Practical

0



                                                  

1.CasearCipher 

import java.util.Scanner;

public class CaesarCipher {

    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

    // Encryption method
    public static String encrypt(String plainText, int shiftKey) {
        plainText = plainText.toLowerCase();
        String cipherText = "";

        for (int i = 0; i < plainText.length(); i++) {
            char currentChar = plainText.charAt(i);
            if (ALPHABET.indexOf(currentChar) != -1) { // Check if it's a letter
                int charPosition = ALPHABET.indexOf(currentChar);
                int keyVal = (shiftKey + charPosition) % 26;
                char replaceVal = ALPHABET.charAt(keyVal);
                cipherText += replaceVal;
            } else {
                cipherText += currentChar; // If not a letter, just append it as is
            }
        }
        return cipherText;
    }

    // Decryption method
    public static String decrypt(String cipherText, int shiftKey) {
        cipherText = cipherText.toLowerCase();
        String plainText = "";

        for (int i = 0; i < cipherText.length(); i++) {
            char currentChar = cipherText.charAt(i);
            if (ALPHABET.indexOf(currentChar) != -1) { // Check if it's a letter

2.ModifiedCaesarCipherDemo

import java.util.*;

class CaesarCipher {
    private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

    // Encryption method
    public String encrypt(String plainText, int shiftKey) {
        plainText = plainText.toLowerCase();
        String cipherText = "";

        for (int i = 0; i < plainText.length(); i++) {
            char currentChar = plainText.charAt(i);
            if (ALPHABET.indexOf(currentChar) != -1) { // Only encrypt alphabetic characters
                int charPosition = ALPHABET.indexOf(currentChar);
                int keyVal = (shiftKey + charPosition) % 26;
                char replaceVal = ALPHABET.charAt(keyVal);
                cipherText += replaceVal;
            } else {
                cipherText += currentChar; // Keep non-alphabetic characters unchanged
            }
        }
        return cipherText;
    }

    // Decryption method
    public String decrypt(String cipherText, int shiftKey) {
        cipherText = cipherText.toLowerCase();
        String plainText = "";

        for (int i = 0; i < cipherText.length(); i++) {
            char currentChar = cipherText.charAt(i);
            if (ALPHABET.indexOf(currentChar) != -1) { // Only decrypt alphabetic characters
                int charPosition = ALPHABET.indexOf(currentChar);
                int keyVal = (charPosition - shiftKey) % 26;
                if (keyVal < 0) {
                    keyVal = ALPHABET.length() + keyVal;
                }
                char replaceVal = ALPHABET.charAt(keyVal);
                plainText += replaceVal;
            } else {
                plainText += currentChar; // Keep non-alphabetic characters unchanged
            }
        }
        return plainText;
    }
}

class ModifiedCaesarCipherDemo {
    public static void main(String args[]) throws Exception {
        Scanner input = new Scanner(System.in);
       
        // Taking plain text input
        System.out.println("Type Your Plain Text:");
        String plainText = input.nextLine();

        // Taking shift key input
        System.out.println("Type Your ShiftKey Length:");
        int shiftKey = input.nextInt();
       
        // Creating CaesarCipher object
        CaesarCipher cc = new CaesarCipher();

        // Encrypting the plain text
        String cipherText = cc.encrypt(plainText, shiftKey);
        System.out.println("Your PlainText: " + plainText);
        System.out.println("Your CipherText: " + cipherText);

        // Decrypting the cipher text
        String decryptedText = cc.decrypt(cipherText, shiftKey);
        System.out.println("Your Decrypted Plain Text: " + decryptedText);

        input.close(); // Closing the Scanner to avoid resource leak
    }
}

3.The MonoAlphabetic

import java.util.*;

public class MonoAlphabetic {
    public static void main(String args[]) {
        char ch, ch1;
        int i, pos;
        String input = "";
        String output = "";
       
        Scanner sc = new Scanner(System.in);
       
        String plainText = "abcdefghijklmnopqrstuvwxyz";
        String cipherText = "GHDWVFJEBDHVYUCDKLMNOPQRSZT"; // Same length as plainText
       
        System.out.println("\nPlainText: " + plainText);
        System.out.println("\nCipherText: " + cipherText);
       
        System.out.println("\nUsing MonoAlphabetic Cipher:");
        System.out.println("\nEnter Data To Encrypt:");
        input = sc.nextLine().toLowerCase(); // Convert input to lowercase for consistency
       
        // Encrypting the input
        for (i = 0; i < input.length(); i++) {
            ch = input.charAt(i);
           
            if (plainText.indexOf(ch) != -1) { // Only encrypt alphabetic characters
                pos = plainText.indexOf(ch);
                ch1 = cipherText.charAt(pos);
                output = output + ch1;
            } else {
                output = output + ch; // Non-alphabetic characters stay the same
            }
        }
       
        System.out.println("\nEncrypted Output: " + output);
       
        sc.close(); // Close the scanner to avoid resource leak
    }
}


4.The PolyAlphabetic

import java.util.*;

class PolyAlphabet {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        String p = "", c = "", k = "", l = "abcdefghijklmnopqrstuvwxyz";
       
        System.out.print("Give the plain text: ");
        p = sc.nextLine().toLowerCase(); // Convert to lowercase for consistency
       
        System.out.print("Give the Key: ");
        k = sc.nextLine().toLowerCase(); // Convert to lowercase for consistency
       
        int ky = k.length();
        int pln = p.length();
       
        // Expand the key to match the length of the plaintext
        StringBuilder expandedKey = new StringBuilder(k);
        while (expandedKey.length() < pln) {
            expandedKey.append(k);
        }
       
        // Trim the expanded key to the length of the plaintext
        k = expandedKey.substring(0, pln);
       
        // Encrypting the plaintext
        for (int j = 0; j < pln; j++) {
            if (l.indexOf(p.charAt(j)) != -1) { // Check if character is in the alphabet
                c += l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j))) % 26);
            } else {
                c += p.charAt(j); // Keep non-alphabetic characters unchanged
            }
        }
       
        c = c.toUpperCase();
        System.out.println("Cipher text: " + c);
       
        // Decrypting the cipher text
        String plDecrypted = "";
        for (int r = 0; r < pln; r++) {
            if (l.indexOf(c.charAt(r)) != -1) { // Check if character is in the alphabet
                plDecrypted += l.charAt((l.indexOf(c.charAt(r)) - l.indexOf(k.charAt(r)) + 26) % 26);
            } else {
                plDecrypted += c.charAt(r); // Keep non-alphabetic characters unchanged
            }
        }
       
        System.out.println("Decrypted text: " + plDecrypted);
        sc.close(); // Close the scanner to avoid resource leak
    }
}

5.RSA

import java.math.*;
import java.util.*;

class RSA {
    public static void main(String args[]) {
        BigInteger one = BigInteger.ONE, p, q, n, φ, E, D;
        Scanner s = new Scanner(System.in);

        System.out.println("Enter A's prime number:");
        p = s.nextBigInteger();

        System.out.println("Enter B's prime number:");
        q = s.nextBigInteger();

        n = p.multiply(q);
        φ = (p.subtract(one)).multiply(q.subtract(one)); // φ(n) = (p-1)(q-1)

        // Get the public key E
        E = BigInteger.ZERO;
        do {
            System.out.println("Enter Public key (E):");
            E = s.nextBigInteger();
        } while (!((φ.gcd(E)).equals(one) && E.compareTo(one) > 0 && E.compareTo(φ) < 0));

        // Calculate D, the modular multiplicative inverse of E mod φ(n)
        D = E.modInverse(φ);

        System.out.println("Enter Plain text:");
        String text = s.next(); // Changed to next() for single word input
        StringBuilder out = new StringBuilder();
        StringBuilder in = new StringBuilder();

        for (int i = 0; i < text.length(); i++) {
            BigInteger T = BigInteger.valueOf((int) text.charAt(i)); // Convert char to BigInteger
            BigInteger O = T.modPow(E, n); // Encrypt
            out.append(O.toString()).append(" "); // Store encrypted value as string
            BigInteger TF = O.modPow(D, n); // Decrypt
            in.append((char) TF.intValue()); // Append decrypted character
        }

        System.out.println("Encrypted text (Cipher Text): " + out.toString());
        System.out.println("Decrypted text (Plain Text): " + in.toString());
       
        s.close(); // Close scanner to avoid resource leak
    }
}

6.Message Authentication Codes

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;

public class MacSample {
    public static void main(String args[]) throws Exception {
        // Creating a KeyGenerator object for HMAC
        KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA256");
       
        // Creating a SecureRandom object
        SecureRandom secRandom = new SecureRandom();
       
        // Initializing the KeyGenerator
        keyGen.init(256, secRandom); // Use 256 bits for HMAC-SHA256
       
        // Creating/Generating a key
        Key key = keyGen.generateKey();
       
        // Creating a Mac object
        Mac mac = Mac.getInstance("HmacSHA256");
       
        // Initializing the Mac object
        mac.init(key);
       
        // Computing the Mac
        String msg = "Hi how are you";
        byte[] bytes = msg.getBytes();
        byte[] macResult = mac.doFinal(bytes);
       
        // Displaying the Mac result in hexadecimal format
        System.out.println("Mac result:");
        System.out.println(bytesToHex(macResult));
    }
   
    // Utility method to convert byte array to hex string
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

7.Implement digital signature algorithms such as RSA-based signatures

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Base64;
import java.util.Scanner;

public class DigitalSignature {
    // Signing Algorithm
    private static final String SIGNING_ALGORITHM = "SHA256withRSA";
    private static final String RSA = "RSA";

    // Function to implement Digital signature using SHA256 and RSA algorithm
    public static byte[] createDigitalSignature(byte[] input, PrivateKey key) throws Exception {
        Signature signature = Signature.getInstance(SIGNING_ALGORITHM);
        signature.initSign(key);
        signature.update(input);
        return signature.sign();
    }

    // Generating the asymmetric key pair using SecureRandom class and RSA algorithm
    public static KeyPair generateRSAKeyPair() throws Exception {
        SecureRandom secureRandom = new SecureRandom();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
        keyPairGenerator.initialize(2048, secureRandom);
        return keyPairGenerator.generateKeyPair();
    }

    // Function for Verification of the digital signature using the public key
    public static boolean verifyDigitalSignature(byte[] input, byte[] signatureToVerify, PublicKey key) throws Exception {
        Signature signature = Signature.getInstance(SIGNING_ALGORITHM);
        signature.initVerify(key);
        signature.update(input);
        return signature.verify(signatureToVerify);
    }

    public static void main(String args[]) throws Exception {
        String input = "GEEKSFORGEEKS IS A COMPUTER SCIENCE PORTAL";
        KeyPair keyPair = generateRSAKeyPair();

        // Function Call
        byte[] signature = createDigitalSignature(input.getBytes(), keyPair.getPrivate());
        System.out.println("Signature Value (Hex): " + bytesToHex(signature));
        System.out.println("Verification: " + verifyDigitalSignature(input.getBytes(), signature, keyPair.getPublic()));
    }

    // Utility method to convert byte array to hex string
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

8.Key Exchange using Diffie-Hellman

import java.math.BigInteger;
import java.util.Scanner;

public class DiffieHellman {
    final static BigInteger one = new BigInteger("1");

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
       
        // Input first prime number
        System.out.println("Enter the first prime number:");
        BigInteger p = getNextPrime(sc.next());
       
        // Input second prime number
        System.out.println("Enter the second prime number:");
        BigInteger g = new BigInteger(sc.next());

        // Input random number for Person A
        System.out.println("Person A, enter your random number (x):");
        BigInteger a = new BigInteger(sc.next());
       
        // Calculate result for Person A
        BigInteger resultA = g.modPow(a, p);
        System.out.println("Person A sends " + resultA + " to Person B");

        // Input random number for Person B
        System.out.println("Person B, enter your random number (y):");
        BigInteger b = new BigInteger(sc.next());
       
        // Calculate result for Person B
        BigInteger resultB = g.modPow(b, p);
        System.out.println("Person B sends " + resultB + " to Person A");

        // Calculate the shared secret keys
        BigInteger keyA = resultB.modPow(a, p);
        BigInteger keyB = resultA.modPow(b, p);

        // Output the calculated keys
        System.out.println("Key A calculates: " + keyA);
        System.out.println("Key B calculates: " + keyB);

        // Validate that both keys are equal
        if (keyA.equals(keyB)) {
            System.out.println("Keys match! Shared secret established.");
        } else {
            System.out.println("Keys do not match! Something went wrong.");
        }

        sc.close();
    }

    public static BigInteger getNextPrime(String input) {
        BigInteger test = new BigInteger(input);
        while (!test.isProbablePrime(99)) {
            test = test.add(one);
        }
        return test;
    }
}
   






Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*