0% found this document useful (0 votes)
2 views10 pages

CryptolabDA 4

The document outlines a series of lab exercises for a Cryptography and Network Security course, including the implementation of Digital Signature Standard (DSS), SSL socket communication, and SSH client-server models. It also covers the development of a web application using JSON Web Tokens (JWT) for authentication. Each exercise includes code snippets and aims to demonstrate key concepts in network security and cryptography.

Uploaded by

Tanay Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

CryptolabDA 4

The document outlines a series of lab exercises for a Cryptography and Network Security course, including the implementation of Digital Signature Standard (DSS), SSL socket communication, and SSH client-server models. It also covers the development of a web application using JSON Web Tokens (JWT) for authentication. Each exercise includes code snippets and aims to demonstrate key concepts in network security and cryptography.

Uploaded by

Tanay Saxena
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Semester: Summer 2024-25 (L11+L12+L41+L42)

Couse Code: BCSE309P Cryptography and


Network Security Lab (Lab)

Name: Tanay Saxena Registration No:


22BDS0049

Lab Assessment 4

Exercise No 7: DSS

Aim: Develop the Digital Signature standard(DSS)for verifying the


legal communicating parties
Code:
import java.util.Scanner;
import java.security.*;
import java.util.Base64;

public class DSS{

public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {


KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(2048);
return keyGen.generateKeyPair();
}

public static byte[] signMessage(String message, PrivateKey privateKey) throws Exception {


Signature signer = Signature.getInstance("SHA256withDSA");
signer.initSign(privateKey);
signer.update(message.getBytes("UTF-8"));
return signer.sign();
}

public static boolean verifySignature(String message, byte[] signatureBytes, PublicKey publicKey) throws Exception {
Signature verifier = Signature.getInstance("SHA256withDSA");
verifier.initVerify(publicKey);
verifier.update(message.getBytes("UTF-8"));
return verifier.verify(signatureBytes);
}

public static void main(String[] args) {


try {
KeyPair keyPair = generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

String message = "Confidential legal agreement between Party A and Party B.";
byte[] digitalSignature = signMessage(message, privateKey);

String signatureBase64 = Base64.getEncoder().encodeToString(digitalSignature);


System.out.println("Original Message: " + message);
System.out.println("Digital Signature (Base64): " + signatureBase64);

boolean isVerified = verifySignature(message, digitalSignature, publicKey);


System.out.println("Signature Verified: " + isVerified);

} catch (Exception e) {
e.printStackTrace();
}
}
}

Submission on Moodle:

Output:
Exercise No 8: SSL socket communication
Aim: Develop a simple client and server application using SSL
socket communication
Code:

// SSLClient.java
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;

public class SSLClient {


public static void main(String[] args) throws Exception {
char[] password = "Password".toCharArray();
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("keystore.jks"), password);

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");


tmf.init(trustStore);

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tmf.getTrustManagers(), null);

SSLSocketFactory factory = sc.getSocketFactory();


SSLSocket socket = (SSLSocket) factory.createSocket("localhost", 8443);

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));


PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

writer.println("Hello from SSL Client!");


String response = reader.readLine();
System.out.println("Server replied: " + response);

socket.close();
}
}

// SSLServer.java
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;

public class SSLServer {


public static void main(String[] args) throws Exception {
char[] password = "Password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("keystore.jks"), password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(8443);
System.out.println("Server started. Waiting for client...");
SSLSocket socket = (SSLSocket) serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

String msg = reader.readLine();


System.out.println("Client says: " + msg);
writer.println("Hello from SSL Server!");
socket.close();
serverSocket.close();
}
}

Submission on Moodle:
Output:
Exercise No 9: SSH

Aim: Develop a simple client server model using telnet and capture
the packets transmitted with tshark Analyze the pcap file and get
the transmitted data (plain text) using any packet capturing library.
Implement the above scenario using SSH and observe the data

Code:

// PlainTextServer.java
import java.io.*;
import java.net.*;

public class PlainTextServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started on port 8080. Waiting for clients...");

Socket clientSocket = serverSocket.accept();


BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("Echo: " + inputLine);
}

in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}

// PlainTextClient.java
import java.io.*;
import java.net.*;

public class PlainTextClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String line;
while ((line = userInput.readLine()) != null) {
out.println(line);
System.out.println("Server: " + in.readLine());
}

socket.close();
}
}

Submission on Moodle:

Output:
Exercise No 10: JSON

Aim: Develop a web application that implements JSON web token

Code:

// JwtLoginServlet.java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Date;

@WebServlet("/login")
public class JwtLoginServlet extends HttpServlet {

private static final String SECRET_KEY = "supersecretkey123";


private static final long EXPIRATION_TIME = 86400000; // 24 hours

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String username = request.getParameter("username");


String password = request.getParameter("password");

if ("admin".equals(username) && "admin123".equals(password)) {


String jwt = Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();

response.setContentType("application/json");
response.getWriter().write("{\"token\": \"" + jwt + "\"}");
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Invalid credentials");
}
}
}

//ProtectedServlet.java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/protected")
public class ProtectedServlet extends HttpServlet {
private static final String SECRET_KEY = "supersecretkey123";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
try {
Claims claims = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();

String user = claims.getSubject();


response.setContentType("text/plain");
response.getWriter().write("Hello, " + user + "! Access to protected resource granted.");
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("Invalid or expired token");
}
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write("Missing Authorization header");
}
}
}
Submission on Moodle:

Output:

You might also like