0% found this document useful (0 votes)
7 views38 pages

IS Lab Theory

The document outlines multiple programming tasks related to encryption techniques using C and Java, including XOR, AND, OR operations, and various cipher algorithms such as Caesar, Substitution, Hill, DES, and Blowfish. Each program is designed to demonstrate specific encryption and decryption methods, highlighting the importance of operations like XOR in security applications. Additionally, it discusses the properties and limitations of these operations in the context of information security.

Uploaded by

kaviloki0405
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views38 pages

IS Lab Theory

The document outlines multiple programming tasks related to encryption techniques using C and Java, including XOR, AND, OR operations, and various cipher algorithms such as Caesar, Substitution, Hill, DES, and Blowfish. Each program is designed to demonstrate specific encryption and decryption methods, highlighting the importance of operations like XOR in security applications. Additionally, it discusses the properties and limitations of these operations in the context of information security.

Uploaded by

kaviloki0405
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 38

Program 1:

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:

1. Encryption and Decryption


 XOR is widely used in symmetric encryption algorithms because of its reversibility:
o If you XOR a value with a key, you get encrypted data.
o XORing the encrypted data with the same key restores the original value.

Example:
Ciphertext = Plaintext XOR Key
Plaintext = Ciphertext XOR Key
This property is fundamental in stream ciphers and other
lightweight cryptographic algorithms.

2. One-Time Pad Encryption


 In an ideal encryption scheme called a One-Time Pad, a random key is XORed with the
plaintext to produce the ciphertext.
 If the key is truly random and used only once, the ciphertext is theoretically unbreakable.
 XOR ensures that each bit of the plaintext is obfuscated by the corresponding bit in the key.

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.

4. Error Detection and Correction


 XOR is used in parity checks and error-correcting codes (ECC):
o It helps in identifying and correcting single-bit errors in transmitted or stored data.
o Example: XORing bits in a block can generate a parity bit that indicates whether the
number of 1s is even or odd.

5. Digital Signatures and Integrity


 XOR is utilized in certain cryptographic protocols for digital signatures and ensuring data
integrity. It ensures that even small changes in data result in drastically different outputs,
making tampering detectable.

6. Key Management and Exchange


 In cryptographic key management protocols (e.g., Diffie-Hellman), XOR is sometimes used to
combine shared secrets or generate intermediate keys.

Why is XOR So Useful in Security?

1. Simplicity: XOR is a lightweight and computationally inexpensive operation.


2. Reversibility: XOR is a reversible operation, making it ideal for encryption and decryption.
3. Uniformity: XOR operates at the bit level, making it flexible for a wide range of data types
and sizes.
4. Nonlinearity: It is a fundamental building block in creating complex, secure cryptographic
primitives.

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.

By leveraging XOR's properties, information security practitioners can achieve


efficient encryption, integrity verification, and secure communication.

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.

1. AND Operation in Information Security

Purpose: Masking Data

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

Purpose: Setting Bits

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.

3. XOR Operation in Information Security

Purpose: Encryption and Obfuscation

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

1. Input: Plaintext (text) and shift value (shift).


2. For each character in the text:
1. If it is a letter:
1. Calculate the new position using (char - base + shift) % 26 +
base, where base is 'A' for uppercase and 'a' for lowercase.
2. Append the new character to the result.
3. Leave non-alphabetic characters unchanged.
3. Return the encrypted text.

Decryption Algorithm

1. Input: Encrypted text and shift value (shift).


2. Perform the encryption algorithm with a shift of 26 - shift.
3. Return the decrypted text.

Program 3b:
Write a Java program to perform encryption and decryption using the
following algorithms:

b. Substitution cipher

Monoalphabetic Cipher is a part of the substitution technique in which a


single cipher alphabet is used per message (mapping is done from plain
alphabet to cipher alphabet). Monoalphabetic cipher converts plain text into
cipher text and re-convert a cipher text to plain text. Monoalphabetic Cipher
is a cipher where the letters of the plain text are mapped to ciphertext letters
based on a single alphabetic key. It is a one to one mapping.
Monoalphabetic Cipher eliminates the brute-force techniques for
cryptanalysis. Moreover, the cipher line can be a permutation of the 26
alphabetic characters.

Program 3c:

Write a Java program to perform encryption and decryption using the


following algorithms:
Hill Cipher:

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"); }
} }

Open with Google Docs


Program 4:
Write a C/JAVA program to implement the DES algorithm logic.

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.

Algorithm: Blowfish Encryption


Divide x into two 32-bit halves: xL, xR
For i = 1to 16:
xL = XL XOR Pi
xR = F(XL) XOR xR
Swap XL and xR
Swap XL and xR (Undo the last swap.)
xR = xR XOR P17
xL = xL XOR P18
Recombine xL and xR

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).

The first N - 1 rounds consist of four distinct transformation functions:


SubBytes, ShiftRows, MixColumns, and AddRoundKey, which are described
subsequently. The final round contains only three transformations, and there
is a initial single transformation (AddRoundKey) before the first round, which
can be considered Round 0. Each transformation takes one or more 4 * 4
matrices as input and produces a 4 * 4 matrix as output. Figure 5.1 shows that
the output of each round is a 4 * 4 matrix, with the output of the final round
being the ciphertext.
Also, the key expansion function generates N + 1 round keys, each of which is
a distinct 4 * 4 matrix. Each round key serves as one of the inputs to the
AddRoundKey transformation in each round.

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.

We can make several comments about the overall AES structure.


1. One noteworthy feature of this structure is that it is not a Feistel structure.
Recall that, in the classic Feistel structure, half of the data block is used to
modify the other half of the data block and then the halves are swapped. AES
instead processes the entire data block as a single matrix during each round
using substitutions and permutation.
2. The key that is provided as input is expanded into an array of forty-four 32-
bit words, w[i]. Four distinct words (128 bits) serve as a round key for each
round; these are indicated in Figure 5.3.
3. Four different stages are used, one of permutation and three of substitution:
• Substitute bytes: Uses an S-box to perform a byte-by-byte
substitution of the block
• ShiftRows: A simple permutation
• MixColumns: A substitution that makes use of arithmetic over GF(28)
• AddRoundKey: A simple bitwise XOR of the current block with a
portion of the expanded key
4. The structure is quite simple. For both encryption and decryption, the cipher
begins with an AddRoundKey stage, followed by nine rounds that each
includes all four stages, followed by a tenth round of three stages. Figure 5.4
depicts the structure of a full encryption round.
5. Only the AddRoundKey stage makes use of the key. For this reason, the
ipher begins and ends with an AddRoundKey stage. Any other stage, applied
at the beginning or end, is reversible without knowledge of the key and so
would add no security.
6. The AddRoundKey stage is, in effect, a form of Vernam cipher and by itself
would not be formidable. The other three stages together provide confusion,
diffusion, and nonlinearity, but by themselves would provide no security
because they do not use the key. We can view the cipher as alternating
operations of XOR encryption (AddRoundKey) of a block, followed by
scrambling of the block (the other three stages), followed by XOR encryption,
and so on.
This scheme is both efficient and highly secure.
7. Each stage is easily reversible. For the Substitute Byte, ShiftRows, and
MixColumns stages, an inverse function is used in the decryption algorithm.
For the AddRoundKey stage, the inverse is achieved by XORing the same
round key to the block, using the result that A B B = A.
8. As with most block ciphers, the decryption algorithm makes use of the
expanded key in reverse order. However, the decryption algorithm is not
identical to the encryption algorithm. This is a consequence of the particular
structure of AES.
9. Once it is established that all four stages are reversible, it is easy to verify
that decryption does recover the plaintext. Figure 5.3 lays out encryption
and decryption going in opposite vertical directions. At each horizontal point
(e.g., the dashed line in the figure), State is the same for both encryption and
decryption.
10. The final round of both encryption and decryption consists of only three
stages. Again, this is a consequence of the particular structure of AES and is
required to make the cipher reversible.

AES Key Expansion:


KeyExpansion (byte key[16], word w[44])
{
word temp
for (i = 0; i < 4; i++) w[i] = (key[4*i], key[4*i+1],
key[4*i+2],
key[4*i+3]);
for (i = 4; i < 44; i++)
{
temp = w[i - 1];
if (i mod 4 = 0) temp = SubWord (RotWord (temp))
Rcon[i/4];
w[i] = w[i-4] temp
}
}

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.

Example with Java Key Tool


Key Generation: Use the keytool utility in Java to create a secure key for
Blowfish:
keytool -genseckey -keyalg Blowfish -keysize 128 -keystore keystore.jks -
storepass password -alias blowfishKey

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;

public class EncryptionDemo {

// RC4 Logic for Encryption


public static String rc4EncryptDecrypt(String text, String key) {
try {
// Initialize cipher for RC4
Cipher cipher = Cipher.getInstance("RC4");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(),
"RC4");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

// 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();

// Encrypt and Decrypt using Blowfish


String blowfishEncrypted = blowfishEncrypt(text, blowfishKey);
System.out.println("Blowfish Encrypted: " + blowfishEncrypted);

String blowfishDecrypted = blowfishDecrypt(blowfishEncrypted,


blowfishKey);
System.out.println("Blowfish Decrypted: " + blowfishDecrypted);
}
}

OUTPUT:
java EncryptionDemo
RC4 Encrypted: jQCI+S6J
Blowfish Encrypted: FybnKd2S1nM=
Blowfish Decrypted: Minhaj
Program 8:
Write a Java program to implement RSA algorithm.

The Rivest-Shamir-Adleman (RSA) scheme is the most widely accepted and


implemented general-purpose approach to public-key encryption.

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.

Description of the Algorithm


RSA makes use of an expression with exponentials. Plaintext is encrypted in
blocks, with each block having a binary value less than some number n. That
is, the block size must be less than or equal to log2(n) + 1; in practice, the
block size is i bits, where 2i 6 n … 2i+1. Encryption and decryption are of the
following form, for some
plaintext block M and ciphertext block C.

C = M^e mod n
M = C^d mod n = (M^e)^d mod n = M^(ed) mod n
Implementation:

// Java Program to Implement the RSA Algorithm


import java.math.*;
import java.util.*;

class RSA {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;

// The number to be encrypted and decrypted


int msg = 12;
double c;
BigInteger msgback;

// 1st prime number p


p = 3;

// 2nd prime number q


q = 11;
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);

for (e = 2; e < z; e++) {

// e is for public key exponent


if (gcd(e, z) == 1) {
break;
}
}
System.out.println("the value of e = " + e);
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);

// d is for private key exponent


if (x % e == 0) {
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
System.out.println("Encrypted message is : " + c);

// converting int value of n to BigInteger


BigInteger N = BigInteger.valueOf(n);

// converting float value of c to BigInteger


BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Decrypted message is : "
+ msgback);
}

static int gcd(int e, int z)


{
if (e == 0)
return z;
else
return gcd(z % e, e);
}
}

Program 9:

Implement the Diffie-Hellman Key Exchange mechanism using HTML


and JavaScript.

Diffie-Hellman algorithm:

The Diffie-Hellman algorithm is being used to establish a shared


secret that can be used for secret communications while
exchanging data over a public network using the elliptic curve to
generate points and get the secret key using the parameters.
 For the sake of simplicity and practical implementation of the
algorithm, we will consider only 4 variables, one prime P and G
(a primitive root of P) and two private values a and b.
 P and G are both publicly available numbers. Users (say Alice
and Bob) pick private values a and b and they generate a key
and exchange it publicly. The opposite person receives the key
and that generates a secret key, after which they have the same
secret key to encrypt.

Step-by-Step explanation is as follows:

Alice Bob

Public Keys available = P, G Public Keys available = P, G

Private Key Selected = a Private Key Selected = b

Key generated = Key generated =


Alice Bob

x=G^a mod P
y=G^b mod P

Exchange of generated keys takes place

Key received = y key received = x

Generated Secret Key = Generated Secret Key =


ka=y^amod P kb=x^b mod P

Algebraically, it can be shown that


ka=kb

Users now have a symmetric secret key to encrypt

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>

// Power function to return value of a ^ b mod P


function power(a, b, p)
{
if (b == 1)
return a;
else
return((Math.pow(a, b)) % p);
}

// Driver code
var P, G, x, a, y, b, ka, kb;

// Both the persons will agree upon the


// public keys G and P

P = parseInt(prompt("Enter a prime number P:"));


document.write("The value of P: " + P + "<br>");

G = parseInt(prompt("Enter a primitive root G:"));


document.write("The value of G: " + G + "<br>");

// Alice will choose the private key a


// a is the chosen private key
a = parseInt(prompt("Enter the private key for Alice (a):"));
document.write("The private key (a) for Alice: " + a + "<br>");

// Gets the generated key


x = power(G, a, P);

// Bob will choose the private key b


// b is the chosen private key
b = parseInt(prompt("Enter the private key for Bob (b):"));
document.write("The private key (b) for Bob: " + b + "<br>");

// Gets the generated key


y = power(G, b, P);

// Generating the secret key after the exchange


// of keys
ka = power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob

document.write("Secret key for Alice is: " + ka + "<br>");


document.write("Secret key for Bob is: " + kb + "<br>");

</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 or Secure Hash Algorithm 1 is a cryptographic


algorithm that 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
been considered insecure since 2005. Major tech giants
browsers like Microsoft, Google, Apple, and Mozilla have
stopped accepting SHA-1 SSL certificates by 2017.

SHA-1 Hash

How SHA-1 Works


The block diagram of the SHA-1 (Secure Hash Algorithm 1)
algorithm. Here’s a detailed description of each component
and process in the diagram:
Components and Process Flow:
1. Message (M):
 The original input message that needs to be
hashed.
2. Message Padding:
 The initial step where the message is
padded to ensure its length is congruent to
448 modulo 512. This step prepares the
message for processing in 512-bit blocks.
3. Round Word Computation (WtW_tWt):
 After padding, the message is divided into
blocks of 512 bits, and each block is further
divided into 16 words of 32 bits. These
words are then expanded into 80 32-bit
words, which are used in the subsequent
rounds.
4. Round Initialize (A, B, C, D, and E):
 Initialization of five working variables (A, B,
C, D, and E) with specific constant values.
These variables are used to compute the
hash value iteratively.
5. Round Constants (KtK_tKt):
 SHA-1 uses four constant values (K1K_1K1,
K2K_2K2, K3K_3K3, K4K_4K4), each applied
in a specific range of rounds:
o K1K_1K1 for rounds 0-19
o K2K_2K2 for rounds 20-39
o K3K_3K3 for rounds 40-59
o K4K_4K4 for rounds 60-79
6. Rounds (0-79):
 The main computation loop of SHA-1,
divided into four stages (each
corresponding to one of the constants
K1K_1K1 to K4K_4K4). In each round, a
combination of logical functions and
operations is performed on the working
variables (A, B, C, D, and E) using the words
generated in the previous step.
7. Final Round Addition:
After all 80 rounds, the resulting values of
A, B, C, D, and E are added to the original
hash values to produce the final hash.
8. MPX (Multiplexing):
 Combines the results from the final round
addition to form the final message digest.
Summary of Steps:
 Input (Message M): The process starts with the
input message MMM.
 Message Padding: The message is padded to
meet the length requirements.
 Word Computation: The padded message is
divided into blocks and further into words, which
are expanded for use in the rounds.
 Initialization: Initial hash values are set.
 Round Processing: The main loop performs 80
rounds of computation using the message words
and round constants.
 Final Addition: The results from the rounds are
added to the initial hash values.
 Output (Hash Value): The final message digest is
produced.
Cryptographic Hash Functions in Java
To calculate cryptographic hash values in Java,
the MessageDigest class is used, which is part of
the java.security package. The MessageDigest class provides
the following cryptographic hash functions:
 MD2
 MD5
 SHA-1
 SHA-224
 SHA-256
 SHA-384
 SHA-512
These algorithms are initialized in static method
called getInstance(). After selecting the algorithm the
message digest value is calculated and the results are
returned as a byte array. BigInteger class is used, to
convert the resultant byte array into its signum
representation. This representation is then converted into a
hexadecimal format to get the expected MessageDigest.
Examples:
Input : hello world
Output : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
Input : GeeksForGeeks
Output : addf120b430021c36c232c99ef8d926aea2acd6b
Example 1: Below program shows the implementation of
SHA-1 hash in Java.
Java
// Java program to calculate SHA-1 hash value
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GFG {


public static String encryptThisString(String input) {
try {
// getInstance() method is called with algorithm SHA-
1
MessageDigest md = MessageDigest.getInstance("SHA-
1");

// digest() method is called


// to calculate message digest of the input string
// returned as array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation


BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value


String hashtext = no.toString(16);

// Add preceding 0s to make it 40 digits long


while (hashtext.length() < 40) {
hashtext = "0" + hashtext;
}

// return the HashText


return hashtext;
}

// For specifying wrong message digest algorithms


catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

// 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));

String s2 = "hello world";


System.out.println("\n" + s2 + " : " +
encryptThisString(s2));
}
}

Output
HashCode Generated by SHA-1 for:

GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b

hello world : 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed

Program 11:

Calculate the message digest of a text using the MD5 algorithm in JAVA.

To calculate cryptographic hashing value in


Java, MessageDigest Class is used, under the package
java.security.
MessageDigest Class provides following cryptographic hash
function to find hash value of a text, they are:
1. MD5
2. SHA-1
3. SHA-256
This Algorithms are initialize in static method
called getInstance(). After selecting the algorithm it
calculate the digest value and return the results in byte
array.
BigInteger class is used, which converts the resultant byte
array into its sign-magnitude representation.
This representation converts into hex format to get the
MessageDigest
Examples:
Input : hello world
Output : 5eb63bbbe01eeed093cb22bb8f5acdc3

Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6
Implementation:
 Java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

// Java program to calculate MD5 hash value


public class MD5 {
public static String getMd5(String input)
{
try {

// Static getInstance method is called with hashing MD5


MessageDigest md = MessageDigest.getInstance("MD5");

// digest() method is called to calculate message digest


// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation


BigInteger no = new BigInteger(1, messageDigest);

// Convert message digest into hex value


String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}

// For specifying wrong message digest algorithms


catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

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

You might also like