INS Practicals

Practical 1

Aim : Write programs to implement the following Substitution Cipher &Techniques :

Code :

public class CeaserCipher {
String message;
static int key;
//For Encryption..
static String encryptCeaser(String message1, int key1){
    char ch;
    String encryptedMessage ="";
    for(int i=0; i<message1.length(); ++i){
        ch = message1.charAt(i);// ascii value
        
        if(ch >='a' && ch <= 'z')
        {
            ch = (char)(ch + key1);// integer shift
            
            if(ch > 'z')
            {
                ch =(char)(ch - 'z'+'a');
            }
            encryptedMessage += ch;
        }
        else if(ch >= 'A' && ch <= 'Z')
                {
                 ch= (char) (ch + key1);
                 if(ch > 'Z')
                 {
                     ch = (char)(ch - 'Z'+ 'A');
                 }
                 encryptedMessage += ch;
                }
        else{
            encryptedMessage += ch;
        }
    }
    return encryptedMessage;
}
//For decryption
static String decryptCeaser(String message1, int key1){
    char ch;
    String decryptedMessage = "";
    for(int i=0; i < message1.length(); ++i){
        ch = message1.charAt(i);
        if(ch >='a' && ch <= 'z')
        {
            ch = (char)(ch - key1);// integer shift
            
            if(ch < 'a')
            {
                ch =(char)(ch + 'z'-'a'+1);
            
            decryptedMessage += ch;
            }
             else if(ch >= 'A' && ch <= 'Z')
                {
                 ch= (char) (ch - key1);
                 if(ch < 'A')
                 {
                     ch = (char)(ch + 'Z'- 'A'+1);
                 }
                 decryptedMessage += ch;
                }
        else{
            decryptedMessage += ch;
        }
    }
        }
    return decryptedMessage;
    }
public static void main (String args[])
{
    String plainText;
    int key;
    String CipherText;
    String decryptedText;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a message to encrypt : ");
    plainText = sc.nextLine();
    
    System.out.println("Enter key : ");
    key = sc.nextInt();
    CipherText = ecryptCeaser(plainText, key);
    
    System.out.println("Cipher Text = "+CipherText);
   
   
    System.out.println("Orignal Text = "+decryptCeaser(CipherText,key));
    
    //System.out.println("Orignal text=" +decryptCeaser);
}
}

import java.util.Scanner;


public class Monoalphabetic {
    
    public static void main(String args[]){
        final char RALPHABETS [] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
        final char MALPHABETS [] = {'Z','X','C','V','B','N','M','L','K','J','H','G','F','D','S','A','Q','W','E','R','T','Y','U','I','O','P'};
        
        char citext[] = new char[20];
        char detext[] = new char[20];
        int i, len; String p1text;
        
        Scanner s = new Scanner(System.in);
        System.out.print("Enter Plain text:");
        p1text = s.nextLine();
        
        p1text = p1text.toLowerCase();
        
        len = (p1text.length());
        for(i = 0; i < len; i++){
            for (int j = 0; j<26; j++){
                if(RALPHABETS[j] == p1text.charAt(i)){
                    citext[i] = MALPHABETS[j];
                    break;
                }
            }
        }
        System.out.println("Cipher text:");
        
        for(i = 0; i < len; i++){
            System.out.print(citext[i]);
            
        }
        String b = new String(citext);
        
        for (i = 0; i < len; i++){
            for (int j = 0; j<26; j++){
                if (MALPHABETS[j] == b.charAt(i)){
                    detext[i] = RALPHABETS[j];
                    break;
                }
            }
        }
        System.out.print("\nDecipher text:");
        
        for(i = 0; i< len;i++){
            System.out.print(detext[i]);
        }
            
 }
 }

Output :

Ceaser Cipher
Enter Plain text:
mewo
Cipher text:
FBUS
Decipher text:mewo

Practical 2

Aim : Write programs to implement the following Substitution Cipher Techniques:

Code :

package ins36;


import java.lang.Math;
public class Vernam {


    public static void main(String args[]) {
        String plainText = new String("hellomom");
        char[] arText = plainText.toCharArray();


        String key = new String("ABCDEFGZ");
        char[] arKey = key.toCharArray();


        char[] cipherText = new char[8];
        System.out.println("Encoded " + plainText + "to be...");


        for (int i = 0; i < arText.length; i++) {
            cipherText[i] = (char) (arText[i] ^ arKey[i]);
            System.out.print(cipherText[i]);
        }


        System.out.println("\nDecoded to be...\n");
        for (int i = 0; i < cipherText.length; i++) {
            char temp = (char) (cipherText[i] ^ arKey[i]);
            System.out.print(temp);
        }
    }
}

Output :


Practical 3

Aim : Write programs to implement the following Transposition Cipher Techniques: -

Code :

import java.util.Scanner;


class RailFenceCipher {
    
    public static void main (String[] args){
        Scanner in = new Scanner(System.in);
        int i=0,j,l,r,s,c=0, t=0;
        String plainText ="", cipherText="";
        System.out.println("******RAIL-FENCE CIPHER******");
        System.out.println("Enter the plaintext: ");
        plainText = in.nextLine();
        System.out.println("Enter the rails:");
        r = in.nextInt(); //3--rows
        l = plainText.length()/r;
        s=2*l;
        char ct[][] = new char[r][s];
        
        while(i<r){//
            ct[i][c] = plainText.charAt(t);
            t++;
            if(i==r-1 && t<= plainText.length() -1){
                c=c+1;
                for(j=r-2; j>=0; j--){
                    ct[j][c] = plainText.charAt(t);
                    t++;
                    if(j==0 && t<= plainText.length()-1)
                    {
                        c++;
                        i=0;
                    }
                }
            }
            i=i+1;
        }
        for(i=0; i<r; i++){
            for(j=0;j<ct[i].length;j++){
                char d=ct[i][j];
                if(d== '\0'){
                    continue;
                }
                else{
                    cipherText = cipherText + ct[i][j]; 
                }
            }
        }
        System.out.println("The Cipher text is :\n" + cipherText);
        System.out.println(cipherText.length());
    }
}
package ins36;


import java.util.Scanner;


public class SCT {


    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your plain text");
        String ptext = sc.nextLine();
        
        System.out.println("Enter key : ");
        String key = sc.nextLine();
        String plaintext = key.concat(ptext);
        
        
        
        System.out.println("Enter the no of rows ");
        int r = Integer.parseInt(sc.nextLine());


        System.out.println("Enter the no of cols");
        int c = Integer.parseInt(sc.nextLine());


        int count = 0;


        char matrix[][] = new char[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (count >= plaintext.length()) {
                    matrix[i][j] = ' ';
                    count++;
                } else {
                    matrix[i][j] = plaintext.charAt(count);
                    count++;
                }
            }
        }
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                System.out.print("\t" + matrix[i][j]);
            }
            System.out.println("\n");
        }
        System.out.println("\nEnter the order of cols you want to view them in");
        int choice[] = new int[c];
        for (int k = 0; k < c; k++) {
            System.out.println("Choice" + k + "👉");
            choice[k] = Integer.parseInt(sc.nextLine());


        }
        System.out.println("\nCipher text in matrix is ->");
        String cipher = " ";
        for (int j = 0; j < c; j++) {
            int k = choice[j];
            for (int i = 0; i < r; i++) {
                cipher += matrix[i][k];
            }
        }
        System.out.println(cipher);


    }
}

Output :

Simple columnar
Enter your plain text
hehehehehehe
Enter key : 
ola
Enter the no of rows 
5
Enter the no of cols
5
	o	l	a	h	e


	h	e	h	e	h


	e	h	e	h	e

Enter the order of cols you want to view them in
Choice0👉
4
Choice1👉
3
Choice2👉
2
Choice3👉
1
Choice4👉
0


Cipher text in matrix is ->
 ehe  heh  ahe  leh  ohe


Practical 4

Aim : Write program to encrypt and decrypt strings using:

Code :

package DES;

import java.math.BigInteger;
import java.util.Random;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JOptionPane;


public class DES {


    byte[] skey = new byte[1000];
    String skeyString;
    static byte[] raw;
    String inputMessage, encryptedData, decryptedData;


    //Constructor 
    public DES() throws Exception {
        generateSymmetricKey();


        // 2. Input 
        inputMessage = JOptionPane.showInputDialog(null, "Enter Message to Encrypt");


        // 3. Convert it Bytes
        byte[] ibyte = inputMessage.getBytes();
        byte[] ebyte = encrypt(raw, ibyte);
        System.out.println("Encrypted Message " + toHexString(ebyte));


        byte[] dbyte = decrypt(raw, ebyte);
        String decryptedMessage = new String(dbyte);
        System.out.println("Decrypted Message " + decryptedMessage);


    }
    // Method : To generate Symmetric key 


    void generateSymmetricKey() throws Exception {
        Random r = new Random();
        int num = r.nextInt(1000);
        String knum = String.valueOf(num);
        byte[] knumb = knum.getBytes();
        System.out.println("Sym Keys :" + toHexString(knumb));
        skey = getRawKey(knumb);
    }


    public static byte[] getRawKey(byte[] seed) throws Exception {


        KeyGenerator kgen = KeyGenerator.getInstance("DES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(56, sr);
        SecretKey skey = kgen.generateKey();
        raw = skey.getEncoded();


        return raw;
    }


    // method 3: Encryption 
    public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;


    }


    // Method 4. Decryption 
    public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);


        return decrypted;
    }


    public static String toHexString(byte[] hash) {
        BigInteger number = new BigInteger(1, hash);
        StringBuilder hexString = new StringBuilder(number.toString(16));
        while (hexString.length() < 32) {
            hexString.insert(0, "0");
        }
        return hexString.toString();
    }


    public static void main(String[] args) throws Exception {
        DES des = new DES();
    }
}

Output :

Sym Keys :00000000000000000000000000003337
Encrypted Message 00000000000000006dcf5d7e83cfa246
Decrypted Message Mewo


Practical 5

Aim : Write a program to implement RSA algorithm to perform encryption / decryption of a given string

Code :

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

// Java Program to implement the RSA Algorithm
 class RSAAlgo {
     public static void main(String args[]){
         int p,q,n,z,d =0, e, i;
         
         //The number to be encrypted and decrypted
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter value for plain text:");
         int msg = sc.nextInt(); //plain text
         double c;
         BigInteger msgback;
         // 1st prime number p and q
         System.out.println("Enter 1st Prime Number: ");
         p= sc.nextInt();
         System.out.println("Enter 2nd Prime Number:");
         q=sc.nextInt();
         
         n= p*q;
         z=(p-1)*(q-1);
         
         System.out.println("the value of z = "+z);
         
         for(e=2; e<z; e++){
             //e is for public key exponent
             if(gcd(e,z) == 1){
                 break;
             }
         }
         System.out.println("The value of e = "+e);
         for(i=0; i<=9;i++)
         {
             int x = 1+(1*z);
             //d is for private key
             if(x%e==0){
                 d=x/e;
                 break;
             }
         }
         System.out.println("The value of d = "+d);
         //cipher text
         
         c= (Math.pow(msg, e))%n;
         System.out.println("Encrypted messgae is: "+c);
         
         // converting int value of n to BigInteger
         BigInteger N= BigInteger.valueOf(n);
         //convering float value of c  to BigInteger
          BigInteger C= BigDecimal.valueOf(c).toBigInteger();
          msgback = (C.pow(d).mod(N));
          System.out.println("Decrypted message is : "+msgback);
         
     }

    static int gcd(int e, int z) {
        if(e==0){
            return z;
        }
        else{
            return gcd(z%e,e);
        }
    }
    
}

Output :


Practical 6

Aim : Write a program to implement the Diffie-Hellman Key Agreement algorithm to generate symmetric keys.

Code :

package dhalgo;

import java.util.Scanner;

public class DHAlgo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter PRIME NUMBER 1 p: ");
        int p = sc.nextInt();
        System.out.println("ENTER PRIME NUMBER 2 g: ");
        int g = sc.nextInt();
        
        System.out.println("Choose 1st secret no(Alice) 'a':");
        int a = sc.nextInt();
        System.out.println("Choose 2nd secret no(Bob) 'b':");
        int b = sc.nextInt();
        
        int A = (int) Math.pow(g, a)%p; //Alice
        int B = (int) Math.pow(g, b)%p; //Bob
        
        //After changing encrypted values
        int S_A = (int) Math.pow(B, a)%p; //Alice
        int S_B = (int) Math.pow(A, b)%p;//bob
        
        if(S_A == S_B){
            System.out.println("Alice and Bob can communicate with each other");
            System.out.println("They share a secret no="+S_A);
        }
        else{
            System.out.println("Alice and Bob cannot communicate with each other");
        }
        
    }
    
}

Output:


Practical 7 ✅

Aim :

  1. Write a program to implement the MD5 algorithm compute the message digests.

Code :

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {

    public static String toHexString(byte[] hash) {
        //Convert byte array into signum representation
        BigInteger number = new BigInteger(1, hash);

        //Convert message digest into hex value
        StringBuilder hexString = new StringBuilder(number.toString(16));

        //Pad with leading zeros
        while (hexString.length() < 32) {
            hexString.insert(0, '0');
        }
        return hexString.toString();
    }

    public static void main(String args[]) throws NoSuchAlgorithmException {
        try {
            System.out.println("Hash Generated by MD5 for:");

            String s1 = "Information and Security";  //Input text = Plain Text
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(s1.getBytes(StandardCharsets.UTF_8));
            System.out.println("\n" + s1 + " : " + toHexString(hash));
            System.out.println("\nLength "+hash.length);
            //for specifying wrong message digest algo
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Exception thrown for incorrect algorithm : " + e);
        }
    }
}

Output :

HahCode Generated by MD5 for :
Mewo : 584aa0b1eb0824fcbd9d47934001eceb