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

CNS cycle 1

Uploaded by

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

CNS cycle 1

Uploaded by

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

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

7. Write a JAVA program to implement the Blowfish algorithm logic.


Program:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Scanner;
public class Blowfish {
private static final String key = "123";
public static String encrypt(String password) {
try {
byte[] keyData = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(password.getBytes());
return new String(Base64.getEncoder().encode(result));
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static String decrypt(String encryptedText) {


try {
byte[] keyData = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] result = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(result);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter text to encrypt: ");
String textToEncrypt = sc.nextLine();
String encryptedText = encrypt(textToEncrypt);
System.out.println("Encrypted text: " + encryptedText);
System.out.println("\nDecrypted text: " + decrypt(encryptedText));
sc.close();
}
}
Output:
Enter text to encrypt: Cryptography
Encrypted text: AOcIcmCKNer5d0Hiopb8wg==
Decrypted text: Cryptography

8. Write a JAVA program to implement the Rijndael algorithm logic.


Program:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Scanner;
public class RijndaelUserInputKey {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
// Get user input for key
System.out.print("Enter key (must be 16, 24, or 32 characters long): ");
String key = scanner.nextLine();
// Validate key length
if (key.length() != 16 && key.length() != 24 && key.length() != 32) {
System.out.println("Invalid key length. Key must be 16, 24, or 32 characters long.");
return;
}
// Get user input for text
System.out.print("Enter text to encrypt: ");
String originalText = scanner.nextLine();
// Encryption
byte[] encryptedBytes = encrypt(originalText, key);
System.out.println("Encrypted: " + new String(encryptedBytes));
// Decryption
String decryptedText = decrypt(encryptedBytes, key);
System.out.println("Decrypted: " + decryptedText);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
}
Output:
Enter key (must be 16, 24, or 32 characters long): abcdefghijklmnopqrstuvwx
Enter text to encrypt: Cryptography
Encrypted: $???htT?v3V ????
Decrypted: 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

Text to encrypt using blowfish: Hello world


Generated Blowfish Key: FLTccHGULZmpUtFd8+7gxw==
Encrypted Blowfish: p5GBSRZp4beNRzGIqzILHA==
Decrypted Blowfish: Hello world

10. Write a Java program to implement RSA algorithm.


Program:
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);
}
}
Output:
the value of z = 20
the value of e = 3
the value of d = 7
Encrypted message is : 12.0
Decrypted message is : 12
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 MD5 {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the text to hash: ");
String text = scanner.nextLine(); // Read user input
scanner.close(); // Close the Scanner
try {
// Creating MD5 MessageDigest instance
MessageDigest md = MessageDigest.getInstance("MD5");
// Getting the bytes from the text
byte[] textBytes = text.getBytes();
// Updating the MessageDigest with the bytes
md.update(textBytes);
// Completing the hash computation
byte[] digest = md.digest();
// Converting the byte array to a hexadecimal string
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b & 0xff));
}
// Outputting the hexadecimal string
System.out.println("MD5 Hash: " + hexString.toString());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
}
}
Output:
Enter the text to hash: Cryptography
MD5 Hash: 64ef07ce3e4b420c334227eecb3b3f4c

You might also like