0% found this document useful (0 votes)
50 views43 pages

IT - 801 Information Security Lab Manual

The document outlines the vision, mission, program outcomes, education objectives, and specific outcomes for the Information Technology department at Swami Vivekanand College of Engineering Indore for the semester Jan-June 2025. It details the course on Information Security, including practical experiments related to network security, denial of service attacks, and IP-based authentication. The document emphasizes the importance of ethical hacking, social engineering, and various security protocols in the field of information technology.

Uploaded by

varmavikas251
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)
50 views43 pages

IT - 801 Information Security Lab Manual

The document outlines the vision, mission, program outcomes, education objectives, and specific outcomes for the Information Technology department at Swami Vivekanand College of Engineering Indore for the semester Jan-June 2025. It details the course on Information Security, including practical experiments related to network security, denial of service attacks, and IP-based authentication. The document emphasizes the importance of ethical hacking, social engineering, and various security protocols in the field of information technology.

Uploaded by

varmavikas251
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/ 43

Swami Vivekanand College of Engineering Indore

Department of Information Technology

Session: Jan – June 2025

Semester-VIII th / IV th Year

Information Security ( IT- 801)

Submitted to: Submitted by:

Ms. Silky Mishra Hariom Ruhela


IT Department 0822IT211016
VISION OF THE DEPARTMENT

To achieve global standard in quality of education, research & development in Information Technology by
adapting to the rapid technological advancement to empowering the IT- industry with the wings of
knowledge and power of innovation though knowledge creation, acquisition and dissemination for the
benefit of Society and Humanity.

MISSION OF THE DEPARTMENT

M1: To provide students with Innovative and research skills, which is need of the hour for technical students.

M2: To impart knowledge to the students of Information Technology with relevant core and practical
knowledge inculcating real time experience in the promising field of computing.

M3: To prepare the graduates to meet information technology challenges with a blend of social, human,
ethical and value based education.

M4: To engage in emerging research areas and establishing leadership.

M5: To contribute to the community services at large as well as catering to socio-economic goals in local
and national levels.

.
PROGRAM OUTCOMES (POs)

PO1. Engineering knowledge:Apply the knowledge of mathematics, science, engineering


fundamentals,andanengineeringspecializationtothesolutionofcomplexengineeringproblems.
PO2.Problemanalysis:Identify,formulate,researchliterature,andanalyzecomplexengineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineeringsciences.

PO3.Design/development of solutions:Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4.Conductinvestigationsofcomplexproblems:Useresearch-basedknowledgeandresearch
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide validconclusions.

PO5.Moderntoolusage:Create,select,andapplyappropriatetechniques,resources,andmodern
engineeringandITtoolsincludingpredictionandmodelingtocomplexengineeringactivitieswith an
understanding of thelimitations.

PO6.Theengineerandsociety:Applyreasoninginformedbythecontextualknowledgetoassess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant tothe
professional engineeringpractice.

PO7. Environment and sustainability:Understand the impact of the professional engineering


solutions in societal and environmental contexts, and demonstrate the knowledge of, and needfor
sustainabledevelopment.

PO8. Ethics:Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9.Individualandteamwork:Functioneffectivelyasanindividual,andasamemberorleader in
diverse teams, and in multidisciplinarysettings.

PO10. Communication:Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO11. Project management and finance:Demonstrate knowledge and understanding of the


engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12.Life-longlearning:Recognizetheneedfor,andhavethepreparationandabilitytoengage in
independent and life-long learning in the broadest context of technologicalchange
PROGRAM EDUCATION OBJECTIVES (PEOs)

PEO-I: Meet Market Demands: To prepare students to become a successful engineer to meet the
demand driven needs of industries/technical profession.

PEO-II: Core Competence: Graduates will demonstrate core competence in mathematical, Scientific and
basic engineering fundamentals necessary to formulate, analyze and solve engineering problems and also to
pursue advanced study or research.

PEO-III: Design and Analysis : Graduates will demonstrate good breadth of knowledge in core areas of
Information Technology and related engineering so as to comprehend engineering trade-offs, analyze,
design, and synthesize data and technical concepts to create novel designs in solving the real life problems.

PEO-IV:Professional Responsibility : Graduates will demonstrate professional responsibility by offering a


wide spectrum of consultancy and testing services by addressing social, cultural, economic, sustainability,
and environmental considerations in the solution of real world engineering problems.

PEO-V: Life-long learning: Graduates will engage themselves in life-long learning through independent
study and by participating in professional activities or continuing education
PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Understand, Analyze and develop computer programs for efficient analysis and design of computer based
system.

PSO2: Apply standard practices and strategies in software development.

PSO3: Employ modern computer language software tools and platforms in creating innovative career paths to
be a successful professional

Course Outcomes (CO)

At the end of the course, student would be able to

1. knowledge of cryptography and network security

2. knowledge of security management and incident response

3. knowledge of security in software and operating systems

4. knowledge of data security and secure system development

5. knowledge of privacy and data protection


INDEX

Student Practical Evaluation Sheet

Marks Signature
S. Date of Date of Obtained Signature
Name of Experiment of
No Experiment Submission of Faculty
LW(10 PQ (10 Student
. marks) marks)
Study of Network Security
fundamentals - Ethical
1 Hacking, Social Engineering
practices.

Study of System threat attacks -


2
Denial of Services.
Study of IP based
3
Authentication.
Study of Techniques uses for
4 Web Based Password
Capturing.
Study of Different attacks
5 causes by Virus and Trojans.

Study of Anti-Intrusion
6
Technique – Honey pot.
Implementation of encryption
and decryption a string using
7
Caesar Cipher.

Implementation of S-DES
8 algorithm for data encryption.

Implementation of RSA
9 algorithm.

Implementation of MD5
10
Algorithm.
Experiment No. 1

AIM: Study of Network Security fundamentals - Ethical Hacking, Social Engineering


practices.

Ethical Hacking- Ethical hacking and ethical hacker are terms that describe hacking
performed to help a company or individual identify potential threats on the computer or network.
An ethical hacker attempts to hack their way past the system security, finding any weak points in
the security that could be exploited by other hackers. The organization uses what the ethical
hacker finds to improve the system security, in an effort to minimize, if not eliminate any
potential hacker attacks.
In order for hacking to be deemed ethical, the hacker must obey the below rules.
1. You have permission to probe the network and attempt to identify potential security risks. It's
recommended that if you are the person performing the tests that you get written consent.
2. You respect the individual's or company's privacy and only go looking for security issues.
3. You report all security vulnerabilities you detect to the company, not leaving anything open
for you or someone else to come in at a later time.
4. You let the software developer or hardware manufacturer know of any security vulnerabilities
you locate in their software or hardware if not already known by the company.

The term "ethical hacker" has received criticism at times from people who say that there is no
such thing as an "ethical" hacker. Hacking is hacking, no matter how you look at it and those
who do the hacking are commonly referred to as computer criminals. However, the work that
ethical hackers do for organizations has helped improve system security and can be said to be
quite successful. Individuals interested in becoming an ethical hacker can work towards a
certification to become a Certified Ethical Hacker. This certification is provided by the
International Council of E-Commerce Consultants (EC-Council).

Social Engineering practices: The practice of deceiving someone, either in person, over the
phone, or using a computer, with the express intent of breaching some level of security either
personal or professional. Social engineering techniques are considered con games which are
performed by con artists. The targets of social engineering may never realize they have been
victimized.
Also Known As: Con Games
Examples:
Using social engineering techniques, the hacker managed to get the network administrator to
provide him the username and password needed to gain access to the company's server.

SOCIAL ENGINEERING TACTICS & TOOLS – USING DECEPTION TO BREAK IN

Social engineering attacks are based on one thing – information. Without information about your
customers, social engineers aren’t able to use the elicitation and pretesting tactics that are
described below.
This information is relatively simple to obtain. A good social engineer can spend a few hours
researching a target online and have enough information to make even the most seasoned contact
center agent believe the social engineer is someone they are not. The increasing amount of
personal information that’s available using search engines, who is databases, social media
(Facebook, LinkedIn, MySpace, Twitter, etc.), blogs, wikis, and photo sharing sites makes it
very simple for them to find or determine:
Even social security numbers are available from some paid research services.

Once the social engineer has relevant information, they use it in these highly effective human
hacking tactics:
• Elicitation
• Pretexting
Experiment No. 2

Aim: Study of System threat attacks - Denial of Services.

Denial of Service: The goal of a denial of service attack is to deny legitimate users access to a
particular resource. An incident is considered an attack if a malicious user intentionally disrupts
service to a computer or network resource. Denial of service (DoS) attacks has become a major
threat to current computer networks. To have a better understanding on DoS attacks, In
particular, we network based and host based DoS attack techniques to illustrate attack principles.
DoS attacks are classified according to their major attack characteristics. Current counterattack
technologies are also reviewed, including major defense products in deployment and
representative defense approaches in research. Finally, DoS attacks and defenses in 802.11 based
wireless networks are explored at physical, MAC and network layers.

OVERVIEW OF DOS ATTACKS IN THE INTERNET


In this section, we overview the common DDoS attack techniques and discuss why attacks
succeed fundamentally.

Attack Techniques
Many attack techniques can be used for DoS purpose as long as they can disable service, or
downgrade service performance by exhausting resources for providing services. Although it is
Impossible to enumerate all existing attack techniques, we describe several representatives
network based and host based attacks in this section to illustrate attack principles. Readers can
find complementary information on DoS attacks in Handley et al. 2006 and Mirkovicet al. 2005.

Network Based Attacks


TCP SYN Flooding.DoS attacks often exploit stateful network protocols (Jian 2000, Shannon
etal. 2002), because these protocols consume resources to maintain states. TCP SYN flooding is
one of such attacks and had a wide impact on many systems. When a client attempts to establish
a TCP connection to a server, the client first sends a SYN message to the server. The server then
acknowledges by sending a SYN-ACK message to the client. The client completes the
establishment by responding with an ACK message. The connection between the client and the
server is then opened, and the service-specific data can be exchanged between them. The abuse
arises at the half-open state when the server is waiting for the client’s ACK message after ending
the SYN-ACK message to the client (CERT 1996). The server needs to allocate memoryfor
storing the information of the half-open connection. The memory will not be released until either
the server receives the final ACK message or the half-open connection expires. Attacking hosts
can easily create half-open connections via spoofing source IPs in SYN messages or ignoring
SYN-ACKs. The consequence is that the final ACK message will never be sent to the victim.
Because the victim normally only allocates a limited size of space in its process table, too many
half-open connections will soon fill the space. Even though the half-open connections will
eventually expire due to the timeout, zombies can aggressively send spoofed TCP SYN packets
requesting connections at a much higher rate than the expiration rate. Finally, the victim will be
unable to accept any new incoming connection and thus cannot provide services.

ICMP Smurf Flooding. ICMP is often used to determine if a computer in the Internet is
responding. To achieve this task, an ICMP echo request packet is sent to a computer. If the
computer receives the request packet, it will return an ICMP echo reply packet. In a smurf attack,
attacking hosts forge ICMP echo requests having the victim's address as the source address and
the broadcast address of these remote networks as the destination address (CERT 1998). As
depicted in Figure 1, if the firewall or router of the remote network does not filter the special
6/28 crafted packets, they will be delivered (broadcast) to all computers on that network. These
computers will then send ICMP echo reply packets back to the source (i.e., the victim) carried in
the request packets. The victim’s network is thus congested.

UDP Flooding.By patching or redesigning the implementation of TCP and ICMP


protocols,current networks and systems have incorporated new security features to prevent TCP
and ICMP attacks. Nevertheless, attackers may simply send a large amount of UDP packets
towards a victim. Since an intermediate network can deliver higher traffic volume than the
victim network can handle, the flooding traffic can exhaust the victim's connection resources.
Pure flooding can be done with any type of packets. Attackers can also choose to flood service
requests so that the victim cannot handle all requests with its constrained resources (i.e., service
memory or CPU cycles). Note that UDP flooding is similar to flash crowds that occur when a
large number of users try to access the same server simultaneously. However, the intent and the
triggering mechanisms for DDoS attacks and flash crowds are different.
Intermittent Flooding. Attackers can further tune their flooding actions to reduce the average
flooding rate to a very low level while achieving equivalent attack impacts on legitimate TCP
connections. In shrew attacks (Kuzmanovic et al. 2003), attacking hosts can flood packets in a
burst to congest and disrupt existing TCP connections. Since all disrupted TCP connections will
wait a specific period (called retransmission-time-out (RTO)) to retransmit lost packets,
attacking hosts can flood packets at the next RTO to disrupt retransmission. Thereby, attacking
hosts can synchronize their flooding at the following RTOs and disable legitimate TCP
connections as depicted in Figure 2. Such collaboration among attacking hosts not only reduces
overall flooding traffic, but also helps avoid detection. Similar attack techniques targeting
services with congestion control mechanisms for Quality of Service (QoS) have been discovered
by Guirguiset al. (2005). When a QoS enabled server receives a burst of service requests, it will
temporarily throttle incoming requests for a period until previous requests have been processed.
Thus, attackers can flood requests at a pace to keep the server throttling the incoming requests
and achieve the DoS effect. Guirguis’s study showed that a burst of 800 requests can bring down
a web server for 200 seconds, and thereby the average flooding rate could be as low as 4 requests
per second.
Experiment No. 03

Aim: Study of IP based Authentication.

IP security refers to security mechanisms implemented at the IP (Internet Protocol) Layer to


ensure integrity, authentication and confidentiality of data during transmission in the open
Internet environment. The primary objective of recent work in this area, mainly by members in
the IETF IP Security (IPsec) working group is to improve the robustness of the cryptographic
key-based security mechanisms at IP layer for users who request security.
How can IP Security be achieved?
Currently, there are two specific headers that can be attached to IP packet to achieve security.
They are the IP Authentication Header (AH) and the IP Encapsulating Security Payload (ESP)
header.

If confidentiality is not required, the Authentication Header (AH) alone can provide security (in
this case, connectionless data integrity and data origin authentication) to IP datagram. The
implementation can be host-host, host-gateway or gateway-gateway. But only host-host
implementation is encouraged. The reason is that, in the case that security gateway provides
security service for the trusted hosts behind the gateway, The security attack can still arise when
the trusted hosts become untrusted. In other words the security can be violated for two
communicating end user if the security (without confidentiality) does not cover completely the
communicating path, but instead stop at the gateway, even though SA is established. Certainly in
any kind of implementation, the untrusted systems (i.e., the systems that don't have the SA
established) can't have the ability to attack data authentication (always referring to both data
integrity and data origin authentication).

The IP Encapsulating Security Payload (ESP) header provides integrity, authentication, and
confidentiality to IP datagram. It can provide a mix of optional security. ESP header can be
applied alone, in combination with the IP Authentication Header (AH), or in a nested way, e. g.
by using Tunnel-mode. The ESP header implementation can be host-host, host-gateway, or
gateway-gateway. The ESP header is inserted after the IP header and before a higher-level
protocol header (Transport-mode) or the encapsulated IP header (Tunnel-mode). Gateway-to-
gateway ESP implementation, using encryption/decryption , is critical for building Private
Virtual Networks (PVN) across an untrusted backbone in an open environment such as the
Internet.
Experiment No. 4

Aim: Study of Techniques uses for Web Based Password Capturing.


Many people don’t understand how easy it is for attackers to take advantage of weak passwords,
and therefore don’t use a password manager or other means to make their passwords stronger.
This post describes 9 common ways passwords get captured, roughly ordered from most to least
common. Proper use of a password manager can thwart some of these attacks and limit damages
from most other types of attacks.
1: You Hand it Over Voluntarily
People frequently hand over their passwords via phishing, other forms of social engineering, or
when a person or entity asks for temporary use of a password.
Protection: The simplest defense is to NEVER share your password for any account with any
person, organization, or web site. An additional good defense is to develop “net smarts”
analogous to “street smarts” to avoid phishing scams or other forms of social engineering. If you
must temporarily share your password (i.e. to import contacts into Facebook), then change your
password immediately after its temporary use is complete.
Damage Control: Your damages are limited to one account if you have a unique password for
each account. Immediately change the password of the affected account.
2: You Hand it Over Unknowingly
This overlaps with the previous attack. You think you are on the web site you intended but you
actually mistyped it by one character, you clicked a bad link to get there, or you were tricked by
tab napping. So you end up on a fake or spoof web site that looks legitimate. When you log in, it
collects your credentials then passes you on to the real site. A variation on this theme is an attack
which layers extra fields over a legitimate web site. You are tricked into typing private personal
information such as birthday, mother’s maiden name, social security number, etc. and then this
information is used to “recover” your account .
Protection: A good defense against this ploy is to only login to a web site by selecting it from
your password manager’s drop down menu (even if the tab was one you thought you opened
yourself). This will automatically log you in to the correct site, which the password manager
stores. Another type of defense is for your browser to use a security service that warns you when
you might be about to open a hazardous web site – but this may slow down browsing.
Damage Control: Your damages are limited to one account if you have a unique password for
each account. Immediately change the password of the affected account.

3: Mass Theft of Password Files


Most people don’t realize that user names and passwords routinely get stolen while your
computer is off and disconnected from the internet. How? Web sites with many users and weak
security are prime targets for attackers who want to steal a password file which lists all user
names and passwords. Recent examples include Monster.com and RockYou.com. While most
sites do not store passwords as clear text, many sites store passwords in a form that can be read
using widely available rainbow table software. For people who use the same password on many
sites, the theft of this password on one site can be the starting point for an attack on all of your
accounts.
Protection: A simple and effective defense for users is to only use long, randomly generated
passwords. How long? 15 characters. Rainbow tables easily crack passwords 8 or fewer
characters long and in some cases up to 14 characters.
Damage Control: In the unlikely case that a rainbow table attack manages to crack one of your
15 character passwords, at least your damages will be limited to one account if you have a
unique password for each account. Change the password of any account that becomes
compromised due to mass theft.

4: Brute Force
Brute Force refers to discovering passwords through trial and error, similar to trying every
possible combination on a lock. The most well known form of brute force attack is for password
cracking software to methodically try millions of passwords on one specific user name on a
specific account. A typically weak password can be cracked in less than a day using this method.
Security conscious online vendors like banks or e-mail services provide some protection against
such brute force attempts by denying access if there are too many attempts per hour. However,
different forms of brute force can be used to get around these safeguards. A common example is
software which automatically logs in to millions of different accounts per day by combining
popular user names, passwords, and web sites (i.e. try password1 at Jsmith@gmail.com, 123456
at dj@facebook.com, qwerty at Mrodriguez@yahoo.com, etc.). As such methods become more
widely adopted, it would not be surprising if nearly all accounts with short user names and short
passwords get compromised.
Brute force is also used as a supplementary attack after a first password is captured. For example,
if the password badpassword1 was captured by phishing, brute force can be used to try similar
passwords on other accounts.
Protection: Brute force attacks are highly unlikely to crack very strong passwords. So just use
strong passwords. I suggest randomized 15 character jumbles.
Damage Control: Your damages are limited to one account if you have a unique password for
each account. Immediately change the password of the affected account.

5: Eavesdropping: Keystroke Logger on Your Browser


Many people believe that nothing bad can happen to people who only visit safe, well respected
sites. They are wrong. Malicious JavaScript can be injected into any browser on any system,
visiting any web site. Keystroke logging is something that is done by some of these JavaScript
injections. In most browsers, malicious JavaScript can log keystrokes in all open tabs, until the
browser is closed. Usernames and passwords entered during the session can be captured this
way.
Protection: Keystroke logging via browser is growing more common but is unfortunately one of
the more difficult threats to defend against. Defenses include:
Use Firefox in conjunction with the No Script extension. While this is a strong defense, the
overall complication of using No Script (popup, white lists, and blacklists) is more of a hassle
than the average Joe wants to deal with.
Some security suites attempt to defend against this threat with browser plug-ins, but these can
dramatically slow down browsing.
A simpler option is to only access the internet using the Google Chrome browser, which is
designed so that malicious JavaScript can be theoretically contained to a single tab. At least other
tabs will be safe.
Some password managers such as RoboForm enter passwords and usernames in a way which
most JavaScript keystroke loggers cannot intercept.
None of these suggestions are sure to stop browser-based keystroke loggers, but if you
implement one or more of these suggestions you’ll at least reduce your chances of getting your
usernames and passwords logged by malicious JavaScript. The only perfect defense is to not
connect to the internet at all.
Damage Control: Your damages are limited to logins captured while browsing, so long as you
have a unique password for each account. Immediately change the password of the affected
accounts. If using a browser-based or web-based password manager, you should also change
your master password.

6: Eavesdropping: Public Wi-Fi Monitoring


Passwords are frequently stolen on public computers and over public Wi-Fi connections, using
free Wi-Fi traffic monitoring software that is simple to operate.
Protection: Never log in to online accounts using a public computer. When using open Wi-Fi
hot spots, you should only log in with your own notebook with services that enforce secure log-
ins and sessions (HTTPS), perhaps using the Firefox Add-on HTTPS Everywhere to help. It is
far safer to access email and other accounts using your phone data service, if you have one.
Damage Control: If you discover that this type of attack has occurred, then you will need to
change the password for all of your accounts as well as your master password. If you know
exactly when the attack occurred, you can change passwords only for the accounts you used
during that session.
Experiment No. 5

Aim: Study of Different attacks causes by Virus and Trojans.


Virus: The most potent and vulnerable threat of computer users is virus attacks. Virus attacks
hampers important work involved with data and documents. It is imperative for every computer
user to be aware about the software and programs that can help to protect the personal computers
from attacks. One must take every possible measure in order to keep the computer systems free
from virus attacks. The top sources of virus attacks are highlighted below:
Downloadable Programs
Cracked Software
Email Attachments
Internet
Booting From CD

Trojans: Trojan horse attacks pose one of the most serious threats to computer security. If you
were referred here, you may have not only been attacked but may also be attacking others
unknowingly. This page will teach you how to avoid falling prey to them, and how to repair the
damage if you already did. According to legend, the Greeks won the Trojan war by hiding in a
huge, hollow wooden horse to sneak into the fortified city of Troy. In today’s computer world, a
Trojan horse is defined as a “malicious, security-breaking program that is disguised as something
benign”. For example, you download what appears to be a movie or music file, but when you
click on it, you unleash a dangerous program that erases your disk, sends your credit card
numbers and passwords to a stranger, or lets that stranger hijack your computer to commit illegal
denial of service attacks.
The following general information applies to all operating systems, but by far most of the
damage is done to/with Windows users due to its vast popularity and many weaknesses. Linux,
MacOS X, and other operating systems are not as frequently infected, but they are far from
immune.
Repairing the Damage
1. Anti-Virus Software: Some of these can handle most of the well knowntrojans, but none are
perfect, no matter what their advertising claims. You absolutely MUST make sure you have the
very latest update files for your programs, or else they will miss the latest trojans. Compared to
traditional viruses, today’s trojans evolve much quicker and come in many seemingly innocuous
forms, so anti-virus software is always going to be playing catch up. Also, if they fail to find
every trojan, anti-virus software can give you a false sense of security, such that you go about
your business not realizing that you are still dangerously compromised. There are many products
to choose from, but the following are generally effective: AVP, PC-cillin, and McAfee Virus
Scan. All are available for immediate downloading typically with a 30 day free trial. For a more
complete review of all major anti-virus programs, including specific configuration suggestions
for each, see the Hack Fix Project’s anti-virus software page .When you are done, make sure
you’ve updated Windows with all security patches .
2. Anti-Trojan Programs: These programs are the most effective against trojan horse attacks,
because they specialize in trojans instead of general viruses. A popular choice is The Cleaner,
$30 commercial software with a 30 day free trial. To use it effectively when you are done, make
sure you’ve updated Windows with all security patches, then change all your passwords because
they may have been seen by every “hacker” in the world.

BASIS FOR
VIRUS WORM TROJAN HORSE
COMPARISON

Meaning A computer program that It eats resources of a It permits an intruder

connects itself to another system to bring it to obtain some

legitimate program to down rather than confidential

cause harm to the performing information about a

computer system or the destructive actions. computer network.

network.

Execution Depends on the transfer Replicates itself Downloaded as


BASIS FOR
VIRUS WORM TROJAN HORSE
COMPARISON

of a file. without any human software and

action. executed.

Replication occurs Yes Yes No

Remotely No Yes Yes

controlled

Rate of spreading Moderate Faster Slow

Infection Initiates by attaching a Utilizes system or Attaches itself to a

virus to an executable application program and

file. weaknesses. interpret as useful

software.

Purpose Modification of the Halt the CPU and Steals the user's

information. memory. information.


Experiment No. 6

Aim: Study of Anti-Intrusion Technique – Honey pot.


Anti-Intrusion Technique: The basic underlying principles of intrusion control and distill the
universe of anti-intrusion techniques into six high-level, mutually supportive approaches. System
and network intrusions may be prevented, preempted, deflected, deterred, detected, and/or
autonomously countered. This Anti-Intrusion Taxonomy (AINT) of anti-intrusion techniques
considers less explored approaches on the periphery of "intrusion detection" which are
independent of the availability of a rich audit trail, as well as better known intrusion detection
techniques. Much like the Open Systems Reference Model supports understanding of
communications protocols by identifying their layer and purpose, the authors believe this anti-
intrusion taxonomy and associated methods and techniques help clarify the relationship between
anti-intrusion techniques described in the literature and those implemented by commercially
available products. The taxonomy may be used to assess computing environments which perhaps
already support Intrusion Detection System (IDS) implementations to help identify useful
complementary intrusion defense approaches.
Honey pot: In computer terminology, a honey pot is a trap set to detect, deflect, or, in some
manner, counteract attempts at unauthorized use of information systems. Generally, a honey pot
consists of a computer, data, or a network site that appears to be part of a network, but is actually
isolated and monitored, and which seems to contain information or a resource of value to
attackers. This is similar to the police baiting a criminal and then conducting undercover
surveillance.
Honeypots can be classified based on their deployment and based on their level of involvement.
Based on deployment, honeypots may be classified as:
1. production honeypots
2. research honeypots

Production honeypots are easy to use, capture only limited information, and are used primarily
by companies or corporations; Production honeypots are placed inside the production network
with other production servers by an organization to improve their overall state of security.
Normally, production honeypots are low-interaction honeypots, which are easier to deploy. They
give less information about the attacks or attackers than research honeypots do.

Research honeypots are run to gather information about the motives and tactics of the Blackhat
community targeting different networks. These honeypots do not add direct value to a specific
organization; instead, they are used to research the threats organizations face and to learn how to
better protect against those threats.Research honeypots are complex to deploy and maintain,
capture extensive information, and are used primarily by research, military, or government
organizations.

Types of Honeypot Deployments

There are three types of honeypot deployments that permit threat actors to perform different
levels of malicious activity:

Pure honeypots—complete production systems that monitor attacks through bug taps on
the link that connects the honeypot to the network. They are unsophisticated.

Low-interaction honeypots—imitate services and systems that frequently attract


criminal attention. They offer a method for collecting data from blind attacks such as
botnets and worms malware.

High-interaction honeypots—complex setups that behave like real production


infrastructure. They don’t restrict the level of activity of a cybercriminal, providing
extensive cybersecurity insights. However, they are higher-maintenance and require
expertise and the use of additional technologies like virtual machines to ensure attackers
cannot access the real system.

Honeypot Limitations
Honeypot security has its limitations as the honeypot cannot detect security breaches in
legitimate systems, and it does not always identify the attacker. There is also a risk that, having
successfully exploited the honeypot, an attacker can move laterally to infiltrate the real
production network. To prevent this, you need to ensure that the honeypot is adequately isolated.
To help scale your security operations, you can combine honeypots with other techniques. For
example, the canary trap strategy helps find information leaks by selectively sharing different
versions of sensitive information with suspected moles or whistleblowers.

Honeynet: A Network of Honeypots


A honeynet is a decoy network that contains one or more honeypots. It looks like a real network
and contains multiple systems but is hosted on one or only a few servers, each representing one
environment. For example, a Windows honeypot machine, a Mac honeypot machine and a Linux
honeypot machine.

A “honeywall” monitors the traffic going in and out of the network and directs it to the honeypot
instances. You can inject vulnerabilities into a honeynet to make it easy for an attacker to access
the trap.

Example of a honeynet topology


Any system on the honeynet may serve as a point of entry for attackers. The honeynet gathers
intelligence on the attackers and diverts them from the real network. The advantage of a
honeynet over a simple honeypot is that it feels more like a real network, and has a larger
catchment area.

This makes honeynet a better solution for large, complex networks – it presents attackers with an
alternative corporate network which can represent an attractive alternative to the real one.
Experiment No. 7

Aim: 7. Implementation of encryption and decryption a string using Caesar Cipher.

For encrypting a string, key-value ‘2’ is added to the ASCII value of the characters in the string.
Similarly, for decrypting a string, key-value ‘2’ is subtracted from the ASCII value of the
characters.

#include <iostream>
using namespace std;

int main()
{
int i, x;
char str[100];

cout << "Please enter a string:\t";


cin >> str;

cout << "\nPlease choose following options:\n";


cout << "1 = Encrypt the string.\n";
cout << "2 = Decrypt the string.\n";
cin >> x;

//using switch case statements


switch(x)
{
//first case for encrypting a string
case 1:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] + 2; //the key for encryption is 3 that is added to ASCII value

cout << "\nEncrypted string: " << str << endl;


break;

//second case for decrypting a string


case 2:
for(i = 0; (i < 100 && str[i] != '\0'); i++)
str[i] = str[i] - 2; //the key for encryption is 3 that is subtracted to ASCII value

cout << "\nDecrypted string: " << str << endl;


break;

default:
cout << "\nInvalid Input !!!\n";
}
return 0;
}

Output :
Please enter a string: svceindore

Please choose following options:


1 = Encrypt the string.
2 = Decrypt the string.
1

Encrypted string: uxegkpfqtg


Experiment No. 8

Aim: Implementation of S-DES algorithm for data encryption Procedure:


S-DES algorithm uses bit wise operation on message letters to encrypt the data so it is more
power full against the cryptanalysis attack. In this algorithm we will take 8-bits of the message at
a time and operate on it using the 10-bit key and two rounds of iteration.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
// Array to hold 16 keys
string round_keys[16];
// String to hold the plain text
string pt;
// Function to convert a number in decimal to binary
string convertDecimalToBinary(int decimal)
{
string binary;
while(decimal != 0) {
binary = (decimal % 2 == 0 ? "0" : "1") + binary;
decimal = decimal/2;
}
while(binary.length() < 4){
binary = "0" + binary;
}
return binary;
}
// Function to convert a number in binary to decimal
int convertBinaryToDecimal(string binary)
{
int decimal = 0;
int counter = 0;
int size = binary.length();
for(int i = size-1; i >= 0; i--)
{
if(binary[i] == '1'){
decimal += pow(2, counter);
}
counter++;
}
return decimal;
}
// Function to do a circular left shift by 1
string shift_left_once(string key_chunk){
string shifted="";
for(int i = 1; i < 28; i++){
shifted += key_chunk[i];
}
shifted += key_chunk[0];
return shifted;
}
// Function to do a circular left shift by 2
string shift_left_twice(string key_chunk){
string shifted="";
for(int i = 0; i < 2; i++){
for(int j = 1; j < 28; j++){
shifted += key_chunk[j];
}
shifted += key_chunk[0];
key_chunk= shifted;
shifted ="";
}
return key_chunk;
}
// Function to compute xor between two strings
string Xor(string a, string b){
string result = "";
int size = b.size();
for(int i = 0; i < size; i++){
if(a[i] != b[i]){
result += "1";
}
else{
result += "0";
}
}
return result;
}
// Function to generate the 16 keys.
void generate_keys(string key){
// The PC1 table
int pc1[56] = {
57,49,41,33,25,17,9,
1,58,50,42,34,26,18,
10,2,59,51,43,35,27,
19,11,3,60,52,44,36,
63,55,47,39,31,23,15,
7,62,54,46,38,30,22,
14,6,61,53,45,37,29,
21,13,5,28,20,12,4
};
// The PC2 table
int pc2[48] = {
14,17,11,24,1,5,
3,28,15,6,21,10,
23,19,12,4,26,8,
16,7,27,20,13,2,
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32
};
// 1. Compressing the key using the PC1 table
string perm_key ="";
for(int i = 0; i < 56; i++){
perm_key+= key[pc1[i]-1];
}
// 2. Dividing the key into two equal halves
string left= perm_key.substr(0, 28);
string right= perm_key.substr(28, 28);
for(int i=0; i<16; i++){
// 3.1. For rounds 1, 2, 9, 16 the key_chunks
// are shifted by one.
if(i == 0 || i == 1 || i==8 || i==15 ){
left= shift_left_once(left);
right= shift_left_once(right);
}
// 3.2. For other rounds, the key_chunks
// are shifted by two
else{
left= shift_left_twice(left);
right= shift_left_twice(right);
}
// Combining the two chunks
string combined_key = left + right;
string round_key = "";
// Finally, using the PC2 table to transpose the key bits
for(int i = 0; i < 48; i++){
round_key += combined_key[pc2[i]-1];
}
round_keys[i] = round_key;
}

}
// Implementing the algorithm
string DES(){
// The initial permutation table
int initial_permutation[64] = {
58,50,42,34,26,18,10,2,
60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,
64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,
59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,
63,55,47,39,31,23,15,7
};
// The expansion table
int expansion_table[48] = {
32,1,2,3,4,5,4,5,
6,7,8,9,8,9,10,11,
12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,
22,23,24,25,24,25,26,27,
28,29,28,29,30,31,32,1
};
// The substitution boxes. The should contain values
// from 0 to 15 in any order.
int substition_boxes[8][4][16]=
{{
14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7,
0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8,
4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0,
15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13
},
{
15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10,
3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5,
0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15,
13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9
},
{
10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8,
13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1,
13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7,
1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12
},
{
7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15,
13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9,
10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4,
3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14
},
{
2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9,
14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6,
4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14,
11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3
},
{
12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11,
10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8,
9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6,
4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13
},
{
4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1,
13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6,
1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2,
6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12
},
{
13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7,
1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2,
7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8,
2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11
}};
// The permutation table
int permutation_tab[32] = {
16,7,20,21,29,12,28,17,
1,15,23,26,5,18,31,10,
2,8,24,14,32,27,3,9,
19,13,30,6,22,11,4,25
};
// The inverse permutation table
int inverse_permutation[64]= {
40,8,48,16,56,24,64,32,
39,7,47,15,55,23,63,31,
38,6,46,14,54,22,62,30,
37,5,45,13,53,21,61,29,
36,4,44,12,52,20,60,28,
35,3,43,11,51,19,59,27,
34,2,42,10,50,18,58,26,
33,1,41,9,49,17,57,25
};
//1. Applying the initial permutation
string perm = "";
for(int i = 0; i < 64; i++){
perm += pt[initial_permutation[i]-1];
}
// 2. Dividing the result into two equal halves
string left = perm.substr(0, 32);
string right = perm.substr(32, 32);
// The plain text is encrypted 16 times
for(int i=0; i<16; i++) {
string right_expanded = "";
// 3.1. The right half of the plain text is expanded
for(int i = 0; i < 48; i++) {
right_expanded += right[expansion_table[i]-1];
}; // 3.3. The result is xored with a key
string xored = Xor(round_keys[i], right_expanded);
string res = "";
// 3.4. The result is divided into 8 equal parts and passed
// through 8 substitution boxes. After passing through a
// substituion box, each box is reduces from 6 to 4 bits.
for(int i=0;i<8; i++){
// Finding row and column indices to lookup the
// substituition box
string row1= xored.substr(i*6,1) + xored.substr(i*6 + 5,1);
int row = convertBinaryToDecimal(row1);
string col1 = xored.substr(i*6 + 1,1) + xored.substr(i*6 + 2,1) + xored.substr(i*6 + 3,1) +
xored.substr(i*6 + 4,1);;
int col = convertBinaryToDecimal(col1);
int val = substition_boxes[i][row][col];
res += convertDecimalToBinary(val);
}
// 3.5. Another permutation is applied
string perm2 ="";
for(int i = 0; i < 32; i++){
perm2 += res[permutation_tab[i]-1];
}
// 3.6. The result is xored with the left half
xored = Xor(perm2, left);
// 3.7. The left and the right parts of the plain text are swapped
left = xored;
if(i < 15){
string temp = right;
right = xored;
left = temp;
}
}
// 4. The halves of the plain text are applied
string combined_text = left + right;
string ciphertext ="";
// The inverse of the initial permuttaion is applied
for(int i = 0; i < 64; i++){
ciphertext+= combined_text[inverse_permutation[i]-1];
}
//And we finally get the cipher text
return ciphertext;
}
int main(){
// A 64 bit key
string key= "1010101010111011000010010001100000100111001101101100110011011101";

// A block of plain text of 64 bits

pt= "0000000111001101111001101010101111001101000100110010010100110110";
string apt = pt;
// Calling the function to generate 16 keys
generate_keys(key);
cout<<"\n Plain text: "<<pt<<endl;
// Applying the algo
string ct= DES();
cout<<" \n Ciphertext: "<<ct<<endl;
// Reversing the round_keys array for decryption
int i = 15;
int j = 0;
while(i > j)
{
string temp = round_keys[i];
round_keys[i] = round_keys[j];
round_keys[j] = temp;
i--;
j++;
}
pt = ct;
string decrypted = DES();
cout<<"\n Decrypted text:"<<decrypted<<endl;
// Comapring the initial plain text with the decrypted text
if (decrypted == apt){
cout<<"\n \n Plain text Encrypted and Decrypted successfully."<<endl;
}
}
Experiment No. 9

Aim: Implementation of RSA algorithm


The RSA algorithm was invented by Ronald L. Rivest, Adi Shamir, and Leonard Adleman in
1977 and released into the public domain on September 6, 2000.
Public-key systems–or asymmetric cryptography–use two different keys with a mathematical
relationship to each other. Their protection relies on the premise that knowing one key will not
help you figure out the other. The RSA algorithm uses the fact that it’s easy to multiply two large
prime numbers together and get a product. But you can’t take that product and reasonably guess
the two original numbers, or guess one of the original primes if only the other is known. The
public key and private keys are carefully generated using the RSA algorithm; they can be used to
encrypt information or sign it.
Key generation 1) Pick two large prime numbers p and q, p != q; 2) Calculate n = p × q; 3)
Calculate ø (n) = (p − 1)(q − 1); 4) Pick e, so that gcd(e, ø (n)) = 1, 1 < e < ø (n); 5) Calculate d,
so that d · e mod ø (n) = 1, i.e., d is the multiplicative inverse of e in mod ø (n); 6) Get public key
as KU = {e, n}; 7) Get private key as KR = {d, n}.
Encryption For plaintext block P < n, its ciphertext C = P^e (mod n). Decryption For ciphertext
block C, its plaintext is P = C^d (mod n).

// Program to Implement the RSA Algorithm

#include<iostream>
#include<math.h>
#include<string.h>
#include<stdlib.h>

using namespace std;

long int p, q, n, t, flag, e[100], d[100], temp[100], j, m[100], en[100], i;


char msg[100];
int prime(long int);
void ce();
long int cd(long int);
void encrypt();
void decrypt();
int prime(long int pr)
{
int i;
j = sqrt(pr);
for (i = 2; i <= j; i++)
{
if (pr % i == 0)
return 0;
}
return 1;
}
int main()
{
cout << "\nENTER FIRST PRIME NUMBER\n";
cin >> p;
flag = prime(p);
if (flag == 0)
{
cout << "\nWRONG INPUT\n";
exit(1);
}
cout << "\nENTER ANOTHER PRIME NUMBER\n";
cin >> q;
flag = prime(q);
if (flag == 0 || p == q)
{
cout << "\nWRONG INPUT\n";
exit(1);
}
cout << "\nENTER MESSAGE\n";
fflush(stdin);
cin >> msg;
for (i = 0; msg[i] != '\0'; i++)
m[i] = msg[i];
n = p * q;
t = (p - 1) * (q - 1);
ce();
cout << "\nPOSSIBLE VALUES OF e AND d ARE\n";
for (i = 0; i < j - 1; i++)
cout << e[i] << "\t" << d[i] << "\n";
encrypt();
decrypt();
return 0;
}
void ce()
{
int k;
k = 0;
for (i = 2; i < t; i++)
{
if (t % i == 0)
continue;
flag = prime(i);
if (flag == 1 && i != p && i != q)
{
e[k] = i;
flag = cd(e[k]);
if (flag > 0)
{
d[k] = flag;
k++;
}
if (k == 99)
break;
}
}
}
long int cd(long int x)
{
long int k = 1;
while (1)
{
k = k + t;
if (k % x == 0)
return (k / x);
}
}
void encrypt()
{
long int pt, ct, key = e[0], k, len;
i = 0;
len = strlen(msg);
while (i != len)
{
pt = m[i];
pt = pt - 96;
k = 1;
for (j = 0; j < key; j++)
{
k = k * pt;
k = k % n;
}
temp[i] = k;
ct = k + 96;
en[i] = ct;
i++;
}
en[i] = -1;
cout << "\nTHE ENCRYPTED MESSAGE IS\n";
for (i = 0; en[i] != -1; i++)
printf("%c", en[i]);
}
void decrypt()
{
long int pt, ct, key = d[0], k;
i = 0;
while (en[i] != -1)
{
ct = temp[i];
k = 1;
for (j = 0; j < key; j++)
{
k = k * ct;
k = k % n;
}
pt = k + 96;
m[i] = pt;
i++;
}
m[i] = -1;
cout << "\nTHE DECRYPTED MESSAGE IS\n";
for (i = 0; m[i] != -1; i++)
printf("%c", m[i]);
}

Output :

ENTER FIRST PRIME NUMBER


7
ENTER ANOTHER PRIME NUMBER
13
ENTER MESSAGE
ram
POSSIBLE VALUES OF e AND d ARE
5 29
11 59
17 17
19 19
23 47
29 5
31 7

THE ENCRYPTED MESSAGE IS


�am
THE DECRYPTED MESSAGE IS
ram
Experiment No. 10

Aim: Implementation of MD5 Algorithm

The MD5 (message-digest algorithm) hashing algorithm is a one-way cryptographic function


that accepts a message of any length as input and returns as output a fixed-length digest value to
be used for authenticating the original message.

The MD5 hash function was originally designed for use as a secure cryptographic hash algorithm
for authenticating digital signatures. But MD5 has been deprecated for uses other than as a
noncryptographic checksum to verify data integrity and detect unintentional data corruption.

#ifndef CONSTEXPR_HASH_MD5_H
#define CONSTEXPR_HASH_MD5_H

#include <array>
#include <iostream>
#include <cstdint>

namespace ConstexprHashes {
// MD5 operations
constexpr uint32_t f(uint32_t x, uint32_t y, uint32_t z) {
return z ^ (x & (y ^ z));
}

constexpr uint32_t g(uint32_t x, uint32_t y, uint32_t z) {


return y ^ (z & (x ^ y));
}

constexpr uint32_t h(uint32_t x, uint32_t y, uint32_t z) {


return x ^ y ^ z;
}

constexpr uint32_t i(uint32_t x, uint32_t y, uint32_t z) {


return y ^ (x | ~z);
}

constexpr uint32_t step_helper(uint32_t fun_val, uint32_t s, uint32_t b) {


return ((fun_val << s) | ((fun_val & 0xffffffff) >> (32 - s))) + b;
}

// Generic application of the "fun" function

template<typename Functor>
constexpr uint32_t step(Functor fun, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t x, uint32_t t, uint32_t s)
{
return step_helper(a + fun(b, c, d) + x + t, s, b);
}

// Retrieve the nth uint32_t in the buffer

constexpr uint32_t data32(const char* data, size_t n) {


return (static_cast<uint32_t>(data[n * 4]) & 0xff) |
((static_cast<uint32_t>(data[n * 4 + 1]) << 8) & 0xff00) |
((static_cast<uint32_t>(data[n * 4 + 2]) << 16) & 0xff0000) |
((static_cast<uint32_t>(data[n * 4 + 3]) << 24) & 0xff000000);
}

// Constants

constexpr std::array<uint32_t, 64> md5_constants = {{


0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,
0xa8304613,0xfd469501,0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,0xf61e2562,0xc040b340,
0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,
0x676f02d9,0x8d2a4c8a,0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,0x289b7ec6,0xeaa127fa,
0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3,0x8f0ccc92,
0xffeff47d,0x85845dd1,0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391
}};

constexpr std::array<size_t, 64> md5_shift = {{


7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,
5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
}};

constexpr std::array<size_t, 64> md5_indexes = {{


0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,
9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,
0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9
}};

// Functions applied

constexpr std::array<decltype(f)*, 4> md5_functions = {{


f, g, h, i
}};

/******************** Initial buffer generators ***********************/

// index_tuples to fill the initial buffer

template<size_t... indexes>
struct index_tuple {};

template<size_t head, size_t... indexes>


struct index_tuple<head, indexes...> {
typedef typename index_tuple<head-1, head-1, indexes...>::type type;
};

template<size_t... indexes>
struct index_tuple<0, indexes...> {
typedef index_tuple<indexes...> type;
};

template<typename... Args>
struct index_tuple_maker {
typedef typename index_tuple<sizeof...(Args)>::type type;
};

/* This builds the buffer.


*
* For indexes < string length: output the ith character in the string.
* For indexes > string length: output 0.
* If index == string length: output 0x80
* If index == 56: output string length << 3
*
*/

template<size_t n, size_t i>


struct buffer_builder {
static constexpr char make_value(const char *data) {
return (i <= n) ? data[i] : 0;
}
};

template<size_t n>
struct buffer_builder<n, n> {
static constexpr char make_value(const char *) {
return 0x80;
}
};

template<size_t n>
struct buffer_builder<n, 56> {
static constexpr char make_value(const char *) {
return n << 3;
}
};

/*
* Simple array implementation, which allows constexpr access to its
* elements.
*/

template<typename T, size_t n>


struct constexpr_array {
const T array[n];

constexpr const T *data() const {


return array;
}
};
typedef constexpr_array<char, 64> buffer_type;

template<size_t n, size_t... indexes>


constexpr buffer_type make_buffer_helper(const char (&data)[n], index_tuple<indexes...>) {
return buffer_type{{ buffer_builder<n - 1, indexes>::make_value(data)... }};
}

// Creates the actual buffer

template<size_t n>
constexpr buffer_type make_buffer(const char (&data)[n]) {
return make_buffer_helper(data, index_tuple<64>::type());
}

/************************ MD5 impl ***************************/

typedef std::array<char, 16> md5_type;

/*
* There are 64 steps. The ith step has the same structure as the ith + 4 step.
* That means that we can repeat the same structure, and pick the appropiate
* constants and function to apply, depending on the step number.
*/

template<size_t n, size_t rot>


struct md5_step;

/*
* Nasty, but works. Convert the MD5 result(which is 4 uint32_t), to
* a std::array<char, 16>.
*/

constexpr md5_type make_md5_result(uint32_t a, uint32_t b, uint32_t c, uint32_t d) {


typedef md5_type::value_type value_type;
return md5_type{{
static_cast<value_type>(a & 0xff), static_cast<value_type>((a & 0xff00) >> 8),
static_cast<value_type>((a & 0xff0000) >> 16), static_cast<value_type>((a & 0xff000000) >> 24),

static_cast<value_type>(b & 0xff), static_cast<value_type>((b & 0xff00) >> 8),


static_cast<value_type>((b & 0xff0000) >> 16), static_cast<value_type>((b & 0xff000000) >> 24),

static_cast<value_type>(c & 0xff), static_cast<value_type>((c & 0xff00) >> 8),


static_cast<value_type>((c & 0xff0000) >> 16), static_cast<value_type>((c & 0xff000000) >> 24),

static_cast<value_type>(d & 0xff), static_cast<value_type>((d & 0xff00) >> 8),


static_cast<value_type>((d & 0xff0000) >> 16), static_cast<value_type>((d & 0xff000000) >> 24),
}};
}

template<>
struct md5_step<64, 0> {
static constexpr md5_type do_step(const char *, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
return make_md5_result(a + 0x67452301, b + 0xefcdab89, c + 0x98badcfe, d + 0x10325476);
}
};

template<size_t n>
struct md5_step<n, 3> {
static constexpr md5_type do_step(const char *data, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
return md5_step<n + 1, (n + 1) % 4>::do_step(data, a, step(md5_functions[n / 16], b, c, d, a, data32(data,
md5_indexes[n]), md5_constants[n], md5_shift[n]), c, d);
}
};

template<size_t n>
struct md5_step<n, 2> {
static constexpr md5_type do_step(const char *data, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
return md5_step<n + 1, (n + 1) % 4>::do_step(data, a, b, step(md5_functions[n / 16], c, d, a, b, data32(data,
md5_indexes[n]), md5_constants[n], md5_shift[n]), d);
}
};

template<size_t n>
struct md5_step<n, 1> {
static constexpr md5_type do_step(const char *data, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
return md5_step<n + 1, (n + 1) % 4>::do_step(data, a, b, c, step(md5_functions[n / 16], d, a, b, c, data32(data,
md5_indexes[n]), md5_constants[n], md5_shift[n]));
}
};

template<size_t n>
struct md5_step<n, 0> {
static constexpr md5_type do_step(const char *data, uint32_t a, uint32_t b, uint32_t c, uint32_t d) {
return md5_step<n + 1, (n + 1) % 4>::do_step(data, step(md5_functions[n / 16], a, b, c, d, data32(data,
md5_indexes[n]), md5_constants[n], md5_shift[n]), b, c, d);
}
};

template<size_t n>
constexpr md5_type md5(const char (&data)[n]) {
return md5_step<0, 0>::do_step(make_buffer(data).data(), 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476);
}

} // namespace ConstexprHashes
#endif //CONSTEXPR_HASH_MD5_H

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
auto hash = ConstexprHashes::md5("SVCE indore");
cout << hex;
for (auto i : hash) {
cout << (static_cast<int>(i) & 0xff);
}
cout << endl;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy