Cns Lab Manual 2024-25
Cns Lab Manual 2024-25
Cns Lab Manual 2024-25
Intoduction to Lab:
Cryptography is the study and application of techniques that hide the real meaning of information
by transforming it into nonhuman readable formats and vice versa.
Applications of Cryptography:
Cryptography finds use in many areas, ranging from safety in payment portals, to secure messaging
platforms like WhatsApp. A few of those applications are as follows -
3. Hashing
Symmetric key cryptography is the category where the same key is used for both the encryption
and decryption of information.
Example:
Block Ciphers - The plaintext is broken down into blocks/chunks of data encrypted
individually and later chained together.
The most widely used Symmetric Key Algorithms are AES (Advanced Encryption Standard),
DES (Data Encryption Standard), 3DES (Triple DES), Twofish, etc.
In asymmetric key cryptography, there are two keys at play. A public key and a private key. The
public key is used to encrypt the data pre-transit, and the private key is used to decrypt the data
post-transit.
Example:
RSA encryption is the most widely used asymmetric encryption standard today. Named after its
founders (Rivest, Shamir, and Adleman), it uses block ciphers that separate the data into blocks
and obscure the information.
3. Hashing
Hashing is the branch of cryptography that scrambles data beyond recognition. However, unlike
symmetric and asymmetric key cryptography, hashing isn’t designed to be reversible. It gives an
output of a fixed size, known as the hash value of the original data.
You can use hash functions to scramble the data. They are not reversible and the output size of a
hash function is always the same, irrespective of the size of the plaintext.
Cryptography Primitives
Cryptography primitives are nothing but the tools and techniques in Cryptography that can be
selectively used to provide a set of desired security services −
Encryption
Hash functions
Digital Signatures
The following table shows the primitives that can achieve a particular security service on their
own
AIM: Write a C program that contains a string (char pointer) with a value \Hello World’. The
program should XOR each character in this string with 0 and display the result.
PROGRAM:
#include <stdio.h>
int main() {
// Print the result (which should be the same as the original character)
printf("%c", result);
return 0;
Output:
Hello World
AIM: Write a C program that contains a string (char pointer) with a value \Hello World’. The
program should AND or and XOR each character in this string with 127 and display the result.
PROGRAM:
#include <stdio.h>
int main() {
printf("\n");
return 0;
Explanation:
1. String Definition: We define a string str with the value "Hello World".
2. AND Operation: We loop through each character in the string, apply the bitwise AND
(&) operation with 127 (binary: 01111111), and print the result.
3. XOR Operation: We then apply the bitwise XOR (^) operation with 127 and print the
result.
Bitwise Operations:
AND with 127 (& 127): The binary value 127 is 01111111 (7 bits set to 1 and the 8th bit
set to 0), which essentially keeps the lower 7 bits of each character unchanged, clearing
the 8th bit (if it was set).
XOR with 127 (^ 127): The XOR operation toggles the 7 lower bits of each character, so
characters will be changed depending on their original values.
Output:
Hello World
? `j j p E d q j p
AIM: Write a Java program to perform encryption and decryption using the following
algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher
It is introduced by Julius cipher.It is one of the simplest and most used encryption techniques.
In this technique, each letter of the given text is replaced by a letter of some fixed number of
positions down the alphabet.
For example, with a shift of 1, X would be replaced by Y, Y would become Z, and so on. Julius
Caesar was the first one who used it for communicating with his officials. Based on his name,
this technique was named as Caesar Cipher technique.
An integer value is required to cipher a given text. The integer value is known as shift, which
indicates the number of positions each letter of the text has been moved down.
ABCDEFGHIJKLMNOPQRSTUVWXYZ
DEFGHIJKLMNOPQRSTUVWXYZABC
1.Encryption :
It’s a process of encoding a message using an encryption algorithm that can only be accessed via
an authorized person.
2.Decryption :
3.Plaintext :
The message which needs to get to the end user, might or might not be formatted.
4.Ciphertext :
The text that results after an encryption algorithm is applied to the plaintext.
5.Shift :
Integer between 0-25 0−25 which tells us the number of shifts to be applied on a character.
Program:
import java.util.Scanner;
char c = text.charAt(i);
if (Character.isUpperCase(c)) {
else if (Character.isLowerCase(c)) {
encrypted.append(c);
return encrypted.toString();
char c = text.charAt(i);
if (Character.isUpperCase(c)) {
else if (Character.isLowerCase(c)) {
decrypted.append(c);
return decrypted.toString();
scanner.close();
Output:
In a Substitution cipher, any character of plain text from the given fixed set of characters is
substituted by some other character from the same set depending on a key. For example with a
shift of 1, A would be replaced by B, B would become C, and so on.
Program:
import java.io.*;
import java.util.Scanner;
if (Character.isLowerCase(c))
encrypted.append(key.charAt(c - 'a'));
else if (Character.isUpperCase(c))
encrypted.append(Character.toUpperCase(key.charAt(c - 'A')));
else encrypted.append(c);
return encrypted.toString();
if (Character.isLowerCase(c))
decrypted.append(alphabet.charAt(key.indexOf(c)));
else if (Character.isUpperCase(c))
decrypted.append(Character.toUpperCase(alphabet.charAt(key.indexOf(Character.toLowerCase(
c)))));
else decrypted.append(c);
return decrypted.toString();
sc.close();
Output:
In classical cryptography, the hill cipher is a polygraphic substitution cipher based on Linear
Algebra. It was invented by Lester S. Hill in the year 1929. In simple words, it is a cryptography
algorithm used to encrypt and decrypt data for the purpose of data security.
The algorithm uses matrix calculations used in Linear Algebra. It is easier to understand if we
have the basic knowledge of matrix multiplication, modulo calculation, and the inverse
calculation of matrices.
In hill cipher algorithm every letter (A-Z) is represented by a number moduli 26. Usually, the
simple substitution scheme is used where A = 0, B = 1, C = 2…Z = 25 in order to use 2x2 key
matrix.
1.Encryption:
To encrypt the text using hill cipher, we need to perform the following operation.
E(K, P) = (K * P) mod 26
Where K is the key matrix and P is plain text in vector form. Matrix multiplication of K and P
generates the encrypted ciphertext.
2. Decryption:
To encrypt the text using hill cipher, we need to perform the following operation.
Where K is the key matrix and C is the ciphertext in vector form. Matrix multiplication of inverse
of key matrix K and ciphertext C generates the decrypted plain text.
Program:
import java.util.ArrayList;
import java.util.Scanner;
double sq = Math.sqrt(key.length());
int k = 0;
k++;
return keyMatrix;
if(det == 0) {
// This method checks if the reverse key matrix is valid (matrix mod26 = (1,0,0,1)
// Find the product matrix of key matrix times reverse key matrix
int factor;
// factor*det = 1 mod 26
if((detmod26 * factor) % 26 == 1)
break;
// Calculate the reverse key matrix elements using the factor found
return reverseMatrix;
int i;
System.out.print(label);
if(i+2 <phrase.size()) {
System.out.print("-");
System.out.println();
int i;
int[][] keyMatrix;
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();
if(phrase.length() % 2 == 1) {
phrase += "Q";
keyMatrix = getKeyMatrix();
isValidMatrix(keyMatrix);
// Find the product per pair of the phrase with the key matrix modulo 26
phraseEncoded.add(alphaZero ? x : (x == 0 ? 26 : x ));
phraseEncoded.add(alphaZero ? y : (y == 0 ? 26 : y ));
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();
keyMatrix = getKeyMatrix();
isValidMatrix(keyMatrix);
revKeyMatrix = reverseMatrix(keyMatrix);
isValidReverseMatrix(keyMatrix, revKeyMatrix);
// Find the product per pair of the phrase with the reverse key matrix modulo 26
//main method
byte[] p;
System.out.println("-------------------------");
System.out.println();
System.out.println();
opt = sc.nextLine();
switch (opt)
case "1":
phrase = sc.nextLine();
encrypt(phrase, true);
break;
case "2":
phrase = sc.nextLine();
decrypt(phrase, true);
break;
case "3":
phrase = sc.nextLine();
encrypt(phrase, false);
break;
case "4":
phrase = sc.nextLine();
decrypt(phrase, false);
break;
Output:
DES stands for Data Encryption Standard. It is a symmetric-key block cipher algorithm used to
encrypt and decrypt data. It is developed by the IBM team in early 1970. It accepts the plaintext
in 64-bit blocks and changes it into the ciphertext that uses the 64-bit keys to encrypt the data. The
algorithm uses the same key to encrypt and decrypt the data.
It is based on LUCIFER (also known as Feistel block cipher algorithm) which is a direct
predecessor of the DES algorithm. It is developed by eminent scholar and researcher Horst
Feistel at IBM. It provides high security by using a 128-bit key block and a 128-bit block size. The
DES algorithm uses the 16 rounds of the Feistel structure. The structure uses a unique key for each
round. Finally, in 1976, it was approved by the federal encryption standard.
Program:
import java.awt.datatransfer.StringSelection;
import java.io.DataInputStream;
/*
3},{ 3, 1, 3, 2}};
2},{ 2, 1, 0, 3}};
/*
*/
int y=0;
//System.out.println(Integer.toBinaryString(x));
/*
String binary=Integer.toBinaryString(x);
*/
for(int i=0;i<p.length;i++) {
// br.setCharAt(i, binary.charAt(p[i]-1));
y=y<<1;
y=y|(x>>(pmax-p[i]))&1;
//System.out.println("Final :"+Integer.toBinaryString(y));
return y;
t0 = S0[ ((t0 & 0x8) >> 2) | (t0 & 1) ][ (t0 >> 1) & 0x3 ];
t1 = S1[ ((t1 & 0x8) >> 2) | (t1 & 1) ][ (t1 >> 1) & 0x3 ];
return t;
/*
*/
printData( m, 8);
m = fK( m, K1);
printData( m, 8);
m = SW( m);
printData( m, 8);
m = fK( m, K2);
printData( m, 8);
return (byte) m;
/*
*/
printData( m, 8);
printData( m, 8);
m = fK( m, K2);
printData( m, 8);
m = SW( m);
printData( m, 8);
m = fK( m, K1);
printData( m, 4);
printData( m, 8);
return (byte) m;
mask >>= 1;
/*
*/
public SDES( int K) //COnstructor generates key k1 & k2 used for encyption
@SuppressWarnings("deprecation")
int K = Integer.parseInt(inp.readLine(),2);
m = A.encrypt( m);
SDES.printData( m, 8);
m = A.decrypt( m);
SDES.printData( m, 8);
Output:
1. blockSize: 64-bits
4. number of rounds: 16
Program:
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
/**
*/
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
cipher.init(Cipher.ENCRYPT_MODE, KS);
encodeToString(cipher.doFinal(password.getBytes("UTF-8")));
return encryptedtext;
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
decode(encryptedtext);
cipher.init(Cipher.DECRYPT_MODE, KS);
String decryptedString =
return decryptedString;
}}
Output:
The AES Encryption algorithm (also known as the Rijndael algorithm) is a symmetric block
cipher algorithm with a block/chunk size of 128 bits.
It is not a Feistel cipher. – It works in parallel over the whole input block.
variety of platforms.
Each round (except the last one) is a uniform and parallel composition
of 4 steps
• ShiftRows (a permutation, which cyclically shifts the last three rows in the State)
• MixColumns (substitution that uses Galois Fields, corps de Galois, GF(28) arithmetic)
Program:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
/* Encryption Method */
try
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
return null;
/* Decryption Method */
try
return null;
/* Driver Code */
/* Message to be encrypted. */
/* Display the original message, encrypted message and decrypted message on the console.
*/
Output:
7. Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello world”
using Blowfish. Create your own key using Java key tool.
RC4 is a symmetric stream cipher and variable key length algorithm. This symmetric key
algorithm is used identically for encryption and decryption such that the data stream is
simply XORed with the generated key sequence. The algorithm is serial as it requires successive
exchanges of state entries based on the key sequence. The algorithm works in two phases:
The state vector is identified as S[0], S[1]…. S[255] is initialized with {0, 1, 2, …, 255}.
The key K[0], K[1], …., K[255] can be of any length from 0 to 256 bytes and is used to
initialize permutation S. Each K[I] and S[I] is a byte.
K is a temporary array if the length of the key is 256 bytes copy it to K else after copying
the remaining positions of K are filled with repeated Key Values until full.
Program:
import java.io.*;
class rc4
int temp=0;
String ptext;
String key;
ptext=in.readLine();
key=in.readLine();
char ptextc[]=ptext.toCharArray();
char keyc[]=key.toCharArray();
for(int i=0;i<ptext.length();i++) {
ptexti[i]=(int)ptextc[i]; }
for(int i=0;i<key.length();i++) {
keyi[i]=(int)keyc[i]; }
for(int i=0;i<255;i++) {
s[i]=i;
k[i]=keyi[i%key.length()]; }
int j=0;
for(int i=0;i<255;i++) {
j=(j+s[i]+k[i])%256;
temp=s[i];
s[i]=s[j];
s[j]=temp; }
int i=0;
j=0;
int z=0;
for(int l=0;l<ptext.length();l++) {
i=(l+1)%256;
j=(j+s[i])%256;
temp=s[i];
s[i]=s[j];
s[j]=temp;
z=s[(s[i]+s[j])%256];
cipher[l]=z^ptexti[l];
decrypt[l]=z^cipher[l];
System.out.print(“\n\nENCRYPTED:\t\t”);
display(cipher);
System.out.print(“\n\nDECRYPTED:\t\t”);
display(decrypt);
for(int l=0;l<disp.length;l++)
convert[l]=(char)disp[l];
System.out.print(convert[l]);
} /*
Output:
Example:
But e Must be
-An integer.
-Not be a factor of n.
2. Compute n = p*q
3. Compute ϕ(n) = (p – 1) * (q – 1)
Program:
import java.math.*;
import java.util.*;
class RSA {
int p, q, n, z, d = 0, e, i;
double c;
BigInteger msgback;
p = 3;
q = 11;
n = p * q;
z = (p - 1) * (q - 1);
if (gcd(e, z) == 1) {
break;
int x = 1 + (i * z);
if (x % e == 0) {
d = x / e;
break;
c = (Math.pow(msg, e)) % n;
BigInteger N = BigInteger.valueOf(n);
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
+ msgback);
if (e == 0)
return z;
else
}}
Output:
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
The Diffie-Hellman algorithm was first published in 1976, and it has become a staple for any kind of
cryptography. Whenever we use cryptography, we usually need to have a symmetric key, and to get that,
we have to perform some kind of Diffie-Hellman.
Program:
Index.html:
<!DOCTYPE HTML>
<html>
<body>
<h1>Diffie Hellman</h1>
<br>
<br>
<div id="generate-shared-key">
</div>
<br>
<br>
<div >
</div>
<br>
<br>
<div id="generate-secret-key">
<div >
</div >
<div>
<br>
<br>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/diffie-hellman.js"></script>
</body>
</html>
Diffie-hellman.js:
var diffieHellman = {
},
},
$(document).ready(function() {
var apps = {
unit_testing: function(prime,base,a,b){
var s1 = diffieHellman.getSKDH(prime,a,public_key_b);
var s2 = diffieHellman.getSKDH(prime,b,public_key_a);
},
generatePublicKey: function(){
$('#shared-key').val(diffieHellman.getPKDH(shared_prime,shared_base,shared_integer));
},
generateSharedSecret: function(){
$('#secret-
key').val(diffieHellman.getSKDH(secret_prime,secret_integer,secret_shared));
},
};
});
Output:
10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
SHA is an abbreviation for Secure Hash Algorithm. In Java SHA and is one of the most
prevalent cryptographic hash functions. A cryptographic hash can be used to create a text signature
or data file. Now, SHA is nothing but a cryptographic hash function that takes input as much as
20 bytes long and returns a hexadecimal hash value which is approximately 40 digits in length.
The SHA-256 algorithm is capable of producing nearly a unique, non-static 256-bit (i.e., 32-byte)
hash value. But the point to remember is that this function is only a one-way function, i.e., the
result it produces cannot be decrypted back to its original value.
Java provides a class named MessageDigest which belongs to the package java.security. This
class supports algorithms such as SHA-1, SHA 256, MD5 algorithms to convert an arbitrary
length message to a message digest.
To convert a given message to a message digest, follow the steps given below −
The MessageDigest class provides a method named getInstance(). This method accepts a String
variable specifying the name of the algorithm to be used and returns a MessageDigest object
implementing the specified algorithm.
MessageDigest md = MessageDigest.getInstance("SHA-256");
After creating the message digest object, you need to pass the message/data to it. You can do so
using the update() method of the MessageDigest class, this method accepts a byte array
representing the message and adds/passes it to the above created MessageDigest object.
md.update(msg.getBytes());
You can generate the message digest using the digest() method od the MessageDigest class this
method computes the hash function on the current object and returns the message digest in the
form of byte array.
Program:
import java.security.MessageDigest;
import java.util.Scanner;
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(message.getBytes());
System.out.println(digest);
Output:
[B@55f96302
11. Calculate the message digest of a text using the MD5 algorithm in JAVA.
MD5 (Message Digest Method 5) is a cryptographic hash algorithm used to generate a 128-bit
digest from a string of any length. It represents the digests as 32 digit hexadecimal numbers.
The digest size is always 128 bits, and thanks to hashing function guidelines, a minor change in
the input string generate a drastically different digest. This is essential to prevent similar hash
generation as much as possible, also known as a hash collision.
Program:
import java.security.*;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
System.out.println();
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
+bytesToHex(output)); System.out.println("");
catch (Exception e)
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
return buf.toString(); } }
Output:
Algorithm = MD5
D41D8CD98F00B204E9800998ECF8427E MD5("abc") =
900150983CD24FB0D6963F7D28E17F72 MD5("abcdefghijklmnopqrstuvwxyz")
= C3FCD3D76192E4007DFB496CCA67E13B