[go: up one dir, main page]

0% found this document useful (0 votes)
38 views29 pages

CNS Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

KG Reddy College of Engineering & Technology

(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)


Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING

CNS WORKSHOP LABORATORY MANUAL

Subject Code : CS407PC


Regulation : R18/JNTUH
Academic Year : 2020-2021

IV B. TECH I SEMESTER

COMPUTER SCIENCE AND ENGINEERING


KG REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
Affiliated o JNTUH, Chilkur,(V), Moinabad(M) R. R Dist, TS-501504
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


VISION AND MISSION OF THE INSTITUTION
VISION
To become self-sustainable institution this is recognized for its new age engineering through innovative
teaching and learning culture, inculcating research and entrepreneurial ecosystem, and sustainable social
impact in the community.
MISSION
To offer undergraduate and post-graduate programs that is supported through industry relevant curriculum
and innovative teaching and learning processes that would help students succeed in their professional
careers.
To provide necessary support structures for students, this will contribute to their personal and professional
growth and enable them to become leaders in their respective fields.
To provide faculty and students with an ecosystem that fosters research and development through strategic
partnerships with government organisations and collaboration with industries.
To contribute to the development of the region by using our technological expertise to work with nearby
communities and support them in their social and economic growth.

VISION AND MISSION OF CSE DEPARTMENT


VISION
To be recognized as a department of excellence by stimulating a learning environment in which students and
faculty will thrive and grow to achieve their professional, institutional and societal goals.
MISSION
To provide high quality technical education to students that will enable life-long learning and build
expertise in advanced technologies in Computer Science and Engineering.
To promote research and development by providing opportunities to solve complex engineering
problems in collaboration with industry and government agencies.
To encourage professional development of students that will inculcate ethical values and
leadership skills while working with the community to address societal issues.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM EDUCATIONAL OBJECTIVES (PEOS):


A graduate of the Computer Science and Engineering Program should:
Program Educational Objective1: (PEO1)
PEO1 The Graduates will provide solutions to difficult and challenging issues in their professionby
applying computer science and engineering theory and principles.

Program Educational Objective2 :( PEO2)


PEO2 The Graduates have successful careers in computer science and engineering fields or will beable to
successfully pursue advanced degrees.
Program Educational Objective3: (PEO3)
PEO3 The Graduates will communicate effectively, work collaboratively and exhibit high levels of
Professionalism, moral and ethical responsibility.
Program Educational Objective4 :( PEO4)
PEO4 The Graduates will develop the ability to understand and analyse Engineering issues in a
broader perspective with ethical responsibility towards sustainable development.

PROGRAM OUTCOMES (POS):

Engineeringknowledge:Applytheknowledgeofmathematics,science,engineering Fundamentals
PO1
andanengineeringspecializationtothesolutionofcomplexengineeringproblems.
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems anddesign
system components or processes that meet the specified needs with appropriate consideration
PO3
for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assesssocietal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering Solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and needfor sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities andnorms
PO8
of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leaderIn diverse
PO9
teams, and in multi-disciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write
PO10
effective reports and design documentation, make effective presentations, and give and receiveclear
instructions.
Project management and finance: Demonstrate knowledge and understanding of the Engineering
PO11 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.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES(PSOS):

Problem Solving Skills – Graduate will be able to apply computational techniques and software
PSO1
principles to solve complex engineering problems pertaining to software engineering.
Professional Skills – Graduate will be able to think critically, communicate effectively, and
PSO2
collaborate in teams through participation in co and extra-curricular activities.
Successful Career – Graduates will possess a solid foundation in computer science and
PSO3 engineering that will enable them to grow in their profession and pursue lifelong learning
through post-graduation and professional development.

COMPUTERSCIENCE&ENGINEERING
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

INDEX
S.NO. TOPIC PAGE NUMBER

Write a C program that contains a string (char pointer) with avalue


1 \HelloWorld’. Theprogram should XOR each characterinthis stringwith0and 1
displaysthe result.

Write a C program that contains a string (char pointer) with


2 avalue\HelloWorld’. The program should AND or and 2
XOReachcharacterinthis stringwith127and display theresult

WriteaJavaprogramtoperformencryptionanddecryption
usingthefollowingalgorithms:
3 3-9
a) CeaserCipher
b) SubstitutionCipher
c) HillCipher
4 WriteaJavaprogramtoimplementtheDESalgorithmlogic 10-12

WriteaC/JAVAprogramtoimplementtheBlowFishalgorithmlogic
5 13-14

WriteaC/JAVAprogramtoimplementtheRijndaelalgorithmlogic.
6 15

UsingJavaCryptography,encryptthetext“Helloworld”usingBlowFish.Createyourow
7 nkeyusingJavakeytool. 17-18

8 WriteaJavaprogramtoimplementRSAAlgoithm 19

ImplementtheDiffie-HellmanKeyExchangemechanism
using HTML andJ avaScript. Consider the end user as
9 oneoftheparties(Alice)andtheJ avaScriptapplicationasotherparty 21-22
(bob).

CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA.
10 23-24

CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA.
11 25-26

COMPUTERSCIENCE&ENGINEERING
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

1. XORastringwithaZero
AIM: Write a C programthatcontainsastring(charpointer)withavalue
\Hello
World’.TheprogramshouldXOReachcharacterinthisstringwith0anddisplay theresult.

PROGRAM:
#include<stdlib.h>main()
{
charstr[]="HelloWorld";charstr1[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
HelloWorldHelloWorld

COMPUTERSCIENCE&ENGINEERING
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

2. XORastringwitha127
Aim:
Implement a program that contains a string with the value "HelloWorld". The program should
AND and XOR each character in this string with 127 and display the result.

PROGRAM:
#include <stdio.h>

int main() {
char *str = "HelloWorld";
char and_result[11]; // Array to store the AND result
char xor_result[11]; // Array to store the XOR result
int i;

// AND each character with 127 and store in and_result


for (i = 0; str[i] != '\0'; i++) {
and_result[i] = str[i] & 127;
}
and_result[i] = '\0'; // Null-terminate the AND result string

// XOR each character with 127 and store in xor_result


for (i = 0; str[i] != '\0'; i++) {
xor_result[i] = str[i] ^ 127;
}
xor_result[i] = '\0'; // Null-terminate the XOR result string

// Display the results


printf("Original string: %s\n", str);
printf("Resulting string after AND with 127: %s\n", and_result);
printf("Resulting string after XOR with 127: %s\n", xor_result);

return 0;
}

OUTPUT:
Original string: HelloWorld
Resulting string after AND with 127: HelloWorld
Resulting string after XOR with 127: 7S{{{9^{{
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

3.Implement encryption and decryption using Caesar Cipher,


Substitution Cipher, and Hill Cipher.
A) CAESAR CIPHER

Aim:

Implement encryption and decryption using Caesar Cipher

Program:
public class CaesarCipher {
public static String encrypt(String text, int shift) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isLetter(ch)) {
char base = Character.isLowerCase(ch) ? 'a' : 'A';
ch = (char) ((ch - base + shift) % 26 + base);
}
result.append(ch);
}
return result.toString();
}

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


return encrypt(text, 26 - shift);
}

public static void main(String[] args) {


String text = "HelloWorld";
int shift = 3;
String encrypted = encrypt(text, shift);
String decrypted = decrypt(encrypted, shift);

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


System.out.println("Encrypted text: " + encrypted);
System.out.println("Decrypted text: " + decrypted);
}
}

OUTPUT:
Original text: HelloWorld
Encrypted text: KhoorZruog
Decrypted text: HelloWorld
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

B) SUBSTITUTION CIPHER

AIM:
Implement encryption and decryption using Substitution Cipher

Program:

import java.util.HashMap;
import java.util.Map;

public class SubstitutionCipher {


private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String SUBSTITUTION = "QWERTYUIOPLKJHGFDSAZXCVBNM";

public static String encrypt(String text) {


text = text.toUpperCase();
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
int index = ALPHABET.indexOf(ch);
if (index != -1) {
result.append(SUBSTITUTION.charAt(index));
} else {
result.append(ch);
}
}
return result.toString();
}

public static String decrypt(String text) {


text = text.toUpperCase();
Map<Character, Character> substitutionMap = new HashMap<>();
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

for (int i = 0; i < ALPHABET.length(); i++) {


substitutionMap.put(SUBSTITUTION.charAt(i), ALPHABET.charAt(i));
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
result.append(substitutionMap.getOrDefault(ch, ch));
}
return result.toString();
}

public static void main(String[] args) {


String text = "HelloWorld";
String encrypted = encrypt(text);
String decrypted = decrypt(encrypted);

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


System.out.println("Encrypted text: " + encrypted);
System.out.println("Decrypted text: " + decrypted);
}
}

OUTPUT:

Original text: HelloWorld


Encrypted text: ITKKGVGSKR
Decrypted text: HELLOWORLD

=== Code Execution Successful ===


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

C) HILL CIPHER

AIM:
Implement encryption and decryption using Hill Cipher.
Program:
import java.util.Scanner;
public class HillCipher {
private static int[][] keyMatrix;
private static int[] messageVector;
private static int[] cipherMatrix;
public static void main(String[] args) {
String message = "HELLOX"; // Adjusted to ensure length is divisible by 3
String key = "GYBNQKURP"; // 3x3 key matrix for simplicity
encrypt(message, key);
}
public static void encrypt(String message, String key) {
getKeyMatrix(key);
int messageLength = message.length();
messageVector = new int[3];
cipherMatrix = new int[3];
for (int i = 0; i < messageLength; i += 3) {
for (int j = 0; j < 3; j++) {
messageVector[j] = message.charAt(i + j) % 65;
}
for (int x = 0; x < 3; x++) {
cipherMatrix[x] = 0;
for (int y = 0; y < 3; y++) {
cipherMatrix[x] += keyMatrix[x][y] * messageVector[y];
}
cipherMatrix[x] = cipherMatrix[x] % 26;
}

for (int z = 0; z < 3; z++) {


System.out.print((char) (cipherMatrix[z] + 65));
}
}
}
public static void getKeyMatrix(String key) {
keyMatrix = new int[3][3];
int k = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
keyMatrix[i][j] = key.charAt(k) % 65;
k++;
}
}
}
}
OUTPUT:
Encrypted text: TFJJZX
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

4. Data Encryption Standard (DES) Algorithm

Aim:
Implement the DES algorithm logic for encryption and decryption.

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

public class DESExample {


public static void main(String[] args) throws Exception {
// Generate a key for DES algorithm
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56); // DES uses a 56-bit key
SecretKey secretKey = keyGenerator.generateKey();

// Convert the secret key to a readable format


String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("Secret Key: " + encodedKey);

// Define a sample text for encryption


String plainText = "HelloWorld";

// Encrypt the text


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the text


String decryptedText = decrypt(encryptedText, secretKey);
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

System.out.println("Decrypted Text: " + decryptedText);


}

public static String encrypt(String plainText, SecretKey key) throws Exception {


// Create a DES cipher object
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Perform the encryption


byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText, SecretKey key) throws Exception {


// Create a DES cipher object
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);

// Perform the decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);

}
}

OUTPUT:
Secret Key: iRb9Yg6z2cI=
Encrypted Text: y7upedUDmcCdcAcflOo1hw==
Decrypted Text: HelloWorld
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

5. Blowfish Algorithm

Aim:
Implement the Blowfish algorithm logic for encryption and decryption.

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

public class BlowfishExample {


public static void main(String[] args) throws Exception {
// Generate a key for Blowfish algorithm
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); // Blowfish can use a key size from 32 to 448 bits
SecretKey secretKey = keyGenerator.generateKey();

// Convert the secret key to a readable format


String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("Secret Key: " + encodedKey);

// Define a sample text for encryption


String plainText = "HelloWorld";

// Encrypt the text


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the text


String decryptedText = decrypt(encryptedText, secretKey);
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

System.out.println("Decrypted Text: " + decryptedText);


}

public static String encrypt(String plainText, SecretKey key) throws Exception {


// Create a Blowfish cipher object
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Perform the encryption


byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText, SecretKey key) throws Exception {


// Create a Blowfish cipher object
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, key);

// Perform the decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}

OUTPUT:
Secret Key: e+cnAkI85Cu1/IHs2j7lOQ==
Encrypted Text: 1far+lVYKo25ZZDANd8j1w==
Decrypted Text: HelloWorld

=== Code Execution Successful ===


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

6. Rijndael algorithm
Aim:
Implement the Rijndael (AES) algorithm logic for encryption and decryption.

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

public class AESExample {


public static void main(String[] args) throws Exception {
// Generate a key for AES algorithm
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // AES uses a key size of 128, 192, or 256 bits
SecretKey secretKey = keyGenerator.generateKey();

// Convert the secret key to a readable format


String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("Secret Key: " + encodedKey);

// Define a sample text for encryption


String plainText = "HelloWorld";

// Encrypt the text


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the text


String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text: " + decryptedText);
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

public static String encrypt(String plainText, SecretKey key) throws Exception {


// Create an AES cipher object
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Perform the encryption


byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText, SecretKey key) throws Exception {


// Create an AES cipher object
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);

// Perform the decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}

OUTPUT:
Secret Key: Z8F8FAOWyW7J3iQmiJ3DxQ==
Encrypted Text: Z4ANZUMyG37UFoFOJC1VOQ==
Decrypted Text: HelloWorld

=== Code Execution Successful ===


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

7. Generate a Blowfish Key Using keytool

Aim:
To encrypt the text "HelloWorld" using Blowfish in Java, and to create your own key using the Java
keytool

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

public class BlowfishEncryption {


public static void main(String[] args) throws Exception {
// Generate a key for Blowfish algorithm
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); // Blowfish can use a key size from 32 to 448 bits
SecretKey secretKey = keyGenerator.generateKey();

// Convert the secret key to a readable format


String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("Secret Key: " + encodedKey);

// Define a sample text for encryption


String plainText = "HelloWorld";

// Encrypt the text


String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the text


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

String decryptedText = decrypt(encryptedText, secretKey);


System.out.println("Decrypted Text: " + decryptedText);
}

public static String encrypt(String plainText, SecretKey key) throws Exception {


// Create a Blowfish cipher object
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Perform the encryption


byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText, SecretKey key) throws Exception {


// Create a Blowfish cipher object
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, key);

// Perform the decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}

OUTPUT:
Secret Key: (varies each time the program runs)
Encrypted Text: (varies each time the program runs)
Decrypted Text: HelloWorld
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

8. RSA (Rivest-Shamir-Adleman) Algorithm


Aim:
Implement the RSA algorithm logic for encryption and decryption.

Program:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
import java.util.Base64;

public class RSAExample {


public static void main(String[] args) throws Exception {
// Generate RSA KeyPair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // RSA key size can be 512, 1024, or 2048 bits
KeyPair keyPair = keyPairGenerator.generateKeyPair();

PublicKey publicKey = keyPair.getPublic();


PrivateKey privateKey = keyPair.getPrivate();

// Define a sample text for encryption


String plainText = "HelloWorld";

// Encrypt the text


String encryptedText = encrypt(plainText, publicKey);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the text


String decryptedText = decrypt(encryptedText, privateKey);
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

System.out.println("Decrypted Text: " + decryptedText);


}

public static String encrypt(String plainText, PublicKey publicKey) throws Exception {


// Create an RSA cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

// Perform the encryption


byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {


// Create an RSA cipher object
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);

// Perform the decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
}
}

OUTPUT:
Encrypted Text: (varies each time the program runs)
Decrypted Text: HelloWorld
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

9. Diffie-Hellman Key Exchange


Aim:
Implement the Diffie-Hellman key exchange mechanism using HTML and JavaScript.

Program:
Create an HTML file (e.g., index.html) with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<script>
// Function to generate a random number within a range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Function to calculate modular exponentiation (base^exp % mod)
function modExp(base, exp, mod) {
let result = 1;
while (exp > 0) {
if (exp % 2 === 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp = Math.floor(exp / 2);
}
return result;
}
// Generate Bob's private and public keys
function generateBobKeys() {
const p = 23; // Prime number
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

const g = 5; // Primitive root modulo p


const b = getRandomNumber(1, p - 1); // Bob's private key
const B = modExp(g, b, p); // Bob's public key
return { p, g, b, B };
}
// Compute shared secret key
function computeSharedKey(publicKey, privateKey, p) {
return modExp(publicKey, privateKey, p);
}

// Handle Alice's key generation


function generateAliceKeys() {
const p = 23; // Prime number
const g = 5; // Primitive root modulo p
const a = getRandomNumber(1, p - 1); // Alice's private key
const A = modExp(g, a, p); // Alice's public key
// Simulate communication with Bob's public key
const bobPublicKey = document.getElementById('bobPublicKey').value;
const sharedSecretKeyAlice = computeSharedKey(bobPublicKey, a, p);
// Compute Bob's shared secret key
const bobKeys = generateBobKeys();
const sharedSecretKeyBob = computeSharedKey(A, bobKeys.b, p);
// Display results
document.getElementById('alicePublicKey').innerText = A;
document.getElementById('alicePrivateKey').innerText = a;
document.getElementById('sharedSecretKey').innerText = sharedSecretKeyAlice;
document.getElementById('bobPublicKey').value = bobKeys.B;
document.getElementById('bobPrivateKey').innerText = bobKeys.b;
document.getElementById('bobSharedSecretKey').innerText = sharedSecretKeyBob;
}
</script>
</head>
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

<body>
<h1>Diffie-Hellman Key Exchange</h1>
<p>Enter Bob's public key:</p>
<input type="text" id="bobPublicKey" placeholder="Enter Bob's public key" />
<button onclick="generateAliceKeys()">Generate Alice's Keys and Shared Secret</button>
<h2>Alice's Key:</h2>
<p>Public Key: <span id="alicePublicKey"></span></p>
<p>Private Key: <span id="alicePrivateKey"></span></p>
<p>Shared Secret Key: <span id="sharedSecretKey"></span></p>
<h2>Bob's Key:</h2>
<p>Public Key: <span id="bobPublicKey"></span></p>
<p>Private Key: <span id="bobPrivateKey"></span></p>
<p>Shared Secret Key: <span id="bobSharedSecretKey"></span></p>
</body>
</html>

OUTPUT:

<h1>Diffie-Hellman Key Exchange</h1>


<p>Enter Bob's public key:</p>
<input type="text" id="bobPublicKey" placeholder="Enter Bob's public key" value="8" />
<button onclick="generateAliceKeys()">Generate Alice's Keys and Shared Secret</button>
<h2>Alice's Key:</h2>
<p>Public Key: <span id="alicePublicKey">2</span></p>
<p>Private Key: <span id="alicePrivateKey">6</span></p>
<p>Shared Secret Key: <span id="sharedSecretKey">16</span></p>
<h2>Bob's Key:</h2>
<p>Public Key: <span id="bobPublicKey">8</span></p>
<p>Private Key: <span id="bobPrivateKey">4</span></p>
<p>Shared Secret Key: <span id="bobSharedSecretKey">16</span></p>
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

10. SHA-1 algorithm

Aim:
Calculate the message digest of a text using the SHA-1 algorithm in Java.

Program:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1Example {


public static void main(String[] args) {
try {
// Text to be hashed
String text = "HelloWorld";

// Get an instance of the SHA-1 MessageDigest


MessageDigest digest = MessageDigest.getInstance("SHA-1");

// Perform the hashing


byte[] hashBytes = digest.digest(text.getBytes());

// Convert the byte array to a hexadecimal string


StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}

// Output the result


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

System.out.println("Original Text: " + text);


System.out.println("SHA-1 Digest: " + hexString.toString());
} catch (NoSuchAlgorithmException e) {
System.err.println("SHA-1 algorithm not found.");
}
}
}

OUTPUT:
Original Text: HelloWorld
SHA-1 Digest: d3486ae9136e7856bc42212385ea7970944758
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

11. SHA-1 and MD5 algorithms


Aim:
Calculate the message digest of a text using SHA-1 and MD5 algorithms in Java.

Program:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MessageDigestExample {


public static void main(String[] args) {
try {
// Text to be hashed
String text = "HelloWorld";

// Compute SHA-1 Digest


String sha1Digest = computeDigest(text, "SHA-1");
System.out.println("SHA-1 Digest: " + sha1Digest);

// Compute MD5 Digest


String md5Digest = computeDigest(text, "MD5");
System.out.println("MD5 Digest: " + md5Digest);

} catch (NoSuchAlgorithmException e) {
System.err.println("Algorithm not found.");
}
}

private static String computeDigest(String text, String algorithm) throws


NoSuchAlgorithmException {
// Get an instance of the MessageDigest for the given algorithm
MessageDigest digest = MessageDigest.getInstance(algorithm);
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

// Perform the hashing


byte[] hashBytes = digest.digest(text.getBytes());

// Convert the byte array to a hexadecimal string


StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}

return hexString.toString();
}
}

OUTPUT:
SHA-1 Digest: db8ac1c259eb89d4a131b253bacfca5f319d54f2
MD5 Digest: 68e109f0f40ca72a15e05cc22786f8e6

=== Code Execution Successful ===


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accredited by NAAC

You might also like