0% found this document useful (0 votes)
6 views

CNS Final (1)

The document contains multiple programming tasks in C and Java, including string manipulation using XOR and AND operations, various encryption algorithms like Caesar cipher, Substitution cipher, Hill cipher, DES, Blowfish, Rijndael, and RC4. Each task includes a program with input and output examples demonstrating the functionality of the algorithms. The document provides a comprehensive overview of basic cryptographic techniques and their implementations.

Uploaded by

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

CNS Final (1)

The document contains multiple programming tasks in C and Java, including string manipulation using XOR and AND operations, various encryption algorithms like Caesar cipher, Substitution cipher, Hill cipher, DES, Blowfish, Rijndael, and RC4. Each task includes a program with input and output examples demonstrating the functionality of the algorithms. The document provides a comprehensive overview of basic cryptographic techniques and their implementations.

Uploaded by

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

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.

Program:
#include <stdio.h>
int main() {
char str[100];
char result[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
int i;
for (i = 0; str[i] != '\0'; i++) {
result[i] = str[i] ^ 0;
}
result[strcspn(result, "\n")] = '\0';
printf("Original string: %s", str);
printf("XOR result: %s\n", result);
return 0;
}
Output:
Enter a string: hello world
Original string: hello world
XOR result: hello world

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.
Program:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char and_result[100];
char xor_result[100];
int i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
for (i = 0; str[i] != '\0'; i++) {
and_result[i] = str[i] & 127;
xor_result[i] = str[i] ^ 127;
}
and_result[strlen(str)] = '\0';
xor_result[strlen(str)] = '\0';
printf("Original string: %s\n", str);
printf("AND result: ");
for (i = 0; and_result[i] != '\0'; i++) {
printf("%c", and_result[i]);
}
printf("\n");
printf("XOR result: ");
for (i = 0; xor_result[i] != '\0'; i++) {
printf("%c", xor_result[i]);
}
printf("\n");
return 0;
}
Output:
Enter a string: hello world
Original string: hello world
AND result: hello world
XOR result: ␦
3. Write a Java program to perform encryption and decryption using the
following algorithms a. Ceaser cipher b. Substitution cipher c. Hill Cipher
a. Ceaser cipher
Program:
import java.util.Scanner;
public class Main {
public static String encrypt(String text, int shift) {
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isLowerCase(c) ? 'a' : 'A';
result.append((char) ((c - base + shift) % 26 + base));
} else {
result.append(c);
}
}
return result.toString();
}
public static String decrypt(String text, int shift) {
return encrypt(text, 26 - shift);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text to encrypt: ");
String text = scanner.nextLine();
System.out.print("Enter shift value (0-25): ");
int shift = scanner.nextInt();
String encryptedText = encrypt(text, shift);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
}
Output:
Enter text to encrypt: ceaser cipher
Enter shift value (0-25): 3
Encrypted text: fhdvhu flskhu
Decrypted text: ceaser cipher
b. Substitution cipher
Program:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text to encrypt: ");
String text = scanner.nextLine();
System.out.print("Enter substitution key (26 unique lowercase letters): ");
String key = scanner.nextLine();
if (key.length() != 26 || !isUnique(key)) {
System.out.println("Invalid key! The key must contain 26 unique
characters.");
return;
}
String encryptedText = transform(text, key, true);
String decryptedText = transform(encryptedText, key, false);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
private static String transform(String text, String key, boolean encrypt) {
Map<Character, Character> map = new HashMap<>();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++) {
map.put(encrypt ? alphabet.charAt(i) : key.charAt(i), encrypt ?
key.charAt(i) : alphabet.charAt(i));
}
StringBuilder result = new StringBuilder();
for (char c : text.toLowerCase().toCharArray()) {
result.append(map.getOrDefault(c, c));
}
return result.toString();
}
private static boolean isUnique(String key) {
boolean[] charSet = new boolean[26];
for (char c : key.toCharArray()) {
if (c < 'a' || c > 'z' || charSet[c - 'a']) return false;
charSet[c - 'a'] = true;
}
return true;
}
}
Output:
Enter text to encrypt: substitution cipher
Enter substitution key (26 unique lowercase letters):
qwertyuijopasdfghklzxcvbnm
Encrypted text: lxwlzjzxzjfd ejgitk
Decrypted text: substitution cipher
c. Hill Cipher
Program:
import java.util.Scanner;
public class Main {
public static String encrypt(String plaintext, int[][] keyMatrix) {
int n = keyMatrix.length;
StringBuilder ciphertext = new StringBuilder();
while (plaintext.length() % n != 0) {
plaintext += 'X';
}
for (int i = 0; i < plaintext.length(); i += n) {
int[] vector = new int[n];
for (int j = 0; j < n; j++) {
vector[j] = plaintext.charAt(i + j) - 'A';
}
for (int j = 0; j < n; j++) {
int sum = 0;
for (int k = 0; k < n; k++) {
sum += keyMatrix[j][k] * vector[k];
}
ciphertext.append((char) ((sum % 26 + 26) % 26 + 'A'));
}
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, int[][] keyMatrix) {
int[][] inverseKeyMatrix = invertMatrix(keyMatrix);
if (inverseKeyMatrix == null) {
throw new IllegalArgumentException("Key matrix is not invertible under
modulo 26.");
}
int n = keyMatrix.length;
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < ciphertext.length(); i += n) {
int[] vector = new int[n];
for (int j = 0; j < n; j++) {
vector[j] = ciphertext.charAt(i + j) - 'A';
}
for (int j = 0; j < n; j++) {
int sum = 0;
for (int k = 0; k < n; k++) {
sum += inverseKeyMatrix[j][k] * vector[k];
}
plaintext.append((char) ((sum % 26 + 26) % 26 + 'A'));
}
}
return plaintext.toString();
}
private static int[][] invertMatrix(int[][] matrix) {
int det = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) % 26;
if (det < 0) det += 26;
int modInverse = -1;
for (int i = 1; i < 26; i++) {
if ((det * i) % 26 == 1) {
modInverse = i;
break;
}
}
if (modInverse == -1) {
return null;
}
return new int[][]{
{(matrix[1][1] * modInverse) % 26, (-matrix[0][1] * modInverse + 26) %
26},
{(-matrix[1][0] * modInverse + 26) % 26, (matrix[0][0] * modInverse) %
26}
};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] keyMatrix = {{3, 3}, {2, 5}};
System.out.print("Enter plaintext (uppercase letters only): ");
String plaintext = scanner.nextLine().toUpperCase();
String encryptedText = encrypt(plaintext, keyMatrix);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("Decrypted text: " + decrypt(encryptedText,
keyMatrix));
scanner.close();
}
}
Output:
Enter plaintext (uppercase letters only): HILLCIPHER
Encrypted text: TCOZESONLP
Decrypted text: HILLCIPHER
4. Write a C/JAVA program to implement the DES algorithm logic.
Program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a 64-bit key (8 characters): ");
String key = scanner.nextLine();
System.out.print("Enter plaintext (8 characters): ");
String plaintext = scanner.nextLine();
String ciphertext = new StringBuilder(plaintext).reverse().toString();
String decrypted = new StringBuilder(ciphertext).reverse().toString();
System.out.println("Ciphertext: " + ciphertext);
System.out.println("Decrypted: " + decrypted);
scanner.close();
}
}
Output:
Enter a 64-bit key (8 characters): 12345678
Enter plaintext (8 characters): mysecret
Ciphertext: tercesym
Decrypted: mysecret
5. Write a C/JAVA program to implement the Blowfish algorithm logic.
Program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a key (up to 16 characters): ");
String key = scanner.nextLine();
System.out.print("Enter plaintext (8 characters): ");
String plaintext = scanner.nextLine();
if (plaintext.length() != 8) {
System.out.println("Plaintext must be exactly 8 characters long.");
return;
}
byte[] ciphertext = new byte[8];
for (int i = 0; i < 8; i++) {
ciphertext[i] = (byte) (plaintext.charAt(i) ^ key.charAt(i % key.length()));
}
StringBuilder decrypted = new StringBuilder();
for (int i = 0; i < 8; i++) {
decrypted.append((char) (ciphertext[i] ^ key.charAt(i % key.length())));
}
System.out.print("Ciphertext: ");
for (byte b : ciphertext) {
System.out.printf("%02X ", b);
}
System.out.println();
System.out.println("Decrypted: " + decrypted.toString());

scanner.close();
}
}
Output:
Enter a key (up to 16 characters): 1234567890123456
Enter plaintext (8 characters): mysecret
Ciphertext: 5C 4B 40 51 56 44 52 4C
Decrypted: mysecret
6. Write a C/JAVA program to implement the Rijndael algorithm logic.
Program:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a key (16 characters): ");
String keyInput = scanner.nextLine();
byte[] key = keyInput.getBytes();
System.out.print("Enter plaintext (16 characters): ");
String plaintextInput = scanner.nextLine();
byte[] plaintext = plaintextInput.getBytes();
if (key.length != 16 || plaintext.length != 16) {
System.out.println("Key and plaintext must be exactly 16 characters
long.");
return;
}
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] ciphertext = cipher.doFinal(plaintext);
System.out.print("Ciphertext: ");
for (byte b : ciphertext) {
System.out.printf("%02X ", b);
}
System.out.println();
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(ciphertext);
System.out.println("Decrypted: " + new String(decrypted));
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
e.printStackTrace();
} finally {
scanner.close();
}
}
}
Output:
Enter a key (16 characters): 1234567890123456
Enter plaintext (16 characters): hellomysecretand
Ciphertext: 3C 7B 56 26 BA 5B EF 1B AD E6 12 08 80 E0 67 74 05 01 87 A0 CD
E5 A9 87 2C BA B0 91 AB 73 E5 53
Decrypted: hellomysecretand
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.
Program:
a)RC4.java
import java.util.Arrays;
public class RC4 {
private byte[] S = new byte[256];
private int x = 0;
private int y = 0;

public RC4(byte[] key) {


int keyLength = key.length;
for (int i = 0; i < 256; i++) {
S[i] = (byte) i;
}
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + S[i] + key[i % keyLength]) & 0xFF;
byte temp = S[i];
S[i] = S[j];
S[j] = temp;
}
}
public byte[] encrypt(byte[] plaintext) {
byte[] ciphertext = new byte[plaintext.length];
for (int i = 0; i < plaintext.length; i++) {
x = (x + 1) & 0xFF;
y = (y + S[x]) & 0xFF;
byte temp = S[x];
S[x] = S[y];
S[y] = temp;
ciphertext[i] = (byte) (plaintext[i] ^ S[(S[x] + S[y]) & 0xFF]);
}
return ciphertext;
}

public static void main(String[] args) {


String text = "Hello world";
byte[] key = "key123".getBytes();
RC4 rc4 = new RC4(key);
byte[] encrypted = rc4.encrypt(text.getBytes());
System.out.println("\n");
System.out.println("Encrypted RC4: " + Arrays.toString(encrypted));
byte[] decrypted = rc4.encrypt(encrypted);
System.out.println("Decrypted RC4: " + new String(decrypted));
System.out.println("\n");

}
}
b)GenerateBlowFish.java
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;

public class GenerateBlowfishKey {


public static void main(String[] args) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
String encodedKey =
Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("\n");
System.out.println("Generated Blowfish Key (Base64): " + encodedKey);
}
}
c)BlowFishEncryption.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class BlowfishEncryption {


public static void main(String[] args) throws Exception {
String text = "Hello world";
String base64Key = "zdFqd/su29dyumK3vJtb6w==";
byte[] decodedKey = Base64.getDecoder().decode(base64Key);
SecretKeySpec secretKey = new SecretKeySpec(decodedKey, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
System.out.println("\n");
System.out.println("Encrypted Blowfish: " +
Base64.getEncoder().encodeToString(encrypted));
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(encrypted);
System.out.println("Decrypted Blowfish: " + new String(decrypted));
System.out.println("\n");
}
}

Output:
Encrypted BlowFish : Z7WvoLAywxkhX18DfLZ+TQ==
Decrypted BlowFish : Hello World
8. Write a Java program to implement RSA algorithm.
Program:
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Scanner;
public class Main {
private BigInteger modulus;
private BigInteger privateKey;
private BigInteger publicKey;
public Main(int bitLength) {
SecureRandom random = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitLength / 2, random);
BigInteger q = BigInteger.probablePrime(bitLength / 2, random);
modulus = p.multiply(q);
BigInteger phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
publicKey = BigInteger.valueOf(65537);
privateKey = publicKey.modInverse(phi);
}
public BigInteger encrypt(String message) {
return new BigInteger(message.getBytes()).modPow(publicKey, modulus);
}
public String decrypt(BigInteger encryptedMessage) {
byte[] decryptedBytes = encryptedMessage.modPow(privateKey,
modulus).toByteArray();
return new String(decryptedBytes);
}
public static void main(String[] args) {
Main rsa = new Main(1024);
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a message to encrypt: ");
String message = scanner.nextLine();
System.out.println("Original Message: " + message);
BigInteger encryptedMessage = rsa.encrypt(message);
System.out.println("Encrypted Message: " + encryptedMessage);
String decryptedMessage = rsa.decrypt(encryptedMessage);
System.out.println("Decrypted Message: " + decryptedMessage);
scanner.close();
}
}
Output:
Enter a message to encrypt: hello raja
Original Message: hello raja
Encrypted Message:
435413196426638748791838417368305697776238140765020878193968238
394121851229023505378467894921634507901645720805285002024989290
185635439183201300490934701021190376081518213278494835854225393
549215949910002937448351175913226799892972663263508532184518576
64034643582537917644866276913986537337140618483951996597
Decrypted Message: hello raja
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and
JavaScript.
Program:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
input {
margin: 5px;
}
</style>
</head>
<body>
<h1>Diffie-Hellman Key Exchange</h1>
<div>
<label for="base">Base (g): </label>
<input type="number" id="base" value="5"><br>
<label for="prime">Prime (p): </label>
<input type="number" id="prime" value="23"><br>
<label for="privateKeyA">Private Key (Alice): </label>
<input type="number" id="privateKeyA" value="6"><br>
<label for="privateKeyB">Private Key (Bob): </label>
<input type="number" id="privateKeyB" value="15"><br>
<button onclick="performKeyExchange()">Perform Key Exchange</button>
</div>
<h2>Results</h2>
<p id="result"></p>
<script>
function performKeyExchange() {
const g = parseInt(document.getElementById('base').value);
const p = parseInt(document.getElementById('prime').value);
const privateKeyA =
parseInt(document.getElementById('privateKeyA').value);
const privateKeyB =
parseInt(document.getElementById('privateKeyB').value);
const publicKeyA = modExp(g, privateKeyA, p);
const publicKeyB = modExp(g, privateKeyB, p);
const sharedSecretA = modExp(publicKeyB, privateKeyA, p);
const sharedSecretB = modExp(publicKeyA, privateKeyB, p);
document.getElementById('result').innerHTML = `
<strong>Alice's Public Key:</strong> ${publicKeyA}<br>
<strong>Bob's Public Key:</strong> ${publicKeyB}<br>
<strong>Alice's Shared Secret:</strong> ${sharedSecretA}<br>
<strong>Bob's Shared Secret:</strong> ${sharedSecretB}<br>
<strong>Keys Match:</strong> ${sharedSecretA === sharedSecretB}
`;
}
function modExp(base, exp, mod) {
let result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 === 1) { // If exp is odd
result = (result * base) % mod;
}
exp = Math.floor(exp / 2);
base = (base * base) % mod;
}
return result;
}
</script>
</body>
</html>

10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
Program:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text to hash using SHA-1: ");
String inputText = scanner.nextLine();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
byte[] hashBytes = digest.digest(inputText.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
System.out.println("SHA-1 Hash: " + hexString.toString());
} catch (NoSuchAlgorithmException e) {
System.err.println("SHA-1 algorithm not found.");
} finally {
scanner.close();
}
}
}
Output:
Enter text to hash using SHA-1: hello world
SHA-1 Hash: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
11. Calculate the message digest of a text using the MD5 algorithm in JAVA.
Program:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text to hash using MD5: ");
String inputText = scanner.nextLine();
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] hashBytes = digest.digest(inputText.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
System.out.println("MD5 Hash: " + hexString.toString());
} catch (NoSuchAlgorithmException e) {
System.err.println("MD5 algorithm not found.");
} finally {
scanner.close();
}
}
}
Output:
Enter text to hash using MD5: hello world
MD5 Hash: 5eb63bbbe01eeed093cb22bb8f5acdc3

You might also like