0% found this document useful (0 votes)
7 views32 pages

R20-CNS-Lab Manual

The document outlines the vision and mission of a computer science and engineering department, aiming to produce skilled professionals with ethical values and research capabilities. It details the program educational objectives, program outcomes, and program specific outcomes that graduates are expected to achieve. Additionally, the document includes various programming experiments related to encryption algorithms, demonstrating practical applications of the concepts taught in the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views32 pages

R20-CNS-Lab Manual

The document outlines the vision and mission of a computer science and engineering department, aiming to produce skilled professionals with ethical values and research capabilities. It details the program educational objectives, program outcomes, and program specific outcomes that graduates are expected to achieve. Additionally, the document includes various programming experiments related to encryption algorithms, demonstrating practical applications of the concepts taught in the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

DEPARTMENT VISION

To emerge as a center of technical expertise in the field of computer science and


engineering by producing globally competent professionals with technical &
research capabilities, ethical values and team spirit.

DEPARTMENT MISSION
M1: To produce competent software professionals.
M2: To induce application oriented and research capabilities in students for the
betterment of society.
M3: To inculcate ethics and human values in students to adapt to the dynamism in
the field of computing technology.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO1: Graduates are prepared to be engineering practitioners in the areas of
computer science and engineering to solve industry’s technological
problems.
PEO2: Graduates are prepared to be employed in IT industries through advanced
education, research and development and entrepreneurial skills.
PEO3: Graduates are prepared to be responsible computing professionals in an
ethical manner.

PROGRAM OUTCOMES (POs)


After successful completion of the program, the graduates will be able to
PO1: Engineering Knowledge : Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the
solution of complex engineering problems.
PO2: Problem Analysis : Identify, formulate, review resear analyze complex
engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
PO3: Design / Development of Solutions : Design solutions for complex
engineering problems and design system components or processes
that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct Investigations of Complex Problems: Use research-based
knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5: Modern Tool Usage : Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
PO6: The Engineer and Society : Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the professional engineering
practice.
PO7: Environment and Sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts
and demonstrate the knowledge of and need for sustainable development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO9: Individual and Teamwork: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear
instructions.
PO11: Project Management and Finance : Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12: Life-Long Learning: Recognize the need for and have the preparation and
ability to engage in independent and life-long learning in the broadest
context of technological change.
PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO 1: Analyze the problem and identify computing requirements appropriate to


its solution.

PSO 2: Design and development of software based solutions to the real world problems

PSO 3: Adapt to a rapidly changing environment by learning and employing


emerging software tools and technologies.
Table of Contents
Experiment 1: Write a C program that contains a string (char pointer) with a value \Hello
World‘. The program should XOR each character in this string with 0 and displays the result.​ 6
Experiment 2: Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should AND or and XOR each character in this string with 127 and
display the result.​ 7
Experiment 3: Write a Java program to perform encryption and decryption using the following
algorithms:​ 8
3a) Ceaser Cipher​ 8
3b) Substitution Cipher​ 10
3c) Hill cipher​ 11
Experiment 4: Write a Java program to implement the DES algorithm logic​ 15
Experiment 5: Write a C/JAVA program to implement the BlowFish algorithm logic.​ 19
Experiment 6: Write a C/JAVA program to implement the Rijndael algorithm logic.​ 21
Experiment 7: Using Java Cryptography, encrypt the text ―Hello world‖ using BlowFish.
Create your own key using Java keytool.​ 23
Experiment 8: Write a Java program to implement RSA Algoithm.​ 25
Experiment 9: Calculate the message digest of a text using the SHA-1 algorithm in JAVA​ 27
Experiment 10: Calculate the message digest of a text using the MD5 25-26 algorithm in
JAVA.​ 30
Experiment 11: Implement the Diffie-Hellman Key Exchange algorithm.​ 32
Experiment 1: Write a C program that contains a string (char pointer) with a value \Hello
World‘. The program should XOR each character in this string with 0 and displays the
result.

Source code
#include<stdlib.h>
main()
{
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf("\n");
}

Output:
Hello World
Hello World
Experiment 2: Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should AND or and XOR each character in this string with 127 and
display the result.

Source code:
#include <stdio.h>
#include<stdlib.h>
void main()
{
char str[]="Hello World";
char str1[11];
char str2[11]=str[];
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
{
str1[i] = str[i]&127;
printf("%c",str1[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str3[i] = str2[i]^127;
printf("%c",str3[i]);
}
printf("\n");
}

Output:
Hello World
Hello World
Hello World
Experiment 3: Write a Java program to perform encryption and decryption using the
following algorithms:
3a) Ceaser Cipher

Description:
To encrypt a message with a Caesar cipher, each letter in the message is changed
using a simple rule: shift by three. Each letter is replaced by the letter three letters ahead in
the alphabet. A becomes D, B becomes E, and so on. For the last letters, we can think of
alphabet as a circle and "wrap around". W becomes Z, X becomes A, Y becomes B, and Z
becomes C. To change a message back, each letter is replaced by the one three before it.

Algorithm:
STEP-1: Read the plain text from the user.
STEP-2: Read the key value from the user.
STEP-3: If the key is positive then encrypt the text by adding the key with each character in the
plain text. STEP-4: Else subtract the key from the plain text.
STEP-5: Display the cipher text obtained above.

Source code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CeaserCipher {
static Scanner sc=new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
System.out.print("Enter any String: ");
String str = br.readLine();
System.out.print("\nEnter the Key: ");
int key = sc.nextInt();
String encrypted = encrypt(str, key);
System.out.println("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("\nDecrypted String is: "
+decrypted); System.out.println("\n");
}
public static String encrypt(String str, int key)
{ String encrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c + (key % 26);
if (c > 'Z')
c = c - 26;
}
else if (Character.isLowerCase(c)) {
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key)
{ String decrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}
else if (Character.isLowerCase(c)) {
c = c - (key % 26);
if (c < 'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
}
}

Output:
Enter the Key: 5
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello World

3b) Substitution Cipher

Description:
In a Substitution cipher, any character of plain text from the given fixed set of characters is
substituted by some other character from the same set depending on a key. For example with a
shift of 1, A would be replaced by B, B would become C, and so on.

Algorithm:
Input:
●​ A String of both lower and upper case letters, called PlainText.
●​ An Integer denoting the required key.
Procedure:
●​ Create a list of all the characters.
●​ Create a dictionary to store the substitution for all characters.
●​ For each character, transform the given character as per the rule, depending on whether
we’re encrypting or decrypting the text.
●​ Print the new string generated.

Source code:
import java.io.*;
import java.util.*;
public class SubstitutionCipher {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
String a = "abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";
System.out.print("Enter any string: ");
String str = br.readLine();
String decrypt = "";
char c;
for(int i=0;i<str.length();i++)
{
c = str.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
System.out.println("The encrypted data is: " +decrypt);
}
}

Output:
Enter any string: aceho
The encrypted data is: zxvsl

3c) Hill cipher

Description:​
Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented
by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not
an essential feature of the cipher. To encrypt a message, each block of n letters (considered as an
n-component vector) is multiplied by an invertible n × n matrix, against modulus 26. To decrypt
the message, each block is multiplied by the inverse of the matrix used for encryption.
The matrix used for encryption is the cipher key, and it should be chosen randomly from the set
of invertible n × n matrices (modulo 26).

Source code:
import java.io.*;
import java.util.*;
import java.io.*;
public class HillCipher
{
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3];
static float[][] b = new float[3][3];
static float[][] mes = new float[3][1];
static float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// TODO code application logic here
getkeymes();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++)
{
res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}
System.out.print("\nEncrypted string is : ");
for(int i=0;i<3;i++)
{
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
System.out.print("\nDecrypted string is : ");
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
public static void getkeymes() throws IOException {
System.out.println("Enter 3x3 matrix for key (It should be inversible): ");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = sc.nextFloat();
System.out.print("\nEnter a 3 letter string: ");
String msg = br.readLine();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
}
public static void inverse() {
float p,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++)
{
for(int i=0;i<3;i++)
{
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++)
{
if(i!=k)
{
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
}}}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\nInverse Matrix is : ");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
System.out.print(b[i][j] + " ");
System.out.print("\n"); }
}
}

Output:
Enter a 3 letter string: hai
Encrypted string is :fdx
Inverse Matrix is :
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is: hai

Experiment 4: Write a Java program to implement the DES algorithm logic


Description:
DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which are
used for parity checks. The key therefore has a "useful" length of 56 bits, which means that
only 56 bits are actually used in the algorithm. The algorithm involves carrying out
combinations, substitutions and permutations between the text to be encrypted and the key,
while making sure the operations can be performed in both directions. The key is ciphered on
64 bits and made of 16 blocks of 4 bits, generally denoted k1 to k16. Given that "only" 56 bits
are actually used for encrypting, there can be 256 different keys.
The main parts of the algorithm are as follows:
●​ Fractioning of the text into 64-bit blocks
●​ Initial permutation of blocks
●​ Breakdown of the blocks into two parts: left and right, named L and R
●​ Permutation and substitution steps repeated 16 times
●​ Re-joining of the left and right parts then inverse initial permutation

Algorithm:
STEP-1: Read the 64-bit plain text.
STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the original
second 32-bit sequence forms the first part.
STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way. Repeat the same
process for the remaining plain text characters.

Source code:
//Java classes that are mandatory to import for encryption and decryption process
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
{
//creating an instance of the Cipher class for encryption
private static Cipher encrypt;
//creating an instance of the Cipher class for decryption
private static Cipher decrypt;
//initializing vector
private static final byte[] initialization_vector = { 22, 33, 11, 44, 55, 99, 66, 77 };
//main() method
public static void main(String[] args)
{
//path of the file that we want to encrypt
String textFile = "C:/Users/lakshmi satya/Desktop/cns-lab-4-1/DemoData.txt";
//path of the encrypted file that we get as output
String encryptedData = "C:/Users/lakshmi satya/Desktop/cns-lab-4-1/encryteddata.txt";
//path of the decrypted file that we get as output
String decryptedData = "C:/Users/lakshmi satya/Desktop/cns-lab-4-1/decrypteddata.txt";
try
{
//generating keys by using the KeyGenerator class
SecretKey scrtkey = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec aps = new IvParameterSpec(initialization_vector);
//setting encryption mode
encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, scrtkey, aps);
//setting decryption mode
decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, scrtkey, aps);
//calling encrypt() method to encrypt the file
encryption(new FileInputStream(textFile), new FileOutputStream(encryptedData));
//calling decrypt() method to decrypt the file
decryption(new FileInputStream(encryptedData), new FileOutputStream(decryptedData));
//prints the stetment if the program runs successfully
System.out.println("The encrypted and decrypted files have been created successfully.");
}
//catching multiple exceptions by using the | (or) operator in a single catch block
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException | IOException e)
{
//prints the message (if any) related to exceptions
e.printStackTrace();
}
}
//method for encryption
private static void encryption(InputStream input, OutputStream output)
throws IOException
{
output = new CipherOutputStream(output, encrypt);
//calling the writeBytes() method to write the encrypted bytes to the file
writeBytes(input, output);
}
//method for decryption
private static void decryption(InputStream input, OutputStream output)
throws IOException
{
input = new CipherInputStream(input, decrypt);
//calling the writeBytes() method to write the decrypted bytes to the file
writeBytes(input, output);
}
//method for writting bytes to the files
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);
}
//closing the output stream
output.close();
//closing the input stream
input.close();
}
}

Output:
Enter the string: Welcome
String To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg=
Decrypted Value : Welcome

Experiment 5: Write a C/JAVA program to implement the BlowFish algorithm logic.


Description:
Blowfish is an encryption technique designed by Bruce Schneier in 1993 as an alternative to
DES Encryption Technique. It is significantly faster than DES and provides a good encryption
rate with no effective cryptanalysis technique found to date. It is one of the first, secure block
cyphers not subject to any patents and hence freely available for anyone to use.

●​ blockSize: 64-bits
●​ keySize: 32-bits to 448-bits variable size
●​ number of subkeys: 18 [P-array]
●​ number of rounds: 16
●​ number of substit ution boxes: 4 [each having 512 entries of 32-bits each]

Source code:
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import java.util.Base64.Encoder;
public class BlowFish{
public static void main(String[] args) throws Exception{
//TODOcodeapplicationlogichere
KeyGenerator keyGenerator=KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey=keyGenerator.generateKey();
Cipher cipherOut=Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
Encoder encoder=new Encoder();
byte iv[]=cipherOut.getIV();
if (iv!=null)
{
System.out.println("InitializationVectoroftheCipher:"+encoder.encode(iv));
}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new FileOutputStream("outputFile.txt");
CipherOutputStream cout=new CipherOutputStream(fout,cipherOut);
int input= 0;
while((input=fin.read())!=-1){cout.write(input);}
fin.close();cout.close(); }}

Output:
Initialization Vector of the Cipher: dI1MXzW97oQ=
Contents of inputFile.txt: Hello World
Contents of outputFile.txt: ùJÖ˜ NåI“
Experiment 6: Write a C/JAVA program to implement the Rijndael algorithm logic.

Description:
Rijndael (pronounced rain-dahl) is an Advanced Encryption Standard (AES) algorithm. It
replaced the older and weaker Data Encryption Standard (DES) when it was selected as the
standard symmetric key encryption algorithm by the National Institute of Standards and
Technology (NIST).
Rijndael accepts input as one-dimensional 8-bit byte arrays that create data blocks.
The plaintext input is mapped onto state bytes. The corresponding cipher key is also a
one-dimensional 8-bit byte array. In the algorithm, different transformations occur sequentially
on intermediate cipher results:
●​ Key and block size. Rijndael can operate in varying data blocks and key sizes of 128,
192 or 256 bits. There are 1,021 times more AES 128-bit keys than DES 56-bit keys.
●​ Subkey and key schedule. Rijndael's key schedule derives subkeys from the cipher key.
The cipher key expands to create an expanded key, and the subkey is created by deriving
a round key. To ensure security and protect the algorithm from cryptanalytic attacks
against its key generation methods, the expanded key is never directly specified but is
always derived from the cipher key.
●​ Whole byte operations. These operations include addition and multiplication within a
finite field and with matrices. These bytes are treated as polynomials, simplifying
implementations.

Source code:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class Rijndael{
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length *
2); int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); }
return strbuf.toString(); }
public static void main(String[] args) throws Exception
{ String message="Rijndael";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message :
args[0]).getBytes()); System.out.println("encrypted string: " +
asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE,
skeySpec); byte[] original = cipher.doFinal(encrypted); String
originalString = new String(original);
System.out.println("Original string: " + originalString + " " + asHex(original));
}
}

Output:
encrypted string: 746e0dcc319f89ea51cb0725c0608ca2
Original string: Rijndael 52696a6e6461656c
Experiment 7: Using Java Cryptography, encrypt the text ―Hello world‖ using BlowFish.
Create your own key using Java keytool.

Description:
Blowfish is an encryption technique designed by Bruce Schneier in 1993 as an alternative to
DES Encryption Technique. It is significantly faster than DES and provides a good encryption
rate with no effective cryptanalysis technique found to date. It is one of the first, secure block
cyphers not subject to any patents and hence freely available for anyone to use.

●​ blockSize: 64-bits
●​ keySize: 32-bits to 448-bits variable size
●​ number of subkeys: 18 [P-array]
●​ number of rounds: 16
●​ number of substit ution boxes: 4 [each having 512 entries of 32-bits each]

Source code:
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import java.util.Base64.Encoder;
public class BlowFish{
public static void main(String[] args) throws Exception{
//TODOcodeapplicationlogichere
KeyGenerator keyGenerator=KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey=keyGenerator.generateKey();
Cipher cipherOut=Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
Encoder encoder=new Encoder();
byte iv[]=cipherOut.getIV();
if (iv!=null)
{
System.out.println("InitializationVectoroftheCipher:"+encoder.encode(iv));
}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new FileOutputStream("outputFile.txt");
CipherOutputStream cout=new CipherOutputStream(fout,cipherOut);
int input= 0;
while((input=fin.read())!=-1){cout.write(input);}
fin.close();cout.close(); }}

Output:
Initialization Vector of the Cipher: dI1MXzW97oQ=
Contents of inputFile.txt: Hello World
Contents of outputFile.txt: ùJÖ˜ NåI“
Experiment 8: Write a Java program to implement RSA Algorithm.

Description:
RSA is an algorithm used by modern computers to encrypt and decrypt messages. It
is an asymmetric cryptographic algorithm. Asymmetric means that there are two different
keys. This is also called public key cryptography, because one of them can be given to
everyone. A basic principle behind RSA is the observation that it is practical to find three
very large positive integers e, d and n such that with modular exponentiation for all
integer m:
(me)d = m (mod n)
The public key is represented by the integers n and e; and, the private key, by the
integer d. m represents the message. RSA involves a public key and a private key. The public
key can be known by everyone and is used for encrypting messages. The intention is that
messages encrypted with the public key can only be decrypted in a reasonable amount of
time using the private key.

Algorithm:
STEP-1: Select two co-prime numbers as p and q.
STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.
STEP-7: Decryption is done as cipherdmod n

Source code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one prime number..
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger(); // ..and another.
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
}
public static BigInteger generateE(BigInteger fiofn) {
int y, intGCD;
BigInteger e;
BigInteger gcd;
Random x = new Random();
do {
y = x.nextInt(fiofn.intValue()-1);
String z = Integer.toString(y);
e = new BigInteger(z);
gcd = fiofn.gcd(e);
intGCD = gcd.intValue();
}
while(y <= 2 || intGCD != 1);
return e;
}
}

Output:
Enter a Prime number: 3
Enter another prime number: 5
Encryption keys are: 5, 15
Decryption keys are: 5, 15.
Experiment 9: Calculate the message digest of a text using the SHA-1 algorithm in JAVA

Description:
In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function.
SHA-1 produces a 160-bit hash value known as a message digest. The way
this algorithm works is that for a message of size < 264 bits it computes a 160-bit condensed
output called a message digest. The SHA-1 algorithm is designed so that it is practically
infeasible to find two input messages that hash to the same output message. A hash function
such as SHA-1 is used to calculate an alphanumeric string that serves as the cryptographic
representation of a file or a piece of data. This is called a digest and can serve as a digital
signature. It is supposed to be unique and non-reversible.

Algorithm:
STEP-1: Read the 256-bit key values.
STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.
STEP-4: The resultant value is permuted with block E.
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of step-4.
STEP-6: Then it is permuted with a weight value and then with some other key pair and
taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times and
taken as the third block.
STEP-8: The blocks C and D are taken as the block D and E for the final output.

Source code:
import java.security.*;
public class SHA1 {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));
System.out.println(""); }
catch (Exception e) {
System.out.println("Exception: " +e);
}
}
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++)
{
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString(); }
}

Output:
Message digest object info:
Algorithm = SHA1
Provider = SUN version 18
ToString = SHA1 Message Digest from SUN, <initialized>
SHA1("") = DA39A3EE5E6B4B0D3255BFEF95601890AFD80709

SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D

SHA1("abcdefghijklmnopqrstuvwxyz") =
32D10C7B8CF96570CA04CE37F2A19D84240D3A89
Experiment 10: Calculate the message digest of a text using the MD5 25-26 algorithm in
JAVA.

Description:
MD5 is a cryptographic hash function algorithm that takes the message as input of any length
and changes it into a fixed-length message of 16 bytes. MD5 algorithm stands for
the message-digest algorithm. MD5 was developed as an improvement of MD4, with
advanced security purposes. The output of MD5 (Digest size) is always 128 bits.
MD5 was developed in 1991 by Ronald Rivest.

Algorithm:​
STEP-1: Read the 128-bit plain text.
STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.​
STEP-3: Compute the functions f, g, h and i with operations such as, rotations, permutations, etc,.
STEP-4: The output of these functions are combined together as F and performed circular
shifting and then given to key round. S
TEP-5: Finally, right shift of ‘s’ times are performed and the results are combined together to
produce the final output.

Source code:
import java.security.*;
public class MD5 {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") = "
+bytesToHex(output));
System.out.println("");
}
catch (Exception e) {
System.out.println("Exception: " +e); }
}
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString(); } }

Output:
Message digest object info:
Algorithm = MD5
Provider = SUN version 18
ToString = MD5 Message Digest from SUN, <initialized>
MD5("") = D41D8CD98F00B204E9800998ECF8427E
MD5("abc") = 900150983CD24FB0D6963F7D28E17F72
MD5("abcdefghijklmnopqrstuvwxyz") = C3FCD3D76192E4007DFB496CCA67E13B
Experiment 11: Implement the Diffie-Hellman Key Exchange algorithm.
Description:
Diffie–Hellman Key Exchange establishes a shared secret between two parties that can
be used for secret communication for exchanging data over a public network. It is
primarily used as a method of exchanging cryptography keys for use in symmetric
encryption algorithms like AES. The algorithm in itself is very simple. The process
begins by having the two parties, Alice and Bob. Let's assume that Alice wants to
establish a shared secret with Bob.

Algorithm:
STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key as B
and sends the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other one’s secret key
power of a mod p.

Source code:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom; import
javax.crypto.spec.DHParameterSpec; import
javax.crypto.spec.DHPublicKeySpec; public
class DiffeHellman { public final static int
pValue = 47;
public final static int gValue = 71;
public final static int XaValue = 9;
public final static int XbValue = 14;
public static void main(String[] args) throws
Exception { // TODO code application logic here
BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigIntegerXa = new
BigInteger(Integer.toString(XaValue)); BigIntegerXb =
new BigInteger(Integer.toString(XbValue)); createKey();
intbitLength = 512; // 512 bits
SecureRandomrnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createKey() throws Exception {
KeyPairGeneratorkpg =
KeyPairGenerator.getInstance("DiffieHellman"); kpg.initialize(512);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpeckspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("Public key is: " +kspec);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throws
Exception { KeyPairGeneratorkpg =
KeyPairGenerator.getInstance("DiffieHellman"); DHParameterSpecparam = new
DHParameterSpec(p, g); kpg.initialize(param);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpeckspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("\nPublic key is : " +kspec);
}
}

Output:
Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29
Public key is: javax.crypto.spec.DHPublicKeySpec@9971ad

You might also like