K
week-6 RJ'S ALGORITHM
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES {
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
for (int 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="AES still rocks!!";
KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128);
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
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));
} }
RC4 LOGIC
week-7
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;
import java.util.Base64;
public class BlowFish{
public static void main(String[] args) throws Exception {
KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
SecretKey secretkey = keygenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish");
String inputText = JOptionPane.showInputDialog("Input your message: ");
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
byte[] encrypted = cipher.doFinal(inputText.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretkey);
byte[] decrypted = cipher.doFinal(encrypted);
String encryptedBase64 = Base64.getEncoder().encodeToString(encrypted);
JOptionPane.showMessageDialog(
JOptionPane.getRootFrame(),"Encrypted text (Base64): " + encryptedBase64 +"\nDecrypted text: " + new String(decrypted));
System.exit(0);
}
}
RSA ALGORITHM
week-8
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) {
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger();
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger();
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);
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,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;
}}
DIFFE- HELLMAN
week-9
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
{
BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new BigInteger(Integer.toString(XaValue));
BigInteger Xb = new BigInteger(Integer.toString(XbValue));
createKey();
int bitLength = 512;
SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createKey() throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("Public key is: " +kspec);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpec param = new DHParameterSpec(p, g);
kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("\nPublic key is : " +kspec);
}
}
SHA-1 ALGORITHM
week-10
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("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));
}
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> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString(); }
}
MD5 ALGORITHM
week -11
import java.security.*;
public class MD5
{
public static void main(String[] a)
{
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("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println("MD5(\"" +input+"\") = " +bytesToHex(output));
}
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> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString();
}
}
import java.io.*;
import java.net.*;
public class WebPages {
public static void main(String[] args) throws Exception {
URL u = new URL("https://www.mlrit.ac.in");
BufferedReader r=new BufferedReader(new InputStreamReader(u.openStream()));
FileWriter w=new FileWriter("downloaded_page.html");
String line;
while((line=r.readLine())!=null)
w.write(line + "\n");
r.close();
w.close();
System.out.println("Webpage downloaded successfully!");
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
public static void main(String[] args) {
final int PORT = 12345;
final String fileName = "amaan.txt";
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server started. Waiting for a client...");
try (Socket clientSocket = serverSocket.accept()) {
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostName());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(fileName);
FileInputStream fis = new FileInputStream(fileName);
BufferedOutputStream bos = new BufferedOutputStream(clientSocket.getOutputStream());
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
fis.close();
System.out.println("File sent: " + fileName);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) {
final String SERVER_IP = "localhost";
final int PORT = 12345;
String fileName = "amaan.txt";
try (Socket socket = new Socket(SERVER_IP, PORT)) {
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String receivedFileName = in.readLine();
System.out.println("Requested file: " + receivedFileName);
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("received_" + receivedFileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
bos.close();
fos.close();
System.out.println("File received: received_" + receivedFileName);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) {
final int portNumber = 5555;
System.out.println("Echo server started on port " + portNumber);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
) {
System.out.println("Client connected");
String inputLine;
while ((inputLine = in.readLine()) != null) { System.out.println("Received from client: " +
inputLine); out.println(inputLine); // Echo back to client
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}}}
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) {
final String host = "localhost";
final int portNumber = 5555;
try (
Socket echoSocket = new Socket(host, portNumber);
PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))
) {
String userInput;
System.out.println("Enter messages to send to the server (type 'exit' to quit):");
while ((userInput = stdIn.readLine()) != null) {
if ("exit".equalsIgnoreCase(userInput)) {
System.out.println("Exiting...");
break;
}
out.println(userInput);
System.out.println("Server echoed: " + in.readLine());
}
} catch (IOException e) {
System.err.println("IOException caught: " + e.getMessage());
}
}
}
import java.io.*;
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
final int PORT = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(PORT)) {
byte[] receiveData = new byte[1024];
System.out.println("Server started. Listening on port " + PORT);
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Client: " + message);
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
String responseMessage = "Message received successfully!";
byte[] sendData = responseMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
final String SERVER_IP = "localhost";
final int SERVER_PORT = 9876;
try (DatagramSocket clientSocket = new DatagramSocket();
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
InetAddress serverAddress = InetAddress.getByName(SERVER_IP);
while (true) {
System.out.print("Enter message to send to server: ");
String message = userInput.readLine();
byte[] sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, SERVER_PORT);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String responseMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Server: " + responseMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class Chatclient{
private static final String SERVER_IP="127.0.0.1";
private static final int SERVER_PORT=9000;
public static void main(String args[]) throws Exception
{
Socket socket=new Socket(SERVER_IP, SERVER_PORT);
System.out.println("Connected to the chat server..");
BufferedReader reader=new BufferedReader(new InputStreamReader (socket.getInputStream()));
PrintWriter writer =new PrintWriter(socket.getOutputStream(), true);
Thread input=new Thread(()->{
BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));
try{
while(true) {
String line=userInput.readLine();
writer.println(line);}
}
catch(IOException e) {
System.out.println(e);}
});
input.start();
String serverMessage;
try{
while((serverMessage=reader.readLine())!=null)
{
System.out.println("Server: "+serverMessage);
}
}catch(IOException e){
e.printStackTrace();
}
finally{
socket.close();
}}}
import java.util.*; import javax.mail.*;
import javax.mail.internet.*; import javax.activation.*;
public class SendMail
{
public static void main(String [] args){
String to = "chinnasamyponnusamy@gmail.com";//change accordingly String from = "chinna@mlrinstitutions.ac.in";//change accordingly String host = "localhost";//or IP address
//Get the session object
Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
//compose the message try{
MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Ping");
message.setText("Hello, this is example of sending email ");
// Send message Transport.send(message);
System.out.println("message sent successfully. ");
}catch (MessagingException mex) {mex.printStackTrace();}
}
}
//DistanceVectorRouting import java.util.Arrays;
public class DistanceVectorRouting {
static final int INFINITY = Integer.MAX_VALUE;
static final int NUM_NODES = 4; // Number of nodes in the network
public static void main(String[] args) { int[][] distanceMatrix = {
{0, 1, 3, INFINITY}, // Distance from Node 0 to other nodes
{1, 0, INFINITY, 2}, // Distance from Node 1 to other nodes
{3, INFINITY, 0, 2}, // Distance from Node 2 to other nodes
{INFINITY, 2, 2, 0} // Distance from Node 3 to other nodes
};
// Initialize distance vector table
int[][] distanceVectorTable = new int[NUM_NODES][NUM_NODES]; for (int i = 0; i < NUM_NODES; i++) {
distanceVectorTable[i] = Arrays.copyOf(distanceMatrix[i], NUM_NODES);
}
System.out.println("Initial Distance Vector Table:");
printDistanceVectorTable(distanceVectorTable);
// Simulate iterations of the Distance Vector Routing algorithm for (int i = 0; i < NUM_NODES; i++) {
System.out.println("Iteration " + (i + 1) + ":"); for (int j = 0; j < NUM_NODES; j++) {
if (j != i) {
for (int k = 0; k < NUM_NODES; k++) {
if (k != i && distanceVectorTable[j][k] > distanceMatrix[j][i] + distanceVectorTable[i][k]) {
distanceVectorTable[j][k] = distanceMatrix[j][i] + distanceVectorTable[i][k];
}
}
}
}
printDistanceVectorTable(distanceVectorTable);
}
}
static void printDistanceVectorTable(int[][] distanceVectorTable) { for (int i = 0; i < NUM_NODES; i++) {
for (int j = 0; j < NUM_NODES; j++) {
System.out.print((distanceVectorTable[i][j] == INFINITY ? "INF" : distanceVectorTable[i][j]) + "\t");
}
System.out.println();
}
System.out.println();
}
}
To Run
Javac DistanceVectorRouting.java
Java DistanceVectorRouting
//LinkStateRouting import java.util.*;
public class LinkStateRouting {
static final int NUM_NODES = 5; // Number of nodes in the network
public static void main(String[] args) { int[][] adjacencyMatrix = {
{0, 2, 0, 1, 0}, // Adjacency matrix representing links between nodes
{2, 0, 3, 2, 0},
{0, 3, 0, 0, 1},
{1, 2, 0, 0, 4},
{0, 0, 1, 4, 0}
};
// Initialize link state database
int[][] linkStateDatabase = new int[NUM_NODES][NUM_NODES]; for (int i = 0; i < NUM_NODES; i++) {
for (int j = 0; j < NUM_NODES; j++) { if (i == j) {
linkStateDatabase[i][j] = 0;
} else if (adjacencyMatrix[i][j] != 0) { linkStateDatabase[i][j] = adjacencyMatrix[i][j];
} else {
linkStateDatabase[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Initial Link State Database:"); printLinkStateDatabase(linkStateDatabase);
// Simulate iterations of the Link State Routing algorithm for (int i = 0; i < NUM_NODES; i++) {
System.out.println("Iteration " + (i + 1) + ":");
for (int j = 0; j < NUM_NODES; j++) { if (j != i) {
for (int k = 0; k < NUM_NODES; k++) {
if (k != i && linkStateDatabase[j][i] != Integer.MAX_VALUE && linkStateDatabase[i][k] != Integer.MAX_VALUE &&
linkStateDatabase[j][k] > linkStateDatabase[j][i] + linkStateDatabase[i][k]) {
linkStateDatabase[j][k] = linkStateDatabase[j][i] + linkStateDatabase[i][k];
}
}
}
}
printLinkStateDatabase(linkStateDatabase);
}
}
static void printLinkStateDatabase(int[][] linkStateDatabase) { for (int i = 0; i < NUM_NODES; i++) {
for (int j = 0; j < NUM_NODES; j++) {
System.out.print((linkStateDatabase[i][j] == Integer.MAX_VALUE ? "INF" : linkStateDatabase[i][j]) + "\t");
}
System.out.println();
}
System.out.println();
}
}
//To Run
//Javac LinkStateRouting.java
//Java LinkStateRouting
GENERAL COMMANDS:
Start the docker daemon
docker -d
Get help with Docker. Can also use –help on all subcommands
docker --help
Display system-wide information
docker info
IMAGES:
Docker images are a lightweight, standalone, executable package of software that includes
everything needed to run an application: code, runtime, system tools, system libraries and
settings.
Build an Image from a Dockerfile
docker build -t
Build an Image from a Dockerfile without the cachedocker build -t . –no-cache
List local images
docker images
Delete an Image
docker rmi
Remove all unused images
docker image prune
CONTAINERS:
A container is a runtime instance of a docker image. A container will always run the same,
regardless of the infrastructure. Containers isolate software from its environment and
ensure that it works uniformly despite differences for instance between development and
staging.
Create and run a container from an image, with a custom name:
docker run –name
Run a container with and publish a container’s port(s) to the host.
docker run -p :
Run a container in the background
docker run -d
Start or stop an existing container:
docker start|stop (or )
Remove a stopped container:
docker rm
Open a shell inside a running container:
docker exec -it sh
Fetch and follow the logs of a container:
docker logs -f
To inspect a running container:
docker inspect (or )
To list currently running containers:
docker ps
List all docker containers (running and stopped):
60
docker ps --all
View resource usage stats
docker container stats