CNS cycle 1
CNS cycle 1
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
display the result.
Program:
#include <stdio.h>
int main() {
// Define the string
char *str = "Hello world";
// XOR each character with 0 and display the result
printf("XOR result: ");
for (int i = 0; str[i] != '\0'; i++) {
printf("%c", str[i] ^ 0);
}
printf("\n");
return 0;
}
Output:
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>
int main() {
// Define the string
char *str = "Hello world";
// Perform AND operation on each character with 127 and display the result
printf("AND result: ");
for (int i = 0; str[i] != '\0'; i++) {
printf("%c", str[i] & 127);
}
printf("\n");
// Perform XOR operation on each character with 127 and display the result
printf("XOR result: ");
for (int i = 0; str[i] != '\0'; i++) {
printf("%c", str[i] ^ 127);
}
printf("\n");
return 0;
}
Output:
AND result: Hello world
XOR result: !!->!!!!>(>
3. Write a Java program to perform encryption and decryption using the Ceaser
cipher algorithm.
Program:
import java.util.Scanner;
public class CaesarCipher {
public static String caesarCipher(String text, int key, boolean encrypt) {
StringBuilder result = new StringBuilder();
int direction = encrypt ? 1 : -1; // 1 for encryption, -1 for decryption
for (char ch : text.toCharArray()) {
if (Character.isLetter(ch)) {
char shifted = (char) ('A' + ((ch - 'A') + direction * key + 26) % 26);
result.append(shifted);
}
else {
result.append(ch);
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input plaintext
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine().toUpperCase(); // Convert to uppercase for simplicity
// Input the key
System.out.print("Enter the key (an integer): ");
int key = scanner.nextInt();
// Encrypt the plaintext
String encryptedText = caesarCipher(plaintext, key, true);
System.out.println("Encrypted text: " + encryptedText);
// Decrypt the ciphertext
String decryptedText = caesarCipher(encryptedText, key, false);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
}
Output:
Enter the plaintext: Cryptography
Enter the key (an integer): 4
Encrypted text: GVCTXSKVETLC
Decrypted text: CRYPTOGRAPHY
4. Write a Java program to perform encryption and decryption using the
Substitution cipher.
Program:
import java.util.Scanner;
public class SubstitutionCipher
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// Define substitution key
char[] encryptionKey = new char[26];
char[] decryptionKey = new char[26];
// Define the substitution mapping for encryption
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String substitution = "QWERTYUIOPASDFGHJKLZXCVBNM"; // Example substitution
for (int i = 0; i < alphabet.length(); i++)
{
encryptionKey[alphabet.charAt(i) - 'A'] = substitution.charAt(i);
decryptionKey[substitution.charAt(i) - 'A'] = alphabet.charAt(i);
}
// Input plaintext
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine().toUpperCase(); // Convert to uppercase for simplicity
// Encrypt the plaintext
StringBuilder encryptedText = new StringBuilder();
for (char ch : plaintext.toCharArray())
{
if (Character.isLetter(ch))
{
encryptedText.append(encryptionKey[ch - 'A']);
}
else
{
encryptedText.append(ch);
}
}
System.out.println("Encrypted text: " + encryptedText);
// Decrypt the ciphertext
StringBuilder decryptedText = new StringBuilder();
for (char ch : encryptedText.toString().toCharArray())
{
if (Character.isLetter(ch))
{
decryptedText.append(decryptionKey[ch - 'A']);
}
else
{
decryptedText.append(ch);
}
}
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
}
Output:
Enter the plaintext: Cryptography
Encrypted text: EKNHZGUKQHIN
Decrypted text: CRYPTOGRAPHY
5. Write a Java program to perform encryption and decryption using the Hill cipher.
Program:
import java.util.Scanner;
public class HillCipher {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input plaintext
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine().toUpperCase().replaceAll("[^A-Z]", ""); // Remove non-
alphabetic characters and convert to uppercase
// Input key matrix
int[][] key = new int[2][2];
System.out.println("Enter the key matrix (2x2):");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
key[i][j] = scanner.nextInt() % 26; // Ensuring elements are in the range [0, 25]
}
}
// Encrypt the plaintext
String encryptedText = encrypt(plaintext, key);
System.out.println("Encrypted text: " + encryptedText);
// Decrypt the ciphertext
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted text: " + decryptedText);
scanner.close();
}
// Function to perform encryption
public static String encrypt(String plaintext, int[][] key) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < plaintext.length(); i += 2) {
int[] vector = new int[]{plaintext.charAt(i) - 'A', plaintext.charAt(i + 1) - 'A'};
int[] product = matrixVectorProduct(key, vector);
result.append((char) ('A' + product[0]));
result.append((char) ('A' + product[1]));
}
return result.toString();
}
// Function to perform decryption
public static String decrypt(String ciphertext, int[][] key) {
StringBuilder result = new StringBuilder();
int determinant = key[0][0] * key[1][1] - key[0][1] * key[1][0];
int detInverse = modInverse(determinant, 26);
int[][] inverseKey = {{key[1][1], -key[0][1]}, {-key[1][0], key[0][0]}};
for (int i = 0; i < ciphertext.length(); i += 2) {
int[] vector = new int[]{ciphertext.charAt(i) - 'A', ciphertext.charAt(i + 1) - 'A'};
int[] product = matrixVectorProduct(inverseKey, vector);
result.append((char) ('A' + (detInverse * product[0] % 26 + 26) % 26));
result.append((char) ('A' + (detInverse * product[1] % 26 + 26) % 26));
}
return result.toString();
}
// Function to calculate the greatest common divisor (gcd)
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// Function to calculate the modular inverse
public static int modInverse(int a, int m) {
a = a % m;
for (int x = 1; x < m; x++) {
if ((a * x) % m == 1) {
return x;
}
}
return 1;
}
// Function to perform matrix-vector multiplication
public static int[] matrixVectorProduct(int[][] matrix, int[] vector) {
int[] product = new int[2];
product[0] = matrix[0][0] * vector[0] + matrix[0][1] * vector[1];
product[1] = matrix[1][0] * vector[0] + matrix[1][1] * vector[1];
return new int[]{product[0] % 26, product[1] % 26}; // Mod 26 arithmetic
}
}
Output:
Enter the plaintext: CRYPTOGRAPHY
Enter the key matrix (2x2):
23
15
Encrypted text: DJPVCLLNTXIX
Decrypted text: CRYPTOGRAPHY
6. Write a JAVA program to implement the DES algorithm logic.
Program:
import javax.crypto.*;
import javax.crypto.spec.*;
import java.util.Base64;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class DESAlgorithm {
private static final String ENCRYPTION_SCHEME = "DES";
private static final String UNICODE_FORMAT = "UTF8";
private static SecretKey key;
static {
try {
key = generateKey();
}
catch (Exception e) {
System.err.println("Error generating key: " + e.getMessage());
System.exit(1); // Terminate program if key generation fails
}
}
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception {
System.out.print("Enter the string: ");
String input = br.readLine();
String encrypted = encrypt(input);
String decrypted = decrypt(encrypted);
System.out.println("\nString To Encrypt: " + input);
System.out.println("\nEncrypted Value: " + encrypted);
System.out.println("\nDecrypted String: " + decrypted);
}
private static String encrypt(String input) throws Exception {
Cipher cipher = Cipher.getInstance(ENCRYPTION_SCHEME);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(input.getBytes(UNICODE_FORMAT));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
private static String decrypt(String encryptedString) throws Exception {
Cipher cipher = Cipher.getInstance(ENCRYPTION_SCHEME);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedString);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, UNICODE_FORMAT);
}
private static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRYPTION_SCHEME);
keyGenerator.init(56); // 56-bit DES key size
return keyGenerator.generateKey();
}
}
Output:
Enter the string: Cryptography
String To Encrypt: Cryptography
Encrypted Value: Kh7ILSuwRJEuQYnDba+vzg==
Decrypted String: Cryptography
9. 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:
import javax.crypto.*;
import java.security.*;
import java.util.Scanner;
import java.util.Base64;
public class RC4logic {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter plain text for RC4 encryption: ");
String rc4Plaintext = scanner.nextLine();
String rc4Key = "MyRC4Key";
System.out.println("\nOriginal: " + rc4Plaintext);
try {
String encryptedRC4 = encrypt("RC4", rc4Plaintext, rc4Key);
System.out.println("Encrypted RC4: " + encryptedRC4);
String decryptedRC4 = decrypt("RC4", encryptedRC4, rc4Key);
System.out.println("Decrypted RC4: " + decryptedRC4);
String plaintext = "Hello world";
System.out.println("\nText to encrypt using blowfish: " + plaintext);
String blowfishKey = generateKey("Blowfish");
System.out.println("\nGenerated Blowfish Key: " + blowfishKey);
String encryptedBlowfish = encrypt("Blowfish", plaintext, blowfishKey);
System.out.println("Encrypted Blowfish: " + encryptedBlowfish);
String decryptedBlowfish = decrypt("Blowfish", encryptedBlowfish, blowfishKey);
System.out.println("Decrypted Blowfish: " + decryptedBlowfish);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
scanner.close();
}
}
public static String encrypt(String algorithm, String plaintext, String key) throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, new
javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), algorithm));
return Base64.getEncoder().encodeToString(cipher.doFinal(plaintext.getBytes()));
}
public static String decrypt(String algorithm, String encryptedText, String key) throws
Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, new
javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), algorithm));
return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedText)));
}
public static String generateKey(String algorithm) throws NoSuchAlgorithmException {
return
Base64.getEncoder().encodeToString(KeyGenerator.getInstance(algorithm).generateKey().get
Encoded());
}
}
Output:
Enter plain text for RC4 encryption: Cryptography
Original: Cryptography
Encrypted RC4: wz1Xk5yzrrZv1Fjn
Decrypted RC4: Cryptography