0% found this document useful (0 votes)
9 views

Cns Record

The document is a certification from JagarlaMudi Kuppuswamy Choudary College for a student in the MCA III Semester, confirming the completion of ten experiments in Cryptography and Network Security Lab. It includes various programming tasks such as implementing encryption and decryption algorithms like Ceaser Cipher, Substitution Cipher, DES, RSA, and others. The document also contains sample Java code for these algorithms.

Uploaded by

Brahmam Kolli
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)
9 views

Cns Record

The document is a certification from JagarlaMudi Kuppuswamy Choudary College for a student in the MCA III Semester, confirming the completion of ten experiments in Cryptography and Network Security Lab. It includes various programming tasks such as implementing encryption and decryption algorithms like Ceaser Cipher, Substitution Cipher, DES, RSA, and others. The document also contains sample Java code for these algorithms.

Uploaded by

Brahmam Kolli
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/ 45

JAGARLAMUDI KUPPUSWAMY CHOUDARY COLLEGE (AUTONOMOUS)

(Accredited at ‘A’ level by NAAC)


JKC Nagar ,Guntur-522006.

DEPARTMENT OF MCA

CERTIFICATE

This is to certify that Mr./ Kum/ Smt_____________________________________

of MCA III Semester class has successfully completed TEN experiments

in CRYPTOGRAPHY AND NETWORK SECURITY LAB under my supervision

during the ODD SEMESTER OF ACADEMIC YEAR 2024-25.

Lecturer in-Charge Head of the Department

External Examiner
CRYPTOGRAPHY AND NETWORK SECURITY

Cryptography and Network Security LAB

1. Write a Java program to perform encryption and decryption using the following

algorithms:

a) Ceaser Cipher b) Substitution Cipher c) Hill Cipher

2. Write a Java program to implement the DES algorithm logic.

3. Write a Java program to implement RSA Algorithm.

4. Write a C/JAVA program to implement the Rail fence technique.

5. Write a C/JAVA program to implement the Vernan cipher technique.

6. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

7. Write a program to implement digital signature.

8. Compute common secret key between client and server using Diffie-Hellman key
exchange technique. Perform encryption and decryption of message using the shared
secret key (Use simple XOR operation to encrypt and decrypt the message).

9. Implement DSS algorithm for signing and verification of messages between two
parties (obtain H (M) using simple XOR method of hash computation on M).

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

. Write a Java program to perform encryption and decryption using the following algorithms:

a) Ceaser Cipher

package Crypto;

import static java.lang.Character.*;

import javax.swing.*;

import static java.lang.System.*;

class Caesar {

int key;

Caesar(int k)

key=k;

String encrypt(String s)

int i=0;

StringBuffer ct = new StringBuffer(s.length());

s=s.toUpperCase();

for(i=0;i<s.length();i++)

if(Character.isLetter(s.charAt(i)))ct.append((char)((((s.charAt(i)-'A')+key)%26)+'A'));

else

ct.append(s.charAt(i));

return ct.toString();

String decrypt(String s)

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

int i=0;

StringBuffer pt = new StringBuffer(s.length());

s=s.toUpperCase();

for(i=0;i<s.length();i++)

if(Character.isLetter(s.charAt(i)))pt.append((char)((((s.charAt(i)-'A')-
key+26)%26)+'A'));

else

pt.append(s.charAt(i));

return pt.toString();

public static void main(String[] args){

Caesar c=new Caesar(3);

String pt= JOptionPane.showInputDialog(null,"give plaintext");

String ct = c.encrypt(pt);

JOptionPane.showMessageDialog(null,ct.toString(),"Ciphertext",JOptionPane.PLAIN_ME
SSAGE);

String pt1 = c.decrypt(ct);

JOptionPane.showMessageDialog(null,pt1.toString(),"decryptedtext",JOptionPane.PLAIN
_MESSAGE);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

b) Substitution Cipher
package Crypto;

import javax.swing.*;

class SubstitutionCipher {

static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

String key;

SubstitutionCipher(String k) {

key = k.toUpperCase();

String encrypt(String plaintext) {

plaintext = plaintext.toUpperCase();

StringBuilder ciphertext = new StringBuilder();

for (char c : plaintext.toCharArray()) {

if (Character.isLetter(c)) {

int index = ALPHABET.indexOf(c);

ciphertext.append(key.charAt(index));

} else {

ciphertext.append(c);

return ciphertext.toString();

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

String decrypt(String ciphertext) {

ciphertext = ciphertext.toUpperCase();

StringBuilder plaintext = new StringBuilder();

for (char c : ciphertext.toCharArray()) {

if (Character.isLetter(c)) {

int index = key.indexOf(c);

plaintext.append(ALPHABET.charAt(index));

} else {

plaintext.append(c);

return plaintext.toString();

public static void main(String[] args) {

String substitutionKey = JOptionPane.showInputDialog(null, "Enter the Substitution


Cipher Key (26 characters):");

SubstitutionCipher sc = new SubstitutionCipher(substitutionKey);

String pt = JOptionPane.showInputDialog(null, "Enter Plaintext:");

String ct = sc.encrypt(pt);

JOptionPane.showMessageDialog(null, "Ciphertext: " + ct, "Encryption Result",


JOptionPane.PLAIN_MESSAGE);

String decryptedText = sc.decrypt(ct);

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText,


"Decryption Result", JOptionPane.PLAIN_MESSAGE);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

c) Hill Cipher
package Crypto;
import javax.swing.*;
public class HillCipher {
private static final int MATRIX_SIZE = 2; // Using a 2x2 matrix for encryption
// Method to multiply key matrix with the message vector
public static int[] multiplyMatrix(int[][] keyMatrix, int[] messageVector) {
int[] result = new int[MATRIX_SIZE]; // Resultant vector after multiplication
for (int i = 0; i < MATRIX_SIZE; i++) {
result[i] = 0;
for (int j = 0; j < MATRIX_SIZE; j++) {
result[i] += keyMatrix[i][j] * messageVector[j];
}
result[i] %= 26; // Modulo 26 ensures result stays within A-Z
}
return result;
}

// Method to encrypt the plaintext using the Hill Cipher


public static String encrypt(String plaintext, int[][] keyMatrix) {
// Ensure the plaintext length is a multiple of the MATRIX_SIZE
int length = plaintext.length();
while (length % MATRIX_SIZE != 0) {
plaintext += 'X'; // Pad with 'X' if necessary
length++;
}
StringBuilder encryptedText = new StringBuilder();
// Process plaintext in chunks of size MATRIX_SIZE
for (int i = 0; i < length; i += MATRIX_SIZE) {
int[] messageVector = new int[MATRIX_SIZE];

// Convert plaintext characters to numeric values (A=0, B=1, ..., Z=25)


for (int j = 0; j < MATRIX_SIZE; j++) {
messageVector[j] = plaintext.charAt(i + j) - 'A';
}
// Multiply the message vector with the key matrix
int[] encryptedVector = multiplyMatrix(keyMatrix, messageVector);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

// Convert encrypted values back to characters


for (int value : encryptedVector) {
encryptedText.append((char) (value + 'A'));
}
}
return encryptedText.toString();
}
public static void main(String[] args) {
try {
// Prompt user for plaintext input
String plaintext = JOptionPane.showInputDialog(null, "Enter plaintext (UPPERCASE
only):");
// Validate plaintext
if (plaintext == null || plaintext.isEmpty()) {
JOptionPane.showMessageDialog(null, "Plaintext cannot be empty!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// Ensure plaintext is in uppercase
plaintext = plaintext.toUpperCase();
// Define the 2x2 key matrix (example matrix)
int[][] keyMatrix = {
{6, 24},
{1, 16}
};
// Encrypt the plaintext using the Hill Cipher
String encryptedText = encrypt(plaintext, keyMatrix);

// Display the encrypted text


JOptionPane.showMessageDialog(null, "Encrypted Text: " + encryptedText, "Hill
Cipher", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

. Write a Java program to implement the DES algorithm logic.

package Crypto;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.swing.*;

public class SimpleDES {

public static void main(String[] args) {

try {

// Generate a DES key

KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");

SecretKey secretKey = keyGenerator.generateKey();

// Create a Cipher instance for DES

Cipher cipher = Cipher.getInstance("DES");

// Input plaintext from the user

String plaintext = JOptionPane.showInputDialog(null, "Enter plaintext:");

if (plaintext == null || plaintext.isEmpty()) {

JOptionPane.showMessageDialog(null, "Plaintext cannot be empty!", "Error",


JOptionPane.ERROR_MESSAGE);

return;

// Encrypt the plaintext

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());

String encryptedText = bytesToHex(encryptedBytes);

// Convert to a readable hex format

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

// Show the encrypted text

JOptionPane.showMessageDialog(null, "Encrypted Text: " + encryptedText, "DES


Encryption", JOptionPane.PLAIN_MESSAGE);

// Decrypt the ciphertext

cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

String decryptedText = new String(decryptedBytes);

// Show the decrypted text

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText, "DES


Decryption", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

// Utility method to convert byte array to hexadecimal string

private static String bytesToHex(byte[] bytes) {

StringBuilder hexString = new StringBuilder();

for (byte b : bytes) {

String hex = Integer.toHexString(0xFF & b);

if (hex.length() == 1) {

hexString.append('0');

hexString.append(hex);

return hexString.toString();

} }

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

. Write a Java program to implement RSA Algorithm.


package Crypto;

import javax.swing.*;

import java.math.BigInteger;

import java.security.SecureRandom;

class RSA {

private BigInteger n, d, e;

private int bitlength = 1024;

// Constructor to generate public and private keys

public RSA() {

SecureRandom random = new SecureRandom();

BigInteger p = BigInteger.probablePrime(bitlength / 2, random);

BigInteger q = BigInteger.probablePrime(bitlength / 2, random);

n = p.multiply(q);

BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));

e = BigInteger.valueOf(65537); // Common value for e

d = e.modInverse(phi);

// Encrypt a message

public String encrypt(String message) {

return (new BigInteger(message.getBytes())).modPow(e, n).toString();

// Decrypt the message

public String decrypt(String ciphertext) {

return new String((new BigInteger(ciphertext)).modPow(d, n).toByteArray()); }

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

// Format text to split long strings into manageable chunks

public static String formatText(String text, int chunkSize) {

StringBuilder formattedText = new StringBuilder();

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

int end = Math.min(i + chunkSize, text.length());

formattedText.append(text, i, end).append("\n");

return formattedText.toString();

public static void main(String[] args) {

try {

RSA rsa = new RSA();

String plaintext = JOptionPane.showInputDialog(null, "Enter plaintext to encrypt:");

// Encrypt the message

String encryptedText = rsa.encrypt(plaintext);

String formattedEncryptedText = formatText(encryptedText, 50); // Split into 50-


character lines

JOptionPane.showMessageDialog(null, "Encrypted Text:\n" +


formattedEncryptedText, "RSA Encryption", JOptionPane.PLAIN_MESSAGE);

// Decrypt the message

String decryptedText = rsa.decrypt(encryptedText);

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText, "RSA


Decryption", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

} } }

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Write a C/JAVA program to implement the Rail fence technique.


package Crypto;

import javax.swing.*;

class RailFenceCipher {

int key;

RailFenceCipher(int k) {

key = k;

String encrypt(String plaintext) {

plaintext = plaintext.replaceAll(" ", "");

char[][] rail = new char[key][plaintext.length()];

for (int i = 0; i < key; i++) {

for (int j = 0; j < plaintext.length(); j++) {

rail[i][j] = '\n';

} }

boolean dirDown = false;

int row = 0, col = 0;

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

if (row == 0 || row == key - 1)

dirDown = !dirDown;

rail[row][col++] = plaintext.charAt(i);

row = dirDown ? row + 1 : row - 1;

StringBuilder ciphertext = new StringBuilder();

for (int i = 0; i < key; i++) {

for (int j = 0; j < plaintext.length(); j++) {

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

if (rail[i][j] != '\n') {

ciphertext.append(rail[i][j]);

} }

return ciphertext.toString();

String decrypt(String ciphertext) {

char[][] rail = new char[key][ciphertext.length()];

for (int i = 0; i < key; i++) {

for (int j = 0; j < ciphertext.length(); j++) {

rail[i][j] = '\n';

boolean dirDown = false;

int row = 0, col = 0;

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

if (row == 0 || row == key - 1)

dirDown = !dirDown;

rail[row][col++] = '*';

row = dirDown ? row + 1 : row - 1;

int index = 0;

for (int i = 0; i < key; i++) {

for (int j = 0; j < ciphertext.length(); j++) {

if (rail[i][j] == '*' && index < ciphertext.length()) {

rail[i][j] = ciphertext.charAt(index++);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

} }

StringBuilder plaintext = new StringBuilder();

row = 0;

col = 0;

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

if (row == 0 || row == key - 1)

dirDown = !dirDown;

if (rail[row][col] != '\n') {

plaintext.append(rail[row][col++]);

row = dirDown ? row + 1 : row - 1;

return plaintext.toString();

public static void main(String[] args) {

int key = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number of


Rails:"));

RailFenceCipher rf = new RailFenceCipher(key);

String pt = JOptionPane.showInputDialog(null, "Enter Plaintext:");

String ct = rf.encrypt(pt);

JOptionPane.showMessageDialog(null, "Ciphertext: " + ct, "Encryption Result",


JOptionPane.PLAIN_MESSAGE);

String decryptedText = rf.decrypt(ct);

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText,


"Decryption Result", JOptionPane.PLAIN_MESSAGE);

} }

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

. Write a C/JAVA program to implement the Vernan cipher technique

package Crypto;

import javax.swing.*;

class VernamCipher {

String encrypt(String plaintext, String key) {

StringBuilder ciphertext = new StringBuilder();

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

char encryptedChar = (char) (plaintext.charAt(i) ^ key.charAt(i));

ciphertext.append(encryptedChar);

return ciphertext.toString();

String decrypt(String ciphertext, String key) {

StringBuilder plaintext = new StringBuilder();

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

char decryptedChar = (char) (ciphertext.charAt(i) ^ key.charAt(i));

plaintext.append(decryptedChar);

return plaintext.toString();

public static void main(String[] args) {

VernamCipher vc = new VernamCipher();

String pt = JOptionPane.showInputDialog(null, "Enter Plaintext:");

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

String key = JOptionPane.showInputDialog(null, "Enter Key (same length as


Plaintext):");

if (key.length() != pt.length()) {

JOptionPane.showMessageDialog(null, "Error: Key length must match Plaintext


length.", "Error", JOptionPane.ERROR_MESSAGE);

return;

String ct = vc.encrypt(pt, key);

JOptionPane.showMessageDialog(null, "Ciphertext: " + ct, "Encryption Result",


JOptionPane.PLAIN_MESSAGE);

String decryptedText = vc.decrypt(ct, key);

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText,


"Decryption Result", JOptionPane.PLAIN_MESSAGE);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Calculate the message digest of a text using the SHA-1 algorithm in java

package Crypto;

import javax.swing.*;

import java.security.MessageDigest;

class SHA1Hash {

public static String getSHA1(String input) throws Exception {

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

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

StringBuilder hexString = new StringBuilder();

for (byte b : hashBytes) {

hexString.append(String.format("%02x", b));

return hexString.toString();

public static void main(String[] args) {

try {

String input = JOptionPane.showInputDialog(null, "Enter the text to hash:");

String sha1Hash = getSHA1(input);

JOptionPane.showMessageDialog(null, "SHA-1 Hash: " + sha1Hash, "Message


Digest (SHA-1)", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Write a program to implement digital signature.


package Crypto;

import javax.swing.*;

import java.security.*;

import java.util.Base64;

class DigitalSignatureExample {

public static String signMessage(String message, PrivateKey privateKey) throws


Exception {

Signature signature = Signature.getInstance("SHA256withRSA");

signature.initSign(privateKey);

signature.update(message.getBytes());

byte[] signatureBytes = signature.sign();

return Base64.getEncoder().encodeToString(signatureBytes);

public static boolean verifySignature(String message, String signatureStr, PublicKey


publicKey) throws Exception {

Signature signature = Signature.getInstance("SHA256withRSA");

signature.initVerify(publicKey);

signature.update(message.getBytes());

byte[] signatureBytes = Base64.getDecoder().decode(signatureStr);

return signature.verify(signatureBytes);

public static String formatSignature(String signature) {

StringBuilder formattedSignature = new StringBuilder();

int chunkSize = 50; // Set chunk size for splitting the signature

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

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

int end = Math.min(i + chunkSize, signature.length());

formattedSignature.append(signature, i, end).append("\n");

return formattedSignature.toString();

public static void main(String[] args) {

try {

String message = JOptionPane.showInputDialog(null, "Enter the message to sign:");

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

keyGen.initialize(2048);

KeyPair keyPair = keyGen.generateKeyPair();

// Sign the message

String signedMessage = signMessage(message, keyPair.getPrivate());

String formattedSignedMessage = formatSignature(signedMessage); // Format the


signature for better display

JOptionPane.showMessageDialog(null, "Signed Message:\n" +


formattedSignedMessage, "Digital Signature", JOptionPane.PLAIN_MESSAGE);

// Verify the signature

boolean isVerified = verifySignature(message, signedMessage, keyPair.getPublic());

JOptionPane.showMessageDialog(null, "Signature Verified: " + isVerified,


"Verification", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

} }

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Compute common secret key between client and server using Diffie-Hellman
key exchange technique. Perform encryption and decryption of message using
the shared secret key (Use simple XOR operation to encrypt and decrypt the
message).
package Crypto;

import javax.swing.*;

import java.math.BigInteger;

import java.security.SecureRandom;

class DiffieHellman {

// XOR Encryption method using the shared key

public static String xorEncryptDecrypt(String text, BigInteger key) {

StringBuilder result = new StringBuilder();

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

result.append((char) (text.charAt(i) ^ key.intValue()));

return result.toString();

public static void main(String[] args) {

try {

// Client and Server agree on public values

BigInteger p = new BigInteger("23"); // Prime number

BigInteger g = new BigInteger("5"); // Primitive root

// Client generates a private key and computes public key

SecureRandom random = new SecureRandom();

BigInteger a = new BigInteger(256, random); // Client's private key

BigInteger A = g.modPow(a, p); // A = g^a % p (Client's public key)

// Server generates a private key and computes public key

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

BigInteger b = new BigInteger(256, random); // Server's private key

BigInteger B = g.modPow(b, p); // B = g^b % p (Server's public key)

// Client and Server compute the shared secret key

BigInteger sharedKeyClient = B.modPow(a, p); // K = B^a % p (Client's shared key)

BigInteger sharedKeyServer = A.modPow(b, p); // K = A^b % p (Server's shared key)

// Both Client and Server now have the same shared key (they can encrypt and
decrypt using this key)

// Displaying the shared key

JOptionPane.showMessageDialog(null, "Shared Secret Key: " +


sharedKeyClient.toString(), "Diffie-Hellman", JOptionPane.PLAIN_MESSAGE);

String plaintext = JOptionPane.showInputDialog(null, "Enter plaintext to encrypt:");

// Encrypting the message

String encryptedText = xorEncryptDecrypt(plaintext, sharedKeyClient);

JOptionPane.showMessageDialog(null, "Encrypted Text: " + encryptedText,


"Encryption", JOptionPane.PLAIN_MESSAGE);

// Decrypting the message using the same shared key

String decryptedText = xorEncryptDecrypt(encryptedText, sharedKeyClient);

JOptionPane.showMessageDialog(null, "Decrypted Text: " + decryptedText,


"Decryption", JOptionPane.PLAIN_MESSAGE);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

OUTPUT

Department of MCA JKC College Guntur


CRYPTOGRAPHY AND NETWORK SECURITY

Implement DSS algorithm for signing and verification of messages between two
parties (obtain H (M) using simple XOR method of hash computation on M).

package Crypto;

import javax.swing.*;

import java.security.*;

class DSS {

public static String getXORHash(String message) {

int hash = 0;

for (char c : message.toCharArray()) {

hash ^= c;

return Integer.toHexString(hash);

public static void main(String[] args) {

try {

String message = JOptionPane.showInputDialog(null, "Enter message to sign:");

String hash = getXORHash(message);

JOptionPane.showMessageDialog(null, "Message Hash: " + hash, "DSS Hash",


JOptionPane.PLAIN_MESSAGE);

// Sign and verify using the hash

// (In reality, DSS uses private/public keys, but this is simplified)

} catch (Exception e) {

JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error",


JOptionPane.ERROR_MESSAGE);

Department of MCA JKC College Guntur

You might also like