Skip to main content

INS Prac

INS

Updated 15 min readMarkdown
*Prac1*
1) Caesar Cipher 

CaesarCipherExample.java 
import java.util.Scanner;       
public class CaesarCipherExample    
{    
    public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";          
    public static String encryptData(String inputStr, int shiftKey)    
    {    
        // convert inputStr into lower case    
        inputStr = inputStr.toLowerCase();              
        String encryptStr = "";             
        // use for loop for traversing each character of the input string    
        for (int i = 0; i < inputStr.length(); i++)    
        {    
            // get position of each character of inputStr in ALPHABET    
            int pos = ALPHABET.indexOf(inputStr.charAt(i));                  
            // get encrypted char for each char of inputStr    
            int encryptPos = (shiftKey + pos) % 26;    
            char encryptChar = ALPHABET.charAt(encryptPos);                  
            // add encrypted char to encrypted string    
            encryptStr += encryptChar;    
        }              
        return encryptStr;    
    }          
    // create decryptData() method for decrypting user input string with given shift key    
    public static String decryptData(String inputStr, int shiftKey)    
    {    
        inputStr = inputStr.toLowerCase();              
        // decryptStr to store decrypted data    
        String decryptStr = "";              
        for (int i = 0; i < inputStr.length(); i++)    
        {    
            // get position of each character of inputStr in ALPHABET    
            int pos = ALPHABET.indexOf(inputStr.charAt(i));                 
            // get decrypted char for each char of inputStr    
            int decryptPos = (pos - shiftKey) % 26;                  
            // if decryptPos is negative    
            if (decryptPos < 0){    
                decryptPos = ALPHABET.length() + decryptPos;    
            }    
            char decryptChar = ALPHABET.charAt(decryptPos);                 
            // add decrypted char to decrypted string    
            decryptStr += decryptChar;    
        }    
        return decryptStr;
         }    
    public static void main(String[] args)    
    {    
        Scanner sc = new Scanner(System.in);         
        System.out.println("Enter a string for encryption using Caesar Cipher: ");    
        String inputStr = sc.nextLine();              
        System.out.println("Enter the value by which each character in the plaintext message gets 
shifted: ");    
        int shiftKey = Integer.valueOf(sc.nextLine());     
        System.out.println("Encrypted Data ===> "+encryptData(inputStr, shiftKey));    
        System.out.println("Decrypted Data ===> "+decryptData(encryptData(inputStr, shiftKey), 
shiftKey));    
        sc.close();    
    }    
} 



2) The Monoalphabetic Cypher 

monoalphabet.java 
import java.util.Scanner; 
public class monoalphabet{ 
    public static char normalChar[] 
        = { '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' }; 
    public static char codedChar[] 
        = { 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 
            'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 
            'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M' }; 
    public static String stringEncryption(String s) 
    { 
        String encryptedString = ""; 
        for (int i = 0; i < s.length(); i++) { 
            for (int j = 0; j < 26; j++) { 
                if (s.charAt(i) == normalChar[j]) 
                { 
                    encryptedString += codedChar[j]; 
                    break; 
                } 
                if (s.charAt(i) < 'a' || s.charAt(i) > 'z') 
                { 
                    encryptedString += s.charAt(i); 
                    break; 
                } 
            } 
        } 
        return encryptedString; 
    } 
    public static String stringDecryption(String s) 
    { 
        String decryptedString = "";  
        // Run the for loop for total string 
        for (int i = 0; i < s.length(); i++) 
        { 
            for (int j = 0; j < 26; j++) { 
                if (s.charAt(i) == codedChar[j]) 
                { 
                    decryptedString += normalChar[j]; 
                    break; 
                } 
                if (s.charAt(i) < 'A' || s.charAt(i) > 'Z') 
                { 
                    decryptedString += s.charAt(i); 
                    break; 
                } 
            } 
        }  
        return decryptedString; 
    } 
    public static void main(String args[]) 
    { 
        Scanner sc =new Scanner(System.in); 
        System.out.println("Enter a plain text:"); 
        String str=sc.nextLine(); 
        System.out.println("Plain text: " + str); 
        String encryptedString = stringEncryption(str.toLowerCase()); 
        System.out.println("Encrypted message: "+ encryptedString); 
        System.out.println("Decrypted message: "+ stringDecryption(encryptedString)); 
    }}  

*Prac2*
1) Verman Algorithm/One Time Pad Algorithm 

VernamCipher.java 
import java.util.Scanner; 
public class VernamCipher { 
    public static String stringEncryption(String text, 
                                          String key) 
    { 
        String cipherText = ""; 
        int cipher[] = new int[key.length()]; 

        for (int i = 0; i < key.length(); i++) { 
            cipher[i] = text.charAt(i) - 'A' 
                        + key.charAt(i) 
                        - 'A'; 
        } 
        for (int i = 0; i < key.length(); i++) { 
            if (cipher[i] > 25) { 
                cipher[i] = cipher[i] - 26; 
            } 
        } 
        for (int i = 0; i < key.length(); i++) { 
            int x = cipher[i] + 'A'; 
            cipherText += (char)x; 
        } 
        return cipherText; 
    } 
    public static String stringDecryption(String s, 
                                          String key) 
    { 
        String plainText = ""; 
        int plain[] = new int[key.length()]; 
        for (int i = 0; i < key.length(); i++) { 
            plain[i] 
                = s.charAt(i) - 'A' 
                  - (key.charAt(i) - 'A'); 
        } 
        for (int i = 0; i < key.length(); i++) { 
            if (plain[i] < 0) { 
                plain[i] = plain[i] + 26; 
            } 
        }
         for (int i = 0; i < key.length(); i++) { 
            int x = plain[i] + 'A'; 
            plainText += (char)x; 
        } 
        return plainText; 
    } 
    public static void main(String[] args) 
    { 
        Scanner sc =new Scanner(System.in); 
        System.out.println("Enter a plain text:"); 
        String plainText=sc.nextLine(); 

        String key = "NCBTZOARX"; 

        String encryptedText = stringEncryption( 
            plainText.toUpperCase(), key.toUpperCase()); 
        System.out.println("Cipher Text - " 
                           + encryptedText); 
        System.out.println( 
            "Message - " 
            + stringDecryption(encryptedText, 
                               key.toUpperCase())); 
    } 
}

2) Playfair Cipher 

PlayfairCipher.java 
import java.util.Arrays; 
import java.util.Scanner; 
public class PlayfairCipher { 
     static String removeDuplicate(String s) 
    {  
        int j, index = 0, len = s.length(); 
        char c[] = s.toCharArray();  
        for (int i = 0; i < len; i++) { 
            for (j = 0; j < i; j++) { 
                if (c[i] == c[j]) 
break; 
            } 
            if (i == j) 
                c[index++] = c[i]; 
        } 
         s = new String((Arrays.copyOf(c, index)));  
        return s; 
    }     
    static String removeWhiteSpace(char[] ch, String key) 
    {  
        char[] c = key.toCharArray(); 
        for (int i = 0; i < c.length; i++) { 
            for (int j = 0; j < ch.length; j++) { 
                if (c[i] == ch[j]) 
                    c[i] = ' '; 
            } 
        }  
        key = new String(c);  
        key = key.replaceAll(" ", ""); 
        return key; 
    }    
    static String makePair(String pt) 
    { 
        String s = ""; 
        char c = 'a'; 
        for (int i = 0; i < pt.length(); i++) { 
            if (pt.charAt(i) == ' ') 
                continue; 
            else {  
                c = pt.charAt(i);  
                s += pt.charAt(i); 
            } 
            if (i < pt.length() - 1) 
                if (pt.charAt(i) == pt.charAt(i + 1)) 
                    s += "x"; 
        }         
        if (s.length() % 2 != 0) 
            s += "x"; 
        System.out.println(s);  
        return s; 
    }    
    static int[] findIJ(char a, char b, char x[][]) 
    {  
        int[] y = new int[4]; 
        if (a == 'j') 
            a = 'i'; 
        else if (b == 'j') 
            b = 'i';  
        for (int i = 0; i < 5; i++) { 
            for (int j = 0; j < 5; j++) {  
                if (x[i][j] == a) { 
                    y[0] = i; 
                    y[1] = j; 
                } 
                else if (x[i][j] == b) { 
                    y[2] = i; 
                    y[3] = j; 
                } 
            } 
        } 
        if (y[0] == y[2]) { 
            y[1] += 1; 
            y[3] += 1; 
        } 
        else if (y[1] == y[3]) { 
            y[0] += 1; 
            y[2] += 1; 
        }  
        for (int i = 0; i < 4; i++) 
            y[i] %= 5;  
        return y; 
    }     
    static String encrypt(String pt, char x[][]) 
    {  
        char ch[] = pt.toCharArray(); 
        int a[] = new int[4]; 
        for (int i = 0; i < pt.length(); i += 2) {  
            if (i < pt.length() - 1) {  
                a = findIJ(pt.charAt(i), pt.charAt(i + 1), x);  
                if (a[0] == a[2]) {  
                    ch[i] = x[a[0]][a[1]];  
                    ch[i + 1] = x[a[0]][a[3]]; 
                } 
                else if (a[1] == a[3]) { 
                    ch[i] = x[a[0]][a[1]]; 
                    ch[i + 1] = x[a[2]][a[1]]; 
                } 
                else { 
                    ch[i] = x[a[0]][a[3]]; 
                    ch[i + 1] = x[a[2]][a[1]]; 
                } 
            } 
        } 
        pt = new String(ch); 
        return pt; 
    }  
    public static void main(String[] args) 
    { 
        Scanner sc = new Scanner(System.in); 
        String pt = "meetmeafterlecture"; 
        String key = "monarchy"; 
        key = removeDuplicate(key); 
        char[] ch = key.toCharArray(); 
        String st = "abcdefghiklmnopqrstuvwxyz"; 
        st = removeWhiteSpace(ch, st); 
        char[] c = st.toCharArray(); 
        char[][] x = new char[5][5]; 
        int indexOfSt = 0, indexOfKey = 0; 
        for (int i = 0; i < 5; i++) { 
            for (int j = 0; j < 5; j++) { 
                if (indexOfKey < key.length()) 
                    x[i][j] = ch[indexOfKey++]; 
                else 
                    x[i][j] = c[indexOfSt++]; 
            } 
        } 
        for (int i = 0; i < 5; i++) { 
            for (int j = 0; j < 5; j++) 
                System.out.print(x[i][j] + " ");  
            System.out.println(); 
        } 
        pt = makePair(pt);  
        pt = encrypt(pt, x);     
        System.out.println(pt); 
    }     
}

*Prac3*
1) Rail Fence Cipher 
RailFence.java 
import java.util.*; 
class RailFenceBasic{ 
int depth; 
String Encryption(String plainText,int depth)throws Exception 
{ 
int r=depth,len=plainText.length(); 
int c=len/depth; 
char mat[][]=new char[r][c]; 
int k=0; 
String cipherText=""; 
for(int i=0;i< c;i++) 
{ 
for(int j=0;j< r;j++) 
{ 
if(k!=len) 
mat[j][i]=plainText.charAt(k++); 
else 
mat[j][i]='X'; 
} 
} 
for(int i=0;i< r;i++) 
{ 
for(int j=0;j< c;j++) 
{ 
cipherText+=mat[i][j]; 
} 
} 
return cipherText; 
} 
String Decryption(String cipherText,int depth)throws Exception 
{ 
int r=depth,len=cipherText.length(); 
int c=len/depth; 
char mat[][]=new char[r][c]; 
int k=0; 
String plainText=""; 
for(int i=0;i< r;i++) 
{ 
for(int j=0;j< c;j++) 
{ 
mat[i][j]=cipherText.charAt(k++); 
} 
} 
for(int i=0;i< c;i++)     
{ 
for(int j=0;j< r;j++) 
{ 
plainText+=mat[j][i]; 
} 
} 
return plainText; 
} 
} 
class RailFence{ 
public static void main(String args[])throws Exception 
{ 
RailFenceBasic rf=new RailFenceBasic(); 
Scanner scn=new Scanner(System.in); 
int depth; 
String plainText,cipherText,decryptedText; 
System.out.println("Enter plain text:"); 
plainText=scn.nextLine(); 
System.out.println("Enter depth for Encryption:"); 
depth=scn.nextInt(); 
cipherText=rf.Encryption(plainText,depth); 
System.out.println("Encrypted text is:\n"+cipherText); 
decryptedText=rf.Decryption(cipherText, depth); 
System.out.println("Decrypted text is:\n"+decryptedText); 
} 
} 

2) Simple Columnar Technique 
ColumnarTranspositionCipher.java 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Scanner; 
public class ColumnarTranspositionCipher { 
// Key for Columnar Transposition 
static String key; 
static Map<Character, Integer> keyMap; 
public static void setPermutationOrder() { 
// Add the permutation order into map 
keyMap = new HashMap<>(); 
for (int i = 0; i < key.length(); i++) { 
keyMap.put(key.charAt(i), i); 
} 
}     
// Encryption 
public static String encryptMessage(String msg) { 
int row, col, columnIndex; 
String cipher = ""; 
/* calculate column of the matrix */ 
col = key.length(); 
/* calculate Maximum row of the matrix */ 
row = (int) Math.ceil((double) msg.length() / col); 
char[][] matrix = new char[row][col]; 
for (int i = 0, k = 0; i < row; i++) { 
for (columnIndex = 0; columnIndex < col; ) { 
if (msg.charAt(k) == '\0') { 
/* Adding the padding character '_' */ 
matrix[i][columnIndex] = '_'; 
columnIndex++; 
} 
if (Character.isLetter(msg.charAt(k)) || msg.charAt(k) == ' ') { 
/* Adding only space and alphabet into matrix */ 
matrix[i][columnIndex] = msg.charAt(k); 
columnIndex++; 
} 
k++; 
} 
} 
for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) { 
int j = entry.getValue(); 
// getting cipher text from matrix column wise using permuted key 
for (int i = 0; i < row; i++) { 
if (Character.isLetter(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] 
== '_') { 
cipher += matrix[i][j]; 
} 
} 
} 
return cipher; 
} 
// Decryption 
public static String decryptMessage(String cipher) { 
/* calculate row and column for cipher Matrix */ 
int col = key.length(); 
int row = cipher.length() / col; 
char[][] cipherMat = new char[row][col]; 
/* add character into matrix column wise */ 
int k = 0; 
for (int j = 0; j < col; j++) { 
for (int i = 0; i < row; i++) { 
cipherMat[i][j] = cipher.charAt(k++); 
} 
} 
/* update the order of key for decryption */ 
int index = 0;   
for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) { 
entry.setValue(index++); 
} 
/* Arrange the matrix column wise according to permutation order by adding into 
new matrix */ 
char[][] decCipher = new char[row][col]; 
int keyIndex = 0; 
for (int l = 0, j; l < key.length(); keyIndex++) { 
j = keyMap.get(key.charAt(l++)); 
for (int i = 0; i < row; i++) { 
decCipher[i][keyIndex] = cipherMat[i][j]; 
} 
} 
/* getting Message using matrix */ 
StringBuilder msg = new StringBuilder(); 
for (int i = 0; i < row; i++) { 
for (int j = 0; j < col; j++) { 
if (decCipher[i][j] != '_') { 
msg.append(decCipher[i][j]); 
} 
} 
} 
return msg.toString(); 
} 
// Driver Program 
public static void main(String[] args) { 
Scanner scanner = new Scanner(System.in); 
System.out.println("Columnar Transposition Cipher"); 
System.out.print("Enter the plaintext: "); 
String plaintext = scanner.nextLine(); 
System.out.print("Enter the keyword: "); 
key = scanner.nextLine(); 
setPermutationOrder(); 
// Calling encryption function 
String cipher = encryptMessage(plaintext); 
System.out.println("Encrypted Message: " + cipher); 
// Calling Decryption function 
String decryptedMessage = decryptMessage(cipher); 
System.out.println("Decrypted Message: " + decryptedMessage); 
scanner.close(); 
} 
} 

*Prac4*
1) DES Algorithm 
CODE: 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.security.InvalidAlgorithmParameterException; 
import java.security.InvalidKeyException; 
import java.security.NoSuchAlgorithmException; 
import java.security.spec.AlgorithmParameterSpec; 
import javax.crypto.Cipher; 
import javax.crypto.CipherInputStream; 
import javax.crypto.CipherOutputStream; 
import javax.crypto.KeyGenerator; 
import javax.crypto.NoSuchPaddingException; 
import javax.crypto.SecretKey; 
import javax.crypto.spec.IvParameterSpec; 
public class DesProgram 
{ 
private static Cipher encrypt; 
private static Cipher decrypt; 
private static final byte[] initialization_vector = { 22, 33, 11, 44, 55, 99, 66, 77 }; 
public static void main(String[] args) 
{ 
String textFile = "C:/Users/LAB1-PC10/Desktop/TYCS21/DemoData.txt"; 
String encryptedData = "C:/Users/LAB1-PC10/Desktop/TYCS21/encrypteddata.txt"; 
String decryptedData = "C:/Users/LAB1-PC10/Desktop/TYCS21/decrypteddata.txt"; 
try 
{ 
} 
SecretKey scrtkey = KeyGenerator.getInstance("DES").generateKey(); 
AlgorithmParameterSpec aps = new IvParameterSpec(initialization_vector); 
encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
encrypt.init(Cipher.ENCRYPT_MODE, scrtkey, aps); 
decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
decrypt.init(Cipher.DECRYPT_MODE, scrtkey, aps); 
encryption(new FileInputStream(textFile), new 
FileOutputStream(encryptedData)); 
decryption(new FileInputStream(encryptedData), new 
FileOutputStream(decryptedData)); 
System.out.println("The encrypted and decrypted files have been created 
successfully."); 
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException 
| InvalidAlgorithmParameterException | IOException e) 
{  
e.printStackTrace();     
} 
} 
private static void encryption(InputStream input, OutputStream output) throws IOException 
{ 
output = new CipherOutputStream(output, encrypt); 
writeBytes(input, output); 
} 
private static void decryption(InputStream input, OutputStream output) throws IOException 
{ 
input = new CipherInputStream(input, decrypt); 
writeBytes(input, output); 
} 
private static void writeBytes(InputStream input, OutputStream output) throws IOException 
{ 
byte[] writeBuffer = new byte[512]; 
int readBytes = 0; 
while ((readBytes = input.read(writeBuffer)) >= 0) 
{ 
output.write(writeBuffer, 0, readBytes); 
} 
output.close(); 
input.close(); 
} 
}

2) AES Algorithm 
CODE: 
import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 
import java.nio.charset.StandardCharsets; 
import java.util.Base64; 
import java.util.Scanner; 
public class AESUtil { 
private static final String AES_ALGORITHM = "AES"; 
private static final String AES_PADDING = "AES/ECB/PKCS5Padding"; 
private static final int AES_KEY_LENGTH_BYTES = 16; // 128 bits 
// Method to encrypt plaintext using AES 
public static String encrypt(String plaintext, String key) throws Exception { 
if (key.length() != AES_KEY_LENGTH_BYTES) { 
throw new IllegalArgumentException("Invalid key length. Key must be " + 
AES_KEY_LENGTH_BYTES + " bytes."); 
} 
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), 
AES_ALGORITHM); 
Cipher cipher = Cipher.getInstance(AES_PADDING); 
cipher.init(Cipher.ENCRYPT_MODE, secretKey); 
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); 
return Base64.getEncoder().encodeToString(encryptedBytes); 
} 
// Method to decrypt ciphertext using AES 
public static String decrypt(String ciphertext, String key) throws Exception { 
if (key.length() != AES_KEY_LENGTH_BYTES) { 
throw new IllegalArgumentException("Invalid key length. Key must be " + 
AES_KEY_LENGTH_BYTES + " bytes."); 
} 
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), 
AES_ALGORITHM); 
Cipher cipher = Cipher.getInstance(AES_PADDING); 
cipher.init(Cipher.DECRYPT_MODE, secretKey); 
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext)); 
return new String(decryptedBytes, StandardCharsets.UTF_8); 
} 
public static void main(String[] args) { 
try { 
Scanner scanner = new Scanner(System.in); 
System.out.print("Enter the plaintext: "); 
String plaintext = scanner.nextLine(); 
String key; 
do {     
System.out.print("Enter the encryption/decryption key (must be 16 bytes): "); 
key = scanner.nextLine(); 
} while (key.length() != AES_KEY_LENGTH_BYTES); 
String encryptedText = encrypt(plaintext, key); 
System.out.println("Encrypted: " + encryptedText); 
String decryptedText = decrypt(encryptedText, key); 
System.out.println("Decrypted: " + decryptedText); 
scanner.close(); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
}

*Prac5*
RSA.java 
import java.math.*; 
import java.util.*; 
class RSA { 
public static void main(String args[]) 
{ 
int p, q, n, z, d = 0, e, i; 
BigInteger[] encrypted; 
// The number to be encrypted and decrypted 
System.out.println("Enter the message to be encrypted"); 
Scanner sc = new Scanner(System.in); 
String msg = sc.nextLine(); 
byte[] msgArray = msg.getBytes(); 
encrypted = new BigInteger[msgArray.length]; 
// 1st prime number p 
System.out.println("Enter the first prime number"); 
p = sc.nextInt(); 
// 2nd prime number q 
System.out.println("Enter the Second prime number"); 
q = sc.nextInt(); 
n = p * q; 
z = (p - 1) * (q - 1); 
System.out.println("the value of N = " + 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 + (i * z); 
// d is for private key exponent 
if (x % e == 0) { 
d = x / e; 
break; 
} 
}     
// converting int value of n to BigInteger 
BigInteger N = BigInteger.valueOf(n); 
// encrypting the message 
for(i=0; i<msgArray.length; i++) 
encrypted[i] = (BigInteger.valueOf(msgArray[i]).pow(e)).mod(N); 
// displaying the encrypted message 
String encryptedMessage = ""; 
for(i=0; i<encrypted.length; i++) 
encryptedMessage += encrypted[i].toString() + " "; 
System.out.println("Encrypted message: " + encryptedMessage); 
// decrypting the message 
for(i=0; i<encrypted.length; i++) 
encrypted[i] = (encrypted[i].pow(d)).mod(N); 
// converting the decrypted message back to string 
byte[] decryptedMessage = new byte[encrypted.length]; 
for(i=0; i<encrypted.length; i++) 
decryptedMessage[i] = encrypted[i].byteValue(); 
System.out.println("Decrypted message: " + new String(decryptedMessage)); 
}  
static int gcd(int e, int z) 
{ 
if (e == 0) 
return z; 
else 
return gcd(z % e, e);
} 
}

*Prac6*
DiffieHellmanAlgorithm.java 
import java.util.*;   
// create class DiffieHellmanAlgorithmExample to calculate the key for two persons   
class DiffieHellmanAlgorithm {   
    // main() method start   
    public static void main(String[] args)   
    {   
        long P, G, x, a, y, b, ka, kb;   
        // create Scanner class object to take input from user   
        Scanner sc = new Scanner(System.in);   
        System.out.println("Both the users should be agreed upon the public keys G and P");   
        // take inputs for public keys from the user   
        System.out.println("Enter value for public key by Vinit:");   
        G = sc.nextLong();   
        System.out.println("Enter value for public key by Faria:");   
        P = sc.nextLong();   
        // get input from user for private keys a and b selected by User1 and User2   
        System.out.println("Enter value for private key a selected by Vinit:");   
        a = sc.nextLong();   
        System.out.println("Enter value for private key b selected by Faria:");   
        b = sc.nextLong();         
        // call calculatePower() method to generate x and y keys   
        x = calculatePower(G, a, P);   
        y = calculatePower(G, b, P);   
        // call calculatePower() method to generate ka and kb secret keys after the exchange of x and y 
keys           
        // calculate secret key for User1   
        ka = calculatePower(y, a, P);   
        // calculate secret key for User2    
        kb = calculatePower(x, b, P);   
        // print secret keys of user1 and user2   
        System.out.println("Secret key for User1 is:" + ka);   
        System.out.println("Secret key for User2 is:" + kb);   
    }   
    // create calculatePower() method to find the value of x ^ y mod P   
    private static long calculatePower(long x, long y, long P)   
    {   
        long result = 0;           
        if (y == 1){   
            return x;   
        }   
        else{   
            result = ((long)Math.pow(x, y)) % P;   
            return result;   
        }   
    }      
}  

*Prac7*
MD5.java 
import java.math.BigInteger; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
public class JavaMD5Hash { 
 public static void main(String[] args) { 
  System.out.println("For null " + md5("")); 
  System.out.println("For simple text "+ md5("This is my text")); 
  System.out.println("For simple numbers " + md5("12345")); 
 } 
 public static String md5(String input) { 
  String md5 = null; 
  if(null == input) return null; 
  try { 
   //Create MessageDigest object for MD5 
   MessageDigest digest = MessageDigest.getInstance("MD5"); 
   //Update input string in message digest 
   digest.update(input.getBytes(), 0, input.length()); 
   //Converts message digest value in base 16 (hex)  
   md5 = new BigInteger(1, digest.digest()).toString(16); 
  } 
  catch (NoSuchAlgorithmException e) { 
   e.printStackTrace(); 
  } 
  return md5; 
 } 
}

*Prac8*
HmacSHA1Signature1.java 
import javax.crypto.Mac; 
import javax.crypto.spec.SecretKeySpec; 
import java.security.NoSuchAlgorithmException; 
import java.security.InvalidKeyException; 
import java.util.Scanner; 

public class HmacSHA1Signature1{ 
    public static String calculateHmacSHA1(String key, String message) throws 
NoSuchAlgorithmException, InvalidKeyException { 
        byte[] keyBytes = key.getBytes(); 
        byte[] messageBytes = message.getBytes(); 
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "HmacSHA1"); 
        Mac mac = Mac.getInstance("HmacSHA1"); 
        mac.init(secretKeySpec); 
        byte[] signatureBytes = mac.doFinal(messageBytes); 
        StringBuilder signature = new StringBuilder(); 
        for (byte b : signatureBytes) { 
            signature.append(String.format("%02x", b)); 
        } 
        return signature.toString(); 
    } 
    public static void main(String[] args) { 
        try { 
            Scanner scanner = new Scanner(System.in); 
            System.out.print("Enter the secret key: "); 
            String key = scanner.nextLine() 
            System.out.print("Enter the message to sign: "); 
            String message = scanner.nextLine(); 
            String signature = calculateHmacSHA1(key, message); 
            System.out.println("HMAC-SHA1 Signature: " + signature); 
            scanner.close(); 
        } catch (NoSuchAlgorithmException | InvalidKeyException e) { 
            e.printStackTrace(); 
        } 
    } 
} 

*Prac9*
Server source code 
EchoServer.java 
import javax.net.ssl.SSLServerSocket; 
import javax.net.ssl.SSLServerSocketFactory; 
import javax.net.ssl.SSLSocket; 
import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

public 
class EchoServer { 
    public 
            static 
    void 
            main(String[] arstring) { 
        try { 
            SSLServerSocketFactory sslserversocketfactory = 
                    (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); 
            SSLServerSocket sslserversocket = 
                    (SSLServerSocket) sslserversocketfactory.createServerSocket(9999); 
            SSLSocket sslsocket = (SSLSocket) sslserversocket.accept(); 

            InputStream inputstream = sslsocket.getInputStream(); 
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream); 
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader); 

            String string = null; 
            while ((string = bufferedreader.readLine()) != null) { 
                System.out.println(string); 
                System.out.flush(); 
            } 
        } catch (Exception exception) { 
            exception.printStackTrace(); 
        } 
    } 
} 

Client source code  
EchoClient.java 
import javax.net.ssl.SSLSocket; 
import javax.net.ssl.SSLSocketFactory; 
import java.io.*; 

public class EchoClient { 
    public static void
            main(String[] arstring) { 
        try { 
            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); 
            SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 9999); 

            InputStream inputstream = System.in; 
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream); 
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader); 

            OutputStream outputstream = sslsocket.getOutputStream(); 
            OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream); 
            BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter); 

            String string = null; 
            while ((string = bufferedreader.readLine()) != null) { 
                bufferedwriter.write(string + '\n'); 
                bufferedwriter.flush(); 
            } 
        } catch (Exception exception) { 
            exception.printStackTrace(); 
        } 
    } 
} 

STEP 1:  do this in server… 

>set path (JAVA BIN) 

>keytool -genkey -keystore mySrvKeystore -keyalg RSA 

> java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 
EchoServer 

STEP 2:  do this in client… 
>set path (JAVA BIN) 
> java -Djavax.net.ssl.trustStore=mySrvKeystore -Djavax.net.ssl.trustStorePassword=123456 
EchoClient 
(---send some messages---) 
STEP 3: you’ll see this (output) in server…

No comments yet. Be the first to comment.