Cns Manual No Source Code
Cns Manual No Source Code
Mandal’s
Maharashtra Institute of Technology, Aurangabad
Department of Computer Science and Engineering
LAB MANUAL
CSE402: Cryptography and Network Security
(2019-20 Part-I)
Vision
To develop the department as a center of excellence in the field of computer
science and engineering by imparting knowledge & training to the students for
meeting growing needs of the industry & society.
Mission
Providing quality education through a well-designed curriculum in tune with the
challenging needs of software industry by providing state of the art facilities and
to impart knowledge in the thrust areas of computer science and engineering.
1
Program Educational Objectives
PEO1: To prepare the students to achieve success in Computing Domain to create
individual careers, innovations or to work as a key contributor to the private or
Government sector and society.
PEO2: To develop the ability among the students to understand Computing and
mathematical fundamentals and apply the principles of Computer Science for
analyzing, designing and testing software for solving problems.
PEO3: To empower the students with ability to quickly reflect the changes in the
new technologies in the area of computer software, hardware, networking and
database management.
PEO4: To promote the students with awareness for lifelong learning, introduce
them to professional practice, ethics and code of professionalism to remain
continuous in their profession and leaders in technological society.
PSO1: Identify appropriate data structures and algorithms for a given contextual
problem and develop programs to design and implement web applications.
PSO3: Design and manage the large databases and develop their own databases to
solve real world problems and to design, build, manage networks and apply
wireless techniques in mobile based applications.
PSO3: Design a variety of computer-based components and systems using
computer hardware, system software, systems integration process and use standard
testing tools for assuring the software quality.
Program Outcomes
Mapping
Experiment
Blooms Level Mapping To CO Mapping To PO
No.
1 3 CO2 2,5
2 3 CO2 2,5
3 3 CO2 2,5
4 3 CO2 2,5
5 3 CO3 5
6 3 CO3 5
7 3 CO3 5
8 3 CO4 5
9 3 CO5 6
10 2 CO6 5
G.S. MANDAL’S
MAHARASHTRA INSTITUTE OF TECHNOLOGY, AURABGABAD
LAB WORK INSTRUCTION SHEET
Index
Contents Page No.
Vision Mission i
Program Educational Objectives ii
Program Specific Objectives ii
Program Outcomes iii
Course Outcomes iv
Mapping iv
5 User A want to send the message “Meet me very urgently” to user B by 22-29
receiver end.
v
Asymmetric Key Cryptography by using RSA algorithms send message
receiver side.
Experiment#1
Outcomes: Students are able to apply there knowledge during the programming.
Theory:
A monoalphabetic substitution cipher, also known as a simple substitution cipher, relies on a fixed
replacement structure. That is, the substitution is fixed for each letter of the alphabet. Thus, if "a" is
encrypted to "R", then every time we see the letter "a" in the plaintext, we replace it with the letter
A simple example is where each letter is encrypted as the next letter in the alphabet: "a simple
manually, it is easiest to generate the cipher text alphabet first, and encrypt by comparing this to
The cipher text alphabet for the cipher where you replace each letter by the next letter in the
alphabet
Assessment Questions:
Theory: It is one of the simplest encryption technique in which each character in plain text is replaced by a
character some fixed number of positions down to it.
For example, if key is 3 then we have to replace character by another character that is 3 position down to it. Like
A will be replaced by D, C will be replaced by F and so on.
Outcomes: Student will able to apply this method for encryption of text
Theory:
The Affine cipher is a type of monoalphabetic substitution cipher, wherein each letter in an
alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and
converted back to a letter. The formula used means that each letter encrypts to one other letter,
and back again, meaning the cipher is essentially a standard substitution cipher with a rule
cipher, the letters of an alphabet of size m are first mapped to the integers in the range 0 … m-1.
The ‘key’ for the Affine cipher consists of 2 numbers, we’ll call them a and b. The following
Assessment Questions:
Objective: Student will able to a program to implement Rail fence Cipher encryption
Theory:
The railfence cipher is a very simple, easy to crack cipher. It is a transposition cipher that
follows a simple rule for mixing up the characters in the plaintext to form the ciphertext. The
railfence cipher offers essentially no communication security, and it will be shown that it can be
easily broken even by hand.
Although weak on its own, it can be combined with other ciphers, such as a substitution cipher, the
combination of which is more difficult to break than either cipher on it's own.
Many websites claim that the rail-fence cipher is a simpler "write down the columns, read along the
rows" cipher. This is equivalent to using an un-keyed columnar transposition cipher.
Example
The key for the railfence cipher is just the number of rails. To encrypt a piece of text, e.g.
d . . . n . . . e . . . t . . . l . . . h . . . s .....
.e.e.d.h.e.s.w.l.o.t.e.a.te
..f...t...a...a...f...c...l
dnetlhseedheswloteateftaafcl
With a key of 4:
d . . . . . t . . . . . t . . . . . f . . . . . s ..
.e...d.h...s.w...o.t...a.t
..f.n...e.a...a.l...h.c...l
. . . e . . . . . e . . . . . l . . . . . e.........e
dttfsedhswotatfneaalhcleelee
Assessment Questions:
using DES algorithms encrypt it at sender end and decrypt it at receiver end.
Outcomes: Student will able to apply this algo to encrypt the text
Theory:
The Data Encryption Standard (DES) is a symmetric-key block cipher published by the National
Institute of Standards and Technology (NIST).
DES is an implementation of a Feistel Cipher. It uses 16 round Feistel structure. The block size is
64-bit. Though, key length is 64-bit, DES has an effective key length of 56 bits, since 8 of the 64 bits
of the key are not used by the encryption algorithm (function as check bits only). General Structure
of DES is depicted in the following illustration −
Since DES is based on the Feistel Cipher, all that is required to specify DES is −
Round function
Key schedule
The initial and final permutations are straight Permutation boxes (P-boxes) that are inverses
of each other. They have no cryptography significance in DES. The initial and final
permutations are shown as follows −
Round Function
The heart of this cipher is the DES function, f. The DES function applies a 48-bit key to the
rightmost 32 bits to produce a 32-bit output.
Expansion Permutation Box − Since right input is 32-bit and round key is a 48-bit, we
first need to expand right input to 48 bits. Permutation logic is graphically depicted in
the following illustration −
The graphically depicted permutation logic is generally described as table in DES
specification illustrated as shown −
XOR (Whitener). − After the expansion permutation, DES does XOR operation on the
expanded right section and the round key. The round key is used only in this
operation.
Substitution Boxes. − The S-boxes carry out the real mixing (confusion). DES uses
8 S- boxes, each with a 6-bit input and a 4-bit output. Refer the following illustration
−
Key Generation
The round-key generator creates sixteen 48-bit keys out of a 56-bit cipher key. The process of
key generation is depicted in the following illustration −
The logic for Parity drop, shifting, and Compression P-box is given in the DES description.
DES Analysis
The DES satisfies both the desired properties of block cipher. These two properties make cipher
very strong.
Avalanche effect − A small change in plaintext results in the very grate change in
the ciphertext.
DES has proved to be a very well designed block cipher. There have been no significant
cryptanalytic attacks on DES other than exhaustive key search.
Assessment Questions:
Aim: User C want to send message “welcome to cse” to user D by using AES
Theory:
The more popular and widely adopted symmetric encryption algorithm likely to be encountered
nowadays is the Advanced Encryption Standard (AES). It is found at least six time faster than triple
DES.
A replacement for DES was needed as its key size was too small. With increasing computing
power, it was considered vulnerable against exhaustive key search attack. Triple DES was
designed to overcome this drawback but it was found slow.
The features of AES are as follows −
Operation of AES
Interestingly, AES performs all its computations on bytes rather than bits. Hence, AES treats the
128 bits of a plaintext block as 16 bytes. These 16 bytes are arranged in four columns and four
rows for processing as a matrix −
Unlike DES, the number of rounds in AES is variable and depends on the length of the key. AES
uses 10 rounds for 128-bit keys, 12 rounds for 192-bit keys and 14 rounds for 256-bit keys. Each of
these rounds uses a different 128-bit round key, which is calculated from the original AES key.
Theory:
to DES Encryption Technique. It is significantly faster than DES and provides a good encryption
rate
with no effective cryptanalysis technique found to date. It is one of the first, secure block cyphers
not subject to any patents and hence freely available for anyone to use.
1. blockSize: 64-bits
2. keySize: 32-bits to 448-bits variable size
3. number of subkeys: 18 [P-array]
4. number of rounds: 16
1. Key-expansion
2. Data Encryption
Key-expansion:
It will converts a key of at most 448 bits into several subkey arrays totaling 4168 bytes. Blowfish
uses large number of subkeys.
P1,P2,…...........,P18
S1,0, S1,1,….......S1,255
S2,0, S2,1,…........S2,255
S3,0, S3,1,…........S3,255
S4,0, S4,1,............S4,255
Generating the Subkeys: The subkeys are calculated using the Blowfish algorithm:
1. Initialize first the P-array and then the four S-boxes, in order, with a fixed string. This string
consists of the hexadecimal digits of pi (less the initial 3): P1 = 0x243f6a88, P2 =
0x85a308d3, P3 = 0x13198a2e, P4 = 0x03707344, etc.
2. XOR P1 with the first 32 bits of the key, XOR P2 with the second 32-bits of the key, and so on
for all bits of the key (possibly up to P14). Repeatedly cycle through the key bits until the
entire P-array has been XORed with key bits. (For every short key, there is at least one
equivalent longer key; for example, if A is a 64-bit key, then AA, AAA, etc., are equivalent
keys.)
3. Encrypt the all-zero string with the Blowfish algorithm, using the subkeys described in steps
(1) and (2).
4. Replace P1 and P2 with the output of step (3).
5. Encrypt the output of step (3) using the Blowfish algorithm with the modified subkeys.
6. Replace P3 and P4 with the output of step (5).
7. Continue the process, replacing all entries of the P array, and then all four S-boxes in order,
with the output of the continuously changing Blowfish algorithm.
In total, 521 iterations are required to generate all required subkeys. Applications can store the
subkeys rather than execute this derivation process multiple times.
Data Encryption:
xR = F(XL) XOR Xr
Swap XL and xR
xR = xR XOR P17
xL = xL XOR P18
Recombine xL and xR
Fig 2: Blowfish Encryption
Assessment Questions:
Aim: user A want to communicate to user B but they want to user Asymmetric
Theory:
works on two different keys i.e. Public Key and Private Key. As the name describes that the Public
2. The server encrypts the data using client’s public key and sends the encrypted data.
Since this is asymmetric, nobody else except browser can decrypt the data even if a third party has
The idea of RSA is based on the fact that it is difficult to factorize a large integer. The public key
consists of two numbers where one number is multiplication of two large prime numbers. And
private key is also derived from the same two prime numbers. So if somebody can factorize the
large number, the private key is compromised. Therefore encryption strength totally lies on the key
size and if we double or triple the key size, the strength of encryption increases exponentially. RSA
keys can be typically 1024 or 2048 bits long, but experts believe that 1024 bit keys could be broken
RSA is one of the first practical public-key cryptosystems and is widely used for secure data
transmission. In such a cryptosystem, the encryption key is public and different from the decryption
key which is kept secret (private). In RSA, this asymmetry is based on the practical difficulty of
factoring the product of two large prime numbers, the factoring problem. RSA is made of the initial
letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who first publicly
described the algorithm in 1978. Clifford Cocks, an English mathematician working for the UK
intelligence agency GCHQ, had developed an equivalent system in 1973, but it was not declassified
until 1997.[1] A user of RSA creates and then publishes a public key based on two large prime
numbers, along with an auxiliary value. The prime numbers must be kept secret. Anyone can use
the public key to encrypt a message, but with currently published methods, if the public key is large
enough, only someone with knowledge of the prime numbers can feasibly decode the message.[2]
Breaking RSA encryption is known as the RSA problem; whether it is as hard as the factoring
problem remains an open question. RSA is a relatively slow algorithm, and because of this it is less
commonly used to directly encrypt user data. More often, RSA passes encrypted shared keys for
symmetric key cryptography which in turn can perform bulk encryption-decryption operations at
Operation
The RSA algorithm involves four steps: key generation, key distribution, encryption and decryption.
A basic principle behind RSA is the observation that it is practical to find three very large positive
integers e, d and n such that with modular exponentiation for all integer m: and that even knowing
and n or even m it can be extremely difficult to find d. Additionally, for some operations it is
convenient that the order of the two exponentiations can be changed and that this relation also
implies: RSA involves a public key and a private key. The public key can be known by everyone and
is
used for encrypting messages. The intention is that messages encrypted with the public key
can only be decrypted in a reasonable amount of time using the private key. The public key is
represented by the integers n and e; and, the private key, by the integer d (although n is also
used during the decryption process; so, it might be considered a part of the private key, too).
m represents the message (previously prepared with a certain technique explained below).
Key generation
The keys for the RSA algorithm are generated the following way:
2. Compute n = pq.
o n is used as the modulus for both the public and private keys. Its length, usually
expressed in bits, is the key length.
4. Choose an integer e such that 1 < e < λ(n) and gcd(e, λ(n)) = 1; i.e., e and λ(n) are
coprime.
5. Determine d as d ≡ e−1 (mod λ(n)); i.e., d is the modular multiplicative inverse of e (modulo
λ(n)).
This is more clearly stated as: solve for d given d⋅e ≡ 1 (mod λ(n)).
e having a short bit-length and small Hamming weight results in more efficient
encryption – most commonly e = 216 + 1 = 65,537. However, much smaller values of e
(such as 3) have been shown to be less secure in some settings. [14]
The public key consists of the modulus n and the public (or encryption) exponent e. The
private key consists of the modulus n and the private (or decryption) exponent d, which must
be kept secret. p, q, and λ(n) must also be kept secret because they can be used to calculate
d.
Alternatively, as in the original RSA paper,[2] the Euler totient function φ(n) = (p − 1)(q − 1)
can
be used instead of λ(n) for calculating the private exponent d. This works because φ(n) is
group of
integers modulo pq), and thus any d satisfying d⋅e ≡ 1 (mod φ(n)) also satisfies d⋅e ≡ 1 (mod
λ(n)). However, computing d modulo φ(n) will sometimes yield a result that is larger than
necessary (i.e. d > λ(n)). Most RSA implementations will accept exponents generated using either
method (if they use the private exponent d at all, rather than using the optimized decryption method
based on the Chinese remainder theorem described below), but some standards like FIPS 186-4
may require that d < λ(n). Any "oversized" private exponents not meeting that criterion may
always be reduced modulo λ(n) to obtain a smaller equivalent exponent.
Note: The authors of the original RSA paper carry out the key generation by choosing d and
then computing e as the modular multiplicative inverse of d (modulo φ(n)). Since it is beneficial
to use a
small value for e (i.e. 65,537) in order to speed up the encryption function, current implementations
Key distribution
Suppose that Bob wants to send a secret message to Alice. If they decide to use RSA, Bob must
know Alice's public key to encrypt the message and, Alice must use her private key to decrypt the
message. To enable Bob to send his encrypted messages, Alice transmits her public key ( n, e) to
Bob via a reliable, but not necessarily secret route. Alice's private key ( d), is never distributed.
Key Genration :
b) Encryption :
c) Decryption:
Ciphertext: C
Plaintext : M= Cd mod n
ed = 1 mod (n)
d = e−1
mod (n)
6.Example:
Key Generation :
1. Select 2 prime numbers -> p=17 and q=11
3. Calculate = 16 × 10= 160 Select ‘e’ such that e is relatively prime to (n)=160 and e
<
4. Determine d such that :
de =1 mod (n)
d × 7 = 1 mod 160
161
PU = {7, 187 }
PR = {23, 187 }
C=887mod(187)88mod187=88882mod187=7744mod187=77884mod187=59969536mod187=
132
887mod187
=(884mod187)×(882mod187)×(88mod187)mod187=(132×77×88)mod187=894432mod187=11
1.
For Decryption :
M=Cdmod187=1123mod187111mod187=11112mod187=121114mod187=14641/187=55118
mod187=214358881mod187=331123mod187
=(118mod187×118mod187×114mod187×112mod187×111mod187)mod187=(33×33×55×81×1
1)mod187=79720245mod187=88
Assessment Questions:
Theory:
SHA-1 or Secure Hash Algorithm 1 is a cryptographic hash function which takes an input and
produces a 160-bit (20-byte) hash value. This hash value is known as a message digest. This
message digest is usually then rendered as a hexadecimal number which is 40 digits long. It is a
U.S. Federal Information Processing Standard and was designed by the United States National
Security Agency.
SHA-1 is now considered insecure since 2005. Major tech giants browsers like Microsoft, Google,
Apple and Mozilla have stopped accepting SHA-1 SSL certificates by 2017.
Experiment#10
Theory:
The code to generate Public-Private Key Pair is identical to the one used in Asymmetric
Cryptography example, please refer to Step 1 or download the source code at the end of the article
that includes all sources
2. Sign the message
Next we have to write our message and then sign it. The message and the signature can be separate
files but in our example we add them to a List of byte[] and write them as Object to the file.
Message.java
package com.mkyong.sender;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
//The constructor of Message class builds the list that will be written to the file.
//The list consists of the message and the signature.
public Message(String data, String keyFile) throws InvalidKeyException, Exception {
list = new ArrayList<byte[]>();
list.add(data.getBytes());
list.add(sign(data, keyFile));
}
//The method that signs the data using the private key that is stored in keyFile path
public byte[] sign(String data, String keyFile) throws InvalidKeyException, Exception{
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(getPrivate(keyFile));
rsa.update(data.getBytes());
return rsa.sign();
}
Output:
The receiver has the file (he knows it is a List of 2 byte arrays; the message and the signature) and
wants to verify that the message comes from the expected source with a pre-shared Public Key.
VerifyMessage.java
package com.mkyong.receiver;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.List;
@SuppressWarnings("unchecked")
//The constructor of VerifyMessage class retrieves the byte arrays from the File
//and prints the message only if the signature is verified.
public VerifyMessage(String filename, String keyFile) throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
this.list = (List<byte[]>) in.readObject();
in.close();
//Method for signature verification that initializes with the Public Key,
//updates the data to be verified and then verifies them using the signature
private boolean verifySignature(byte[] data, byte[] signature, String keyFile) throws Exception {
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(getPublic(keyFile));
sig.update(data);
return sig.verify(signature);
}
//Method to retrieve the Public Key from a file
public PublicKey getPublic(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
Output:
VERIFIED MESSAGE
Assessment Questions: