IS Lab Theory
IS Lab Theory
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
displays the result.
In the field of information security, the XOR (Exclusive OR) operation plays a
crucial role due to its unique properties and simplicity. Below are its key uses:
Example:
Ciphertext = Plaintext XOR Key
Plaintext = Ciphertext XOR Key
This property is fundamental in stream ciphers and other
lightweight cryptographic algorithms.
3. Hash Functions
XOR is a building block in hash functions. It is used to combine data inputs and produce a
fixed-size hash value.
For example, XOR is often applied during the mixing or compression steps in hashing
algorithms to ensure data diffusion.
Limitations
On its own, XOR is not secure because it is deterministic and reversible. For robust
encryption, it must be combined with other operations, keys, or algorithms to avoid
vulnerabilities.
Program 2:
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.
o The AND operation (& 127) is used to mask specific bits in data. By ANDing with
127, only the lower 7 bits are preserved, and the most significant bit (MSB) is
cleared.
o The binary representation of 127 is 01111111 (7 bits set to 1).
o Applying & 127 effectively clears the most significant bit (8th bit) of any character.
This confines the result to the lower 7 bits, ensuring the value lies within the ASCII
range (0–127).
o It can be used to strip non-ASCII data from input, ensuring only
standard ASCII characters remain.
o Example Usage:
Sanitizing inputs to ensure only valid ASCII characters are processed.
Stripping metadata or extra bits from communication protocols or file
formats.
Application:
o Ensures the data conforms to a specific standard, such as ASCII, and prevents
unwanted high-bit manipulations that could lead to buffer overflows or encoding
vulnerabilities.
2. OR Operation in Information Security
o The OR operation (| 127) forces certain bits to be set to 1, ensuring the result
matches or exceeds a specific threshold.
o The binary representation of 127 ensures all 7 lower bits are set to 1. Performing |
127 forces these bits to become 1, regardless of their original state.
o The result is always 01111111 for any input (ASCII 127 in decimal, the DEL control
character).
o Example Usage:
Marking data for identification (e.g., adding flags or indicators to characters
or bytes).
Generating consistent high-value identifiers or delimiters for
communication.
Application:
o While not directly secure, it could assist in creating markers or metadata for
encrypted payloads, helping in secure protocol design.
o XOR is extensively used in cryptography due to its reversible property. XORing data
with 127 flips the lower 7 bits, transforming plaintext into a scrambled format.
o Example Usage:
Simple encryption schemes (e.g., stream ciphers or OTP-like techniques).
Obfuscating data to protect sensitive information during transfer or
storage.
Application:
o XOR with 127 can serve as a lightweight obfuscation method. While not secure on
its own, it can act as a step in more complex encryption schemes.
o For example, XOR-based ciphers like RC4 and OTP depend heavily on this reversible
transformation property.
Program 3a:
Write a Java program to perform encryption and decryption using the
following algorithms:
a. Ceaser cipher
The Caesar Cipher shifts each letter in the plaintext by a fixed number of positions in the alphabet.
For example, with a shift of 3:
'A' becomes 'D'
'B' becomes 'E'
Non-alphabetic characters (e.g., spaces, numbers, punctuation) remain unchanged.
Example
Plaintext: HELLO WORLD
Shift: 3
Encryption: KHOOR ZRUOG
Decryption: HELLO WORLD
Encryption Algorithm
Decryption Algorithm
Program 3b:
Write a Java program to perform encryption and decryption using the
following algorithms:
b. Substitution cipher
Program 3c:
import java.io.*;
import java.util.*;
import java.io.*; public
class HillCipher {
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3]; static
float[][] b = new float[3][3]; static
float[][] mes = new float[3][1]; static
float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); static Scanner sc = new
Scanner(System.in);
public static void main(String[] args) throws IOException {
// TODO code application logic
here getkeymes();
for(int i=0;i<3;i++) for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
res[i][j]=res[i][j]+a[i][k]*mes[k][j]; }
System.out.print("\nEncrypted string is :
"); for(int i=0;i<3;i++) {
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
System.out.print("\nDecrypted string is : ");
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
public static void getkeymes() throws IOException {
System.out.println("Enter 3x3 matrix for key (It should be
inversible): ");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = sc.nextFloat();
System.out.print("\nEnter a 3 letter string: ");
String msg = br.readLine();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
}
public static void inverse() {
floatp,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) {
if(i!=k) {
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
} } } }
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\nInverse Matrix is : ");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print(b[i][j] + " ");
System.out.print("\n"); }
} }
DES Encryption
The overall scheme for DES encryption is illustrated in Figure 3.5. As with any
encryption scheme, there are two inputs to the encryption function: the plaintext to be
encrypted and the key. In this case, the plaintext must be 64 bits in length and the
key is 56 bits in length.8
Looking at the left-hand side of the figure, we can see that the processing
of the plaintext proceeds in three phases. First, the 64-bit plaintext passes through
an initial permutation (IP) that rearranges the bits to produce the permuted input.
This is followed by a phase consisting of sixteen rounds of the same function, which
involves both permutation and substitution functions. The output of the last
(sixteenth)
round consists of 64 bits that are a function of the input plaintext and the
key. The left and right halves of the output are swapped to produce the preoutput.
Finally, the preoutput is passed through a permutation [IP -1] that is the inverse of
the initial permutation function, to produce the 64-bit ciphertext. With the exception
of the initial and final permutations, DES has the exact structure of a Feistel
cipher, as shown in Figure 3.3.
The right-hand portion of Figure 3.5 shows the way in which the 56-bit key is
used. Initially, the key is passed through a permutation function. Then, for each of
the sixteen rounds, a subkey (Ki) is produced by the combination of a left circular
shift and a permutation. The permutation function is the same for each round, but a
different subkey is produced because of the repeated shifts of the key bits.
DES Decryption
As with any Feistel cipher, decryption uses the same algorithm as encryption,
except that the application of the subkeys is reversed. Additionally, the initial and
final permutations are reversed.
Program 5:
Write a C/JAVA program to implement the Blowfish algorithm logic.
Description of Algorithm:
Blowfish symmetric block cipher algorithm encrypts block data of 64-bits
at a time. The algorithm follows fiestal network and is divided into 3
main parts:
1. Key-expansion
2. Data Encryption
3. Data Decryption
Key Expansion
Prior to any data encryption and decryption, these keys should be computed before-
hand.
The p-array consists of 18, 32-bit sub-keys:
P1, P2,., P18
Four 32-bit S-Boxes consist of 256 entries each:
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 Sub-keys:
The sub-keys are calculated and generated 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 sub-keys
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 modifed sub-
keys.
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 sub-keys. Applications
can store the sub-keys rather than execute this derivation process multiple times.
Data Encryption
It is having a function to iterate 16 times of network. Each round consists of key-
dependent permutation and a key and data-dependent substitution.
All operations are XORs and additions on 32-bit words. The only additional
operations are four indexed array data lookup tables for each round.
Data Decryption
Decryption is exactly the same as encryption, except that P1, P2 ..... P18 are used in
the reverse order.
Areas Of Applications
A standard encryption algorithm must be suitable for many di
erent applications:
1. Bulk encryption: The algorithm should be efficient in encrypting data files or a
continuous data stream.
2. Random bit generation: The algorithm should be efficient in producing single
random bits.
3. Packet encryption: The algorithm should be efficient in encrypting
packet-sized data. (An ATM packet has a 48- byte data field.) It should
implementable in an application where successive packets may be encrypted or
decrypted with different keys.
4. Hashing: The algorithm should be efficient in being converted to a one-way hash
function.
Program 6:
Write a C/JAVA program to implement the Rijndael algorithm logic.
Figure 5.1 shows the overall structure of the AES encryption process.
The cipher takes a plaintext block size of 128 bits, or 16 bytes. The key length can be
16, 24, or 32 bytes (128, 192, or 256 bits). The algorithm is referred to as AES-128,
AES-192, or AES-256, depending on the key length.
The input to the encryption and decryption algorithms is a single 128-bit block.
this block is depicted as a 4 * 4 square matrix of bytes. This block is copied into the
State array, which is modified at each stage of encryption or decryption. After the
final stage, State is copied to an output matrix. These operations
are depicted in Figure 5.2a.
Similarly, the key is depicted as a square matrix of bytes.
This key is then expanded into an array of key schedule words. Figure 5.2b
shows the expansion for the 128-bit key. Each word is four bytes, and the
total key schedule is 44 words for the 128-bit key. Note that the ordering of
bytes within a matrix is by column. So, for example, the first four bytes of a
128-bit plaintext input to the encryption cipher occupy the first column of the in
matrix, the second four bytes occupy the second column, and so on. Similarly,
the first four bytes of the expanded key, which form a word, occupy the first
column of the w matrix.
The cipher consists of N rounds, where the number of rounds depends on the
key length: 10 rounds for a 16-byte key, 12 rounds for a 24-byte key, and 14
rounds for a 32-byte key (Table 5.1).
Detailed Structure
Figure 5.3 shows the AES cipher in more detail, indicating the sequence of
transformations in each round and showing the corresponding decryption
function.
Program 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 stream cipher that uses a symmetric key to encrypt and decrypt
data.
The key-stream is XORed with the plaintext (or ciphertext) to produce the
ciphertext (or plaintext).
Key Feature:
The process is identical for both encryption and decryption due to the
symmetric nature of XOR.
Blowfish Encryption
Blowfish is a symmetric block cipher that operates on 64-bit blocks and uses
variable key lengths from 32 to 448 bits.
It is fast, secure, and suitable for applications where key reuse is required.
Steps:
Generate a secure key using a key generator.
Encrypt the plaintext using the secret key.
Decrypt the ciphertext to recover the original plaintext.
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
// Encrypt or Decrypt
byte[] outputBytes = cipher.doFinal(text.getBytes());
return Base64.getEncoder().encodeToString(outputBytes);
} catch (Exception e) {
throw new RuntimeException("Error in RC4 encryption/decryption", e);
}
}
// Blowfish Encryption
public static String blowfishEncrypt(String text, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException("Error in Blowfish encryption", e);
}
}
// Blowfish Decryption
public static String blowfishDecrypt(String encryptedText, SecretKey
secretKey) {
try {
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
} catch (Exception e) {
throw new RuntimeException("Error in Blowfish decryption", e);
}
}
public static void main(String[] args) throws Exception {
// Text to encrypt
String text = "Minhaj";
// RC4 Example
String rc4Key = "SampleRC4Key"; // Key for RC4
String rc4Encrypted = rc4EncryptDecrypt(text, rc4Key);
System.out.println("RC4 Encrypted: " + rc4Encrypted);
// Blowfish Example
// Generate a secret key for Blowfish
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128, new SecureRandom()); // 128-bit key
SecretKey blowfishKey = keyGenerator.generateKey();
OUTPUT:
java EncryptionDemo
RC4 Encrypted: jQCI+S6J
Blowfish Encrypted: FybnKd2S1nM=
Blowfish Decrypted: Minhaj
Program 8:
Write a Java program to implement RSA algorithm.
The RSA scheme is a cipher in which the plaintext and ciphertext are integers
between 0 and n - 1 for some n. A typical size for n is 1024 bits, or 309
decimal digits. That is, n is less than 21024. We examine RSA in this section
in some detail, beginning with an explanation of the algorithm. Then we
examine some of the computational and cryptanalytical implications of RSA.
C = M^e mod n
M = C^d mod n = (M^e)^d mod n = M^(ed) mod n
Implementation:
class RSA {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;
Program 9:
Diffie-Hellman algorithm:
Alice Bob
x=G^a mod P
y=G^b mod P
Example:
Step 1: Alice and Bob get public numbers P = 23, G = 9
Step 2: Alice selected a private key a = 4 and
Bob selected a private key b = 3
Step 3: Alice and Bob compute public values
Alice: x =(9^4 mod 23) = (6561 mod 23) = 6
Bob: y = (9^3 mod 23) = (729 mod 23) = 16
Step 4: Alice and Bob exchange public numbers
Step 5: Alice receives public key y =16 and
Bob receives public key x = 6
Step 6: Alice and Bob compute symmetric keys
Alice: ka = y^a mod p = 65536 mod 23 = 9
Bob: kb = x^b mod p = 216 mod 23 = 9
Step 7: 9 is the shared secret.
<!DOCTYPE html>
<html>
<head>
<title>Diffie-Hellman Key Exchange</title>
</head>
<body>
<script>
// Driver code
var P, G, x, a, y, b, ka, kb;
</script>
</body>
</html>
OUTPUT:
The value of P: 23
The value of G: 9
The private key (a) for Alice: 4
The private key (b) for Bob: 5
Secret key for Alice is: 2
Secret key for Bob is: 2
Program 10:
Calculate the message digest of a text using the SHA-1 algorithm in
JAVA.
SHA-1 Hash
// Driver code
public static void main(String args[]) throws
NoSuchAlgorithmException {
System.out.println("HashCode Generated by SHA-1 for:");
String s1 = "GeeksForGeeks";
System.out.println("\n" + s1 + " : " +
encryptThisString(s1));
Output
HashCode Generated by SHA-1 for:
GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b
Program 11:
Calculate the message digest of a text using the MD5 algorithm in JAVA.
Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6
Implementation:
Java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException
{
String s = "GeeksForGeeks";
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s
}
}
Output
Your HashCode Generated by MD5 is:
e39b9c178b2c9be4e99b141d956c6ff6