0% found this document useful (0 votes)
28 views24 pages

Lab C&ns

Uploaded by

lofi music
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)
28 views24 pages

Lab C&ns

Uploaded by

lofi music
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/ 24

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.

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.

3. Write a Java program to perform encryption and decryption using the


following algorithms a. Ceaser cipher b. Substitution cipher c. Hill Cipher

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

5. Write a C/JAVA program to implement the Blowfish algorithm logic.

6. Write a C/JAVA program to implement the Rijndael algorithm logic.

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.

8. Write a Java program to implement RSA algorithm.

9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and


JavaScript.

10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

11. Calculate the message digest of a text using the MD5 algorithm in JAVA
Program:1

#include <stdio.h>

#include <string.h>

int main() {

char *str = "Hello world";

int len = strlen(str);

int i;
printf("Original string: %s\n", str);

printf("XOR with 0: ");

for (i = 0; i < len; i++) {

printf("%c", str[i] ^ 0);

printf("\n");

return 0;

Output:

Original string: Hello world

XOR with 0: Hello world

Program:2

#include <stdio.h>

#include <string.h>

int main() {

char *str = "Hello world";

int len = strlen(str);

int i;

printf("Original string: %s\n", str);

printf("XOR with 127: ");


for (i = 0; i < len; i++) {

printf("%c", str[i] ^ 127);

printf("\n");

printf("AND with 127: ");

for (i = 0; i < len; i++) {

printf("%c", str[i] & 127);

printf("\n");

return 0;

Output:

Original string: Hello world

XOR with 127: ^_W`n%!=tX

AND with 127: D]MM%#qjgq

Program :3

a) CaesarCipher

public class CaesarCipher {

public static String encrypt(String plaintext, int shift) {

StringBuilder ciphertext = new StringBuilder();

for (char c : plaintext.toCharArray()) {

if (Character.isLetter(c)) {

int originalAlphabetPosition = c - 'a';


int newAlphabetPosition = (originalAlphabetPosition + shift) % 26;

char newCharacter = (char) ('a' + newAlphabetPosition);

ciphertext.append(newCharacter);

} else {

ciphertext.append(c);

return ciphertext.toString();

public static String decrypt(String ciphertext, int shift) {

return encrypt(ciphertext, 26 - shift);

public static void main(String[] args) {

String plaintext = "hello world";

int shift = 3;

String ciphertext = encrypt(plaintext, shift);

String decrypted = decrypt(ciphertext, shift);

System.out.println("Plaintext: " + plaintext);

System.out.println("Ciphertext: " + ciphertext);

System.out.println("Decrypted text: " + decrypted);

}
Output:

Plaintext: hello world

Ciphertext: khoor zruog

Decrypted text: hello world

b) SubstitutionCipher

public class SubstitutionCipher {

private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

private static final String SUBSTITUTION = "defghijklmnopqrstuvwxyzabc";

public static String encrypt(String plaintext) {

StringBuilder ciphertext = new StringBuilder();

for (char c : plaintext.toCharArray()) {

if (Character.isLetter(c)) {

int index = ALPHABET.indexOf(Character.toLowerCase(c));

char newCharacter = SUBSTITUTION.charAt(index);

ciphertext.append(Character.isUpperCase(c) ? Character.toUpperCase(newCharacter) :
newCharacter);

} else {

ciphertext.append(c);

return ciphertext.toString();

public static String decrypt(String ciphertext) {


StringBuilder plaintext = new StringBuilder();

for (char c : ciphertext.toCharArray()) {

if (Character.isLetter(c)) {

int index = SUBSTITUTION.indexOf(Character.toLowerCase(c));

char newCharacter = ALPHABET.charAt(index);

plaintext.append(Character.isUpperCase(c) ? Character.toUpperCase(newCharacter) :
newCharacter);

} else {

plaintext.append(c);

return plaintext.toString();

public static void main(String[] args) {

String plaintext = "hello world";

String ciphertext = encrypt(plaintext);

String decrypted = decrypt(ciphertext);

System.out.println("Plaintext: " + plaintext);

System.out.println("Ciphertext: " + ciphertext);

System.out.println("Decrypted text: " + decrypted);

Output:

Plaintext: hello world


Ciphertext: khoor zruog

Decrypted text: hello world

c) Hill Cipher

import java.util.Scanner;

public class HillCipher {

// Size of the matrix

private static final int SIZE = 2;

// Encryption key matrix

private static final int[][] KEY = {{3, 4}, {1, 2}};

// Decryption key matrix

private static final int[][] INVERSE_KEY = {{-2, 4}, {1.5, -1.5}};

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the plaintext: ");

String plaintext = scanner.nextLine().toLowerCase().replaceAll("\\s+", "");

// Padding the plaintext with 'x' if its length is not a multiple of 2

if (plaintext.length() % SIZE != 0) {

plaintext += "x";
}

// Convert the plaintext into a matrix of size (SIZE x length)

int[][] plaintextMatrix = new int[SIZE][plaintext.length()];

for (int i = 0; i < plaintext.length(); i++) {

plaintextMatrix[i % SIZE][i] = plaintext.charAt(i) - 'a';

// Multiply the plaintext matrix with the encryption key matrix

int[][] ciphertextMatrix = multiply(KEY, plaintextMatrix);

// Convert the ciphertext matrix back into a string

StringBuilder ciphertextBuilder = new StringBuilder();

for (int i = 0; i < ciphertextMatrix[0].length; i++) {

ciphertextBuilder.append((char) (ciphertextMatrix[0][i] % 26 + 'a'));

ciphertextBuilder.append((char) (ciphertextMatrix[1][i] % 26 + 'a'));

String ciphertext = ciphertextBuilder.toString();

// Decrypt the ciphertext

int[][] decryptedMatrix = multiply(INVERSE_KEY, ciphertextMatrix);

// Convert the decrypted matrix back into a string

StringBuilder decryptedBuilder = new StringBuilder();

for (int i = 0; i < decryptedMatrix[0].length; i++) {

decryptedBuilder.append((char) (Math.floorMod(decryptedMatrix[0][i], 26) + 'a'));


decryptedBuilder.append((char) (Math.floorMod(decryptedMatrix[1][i], 26) + 'a'));

String decrypted = decryptedBuilder.toString();

// Print the results

System.out.println("Plaintext: " + plaintext);

System.out.println("Ciphertext: " + ciphertext);

System.out.println("Decrypted text: " + decrypted);

// Helper method to multiply two matrices

private static int[][] multiply(int[][] a, int[][] b) {

int[][] result = new int[SIZE][b[0].length];

for (int i = 0; i < SIZE; i++) {

for (int j = 0; j < b[0].length; j++) {

for (int k = 0; k < SIZE; k++) {

result[i][j] += a[i][k] * b[k][j];

return result;

Output:

Enter the plaintext: attackatdawn

Plaintext: attackatdawn
Ciphertext: ndwjvzntkryh

Decrypted text: attackatdawn

4.des algo
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class DESExample {


public static void main(String[] args) throws Exception {
// Generate a DES key
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
SecretKey key = keyGenerator.generateKey();

// Create a cipher object and initialize it with the key


Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Encrypt the plaintext


String plaintext = "welcome to java";
byte[] encrypted = cipher.doFinal(plaintext.getBytes());
// Decrypt the ciphertext
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(encrypted);
String decryptedText = new String(decrypted);

// Print the plaintext and decrypted text


System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext: " + new String(encrypted));
System.out.println("Decrypted text: " + decryptedText);
}
}
Output:
Plaintext: welcome to javaCiphertext: L?????"W???+Fig
Decrypted text: welcome to java
5. Blowfish algo
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class BlowfishExample {


public static void main(String[] args) throws Exception {
// Generate a Blowfish key
KeyGenerator keyGenerator =
KeyGenerator.getInstance("Blowfish");
SecretKey key = keyGenerator.generateKey();

// Create a cipher object and initialize it with the key


Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);

// Encrypt the plaintext


String plaintext = "Hello, world!";
byte[] encrypted = cipher.doFinal(plaintext.getBytes());

// Decrypt the ciphertext


cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(encrypted);
String decryptedText = new String(decrypted);

// Print the plaintext and decrypted text


System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext: " + new String(encrypted));
System.out.println("Decrypted text: " + decryptedText);
}
}
Output:
Plaintext: Hello, world!
Ciphertext: ??)??????N#z?
Decrypted text: Hello, world!
6. Program to implement Rijndael algorithm logiC
import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

public class AESExample {

public static void main(String[] args) throws Exception {

// Generate an AES key

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

SecretKey key = keyGenerator.generateKey();

// Create a cipher object and initialize it with the key

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, key);

// Encrypt the plaintext

String plaintext = "Hello, world!";

byte[] encrypted = cipher.doFinal(plaintext.getBytes());

// Decrypt the ciphertext

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] decrypted = cipher.doFinal(encrypted);

String decryptedText = new String(decrypted);


// Print the plaintext and decrypted text

System.out.println("Plaintext: " + plaintext);

System.out.println("Ciphertext: " + new String(encrypted));

System.out.println("Decrypted text: " + decryptedText);

OUTPUT:
Plaintext: Hello, world!
Ciphertext: K???&7??F????
Decrypted text: Hello, world!

Program 9 Diffie-Hellman Key exchange algorithm using html and javascript

<script>
 
// This program calculates the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
 
// 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 be agreed upon the
// public keys G and P
 
// A prime number P is taken
P = 23;
document.write("The value of P:" + P + "<br>");
 
// A primitive root for P, G is taken
G = 9;
document.write("The value of G:" + G + "<br>");
 
// Alice will choose the private key a
// a is the chosen private key
a = 4;
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 = 3;
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 the Alice is:" +
               ka + "<br>");
document.write("Secret key for the Bob is:" +
               kb + "<br>");
 
// This code is contributed by Ankita saini
 
</script>
Note : write this code in notepad save this file with .html extension

Output:

The value of P:23


The value of G:9
The private key a for Alice:4
The private key b for Bob:3
Secret key for the Alice is:9
Secret key for the Bob is:9

Program in java
class GFG{
     
// Power function to return value of a ^ b mod P
private static long power(long a, long b, long p)
{
    if (b == 1)
        return a;
    else
        return (((long)Math.pow(a, b)) % p);
}
 
// Driver code
public static void main(String[] args)
{
    long P, G, x, a, y, b, ka, kb;
     
    // Both the persons will be agreed upon the
    // public keys G and P
     
    // A prime number P is taken
    P = 23;
    System.out.println("The value of P:" + P);
     
    // A primitive root for P, G is taken
    G = 9;
    System.out.println("The value of G:" + G);
     
    // Alice will choose the private key a
    // a is the chosen private key
    a = 4;
    System.out.println("The private key a for Alice:" + a);
     
    // Gets the generated key
    x = power(G, a, P);
     
    // Bob will choose the private key b
    // b is the chosen private key   
    b = 3;
    System.out.println("The private key b for Bob:" + b);
     
    // 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
     
    System.out.println("Secret key for the Alice is:" + ka);
    System.out.println("Secret key for the Bob is:" + kb);
}
}

Output:
The value of P : 23
The value of G : 9

The private key a for Alice : 4


The private key b for Bob : 3

Secret key for the Alice is : 9


Secret Key for the Bob is : 9

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.

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;
public class BlowFishCipher{
public static void main(String[]args) throws Exception{
//create a keygenerator based upon the
KeyGenerator keygenerator=
KeyGenerator.getInstance("Blowfish");
//create a key
SecretKey secretkey=keygenerator.generateKey();
//create a cipher based upon Blowfish
Cipher cipher=Cipher.getInstance("Blowfish");
//initialise cipher to with secretkey
cipher.init(Cipher.ENCRYPT_MODE,secretkey);
//get the text to encrypt
String inputText = "Hello world";
//encrypt message
byte[] encrypted=cipher.doFinal(inputText.getBytes());
//re-initialise the cipher to be in decrypt mode
cipher.init(Cipher.DECRYPT_MODE,secretkey);
byte[] decrypted=cipher.doFinal(encrypted);
System.out.println("Original String: " + inputText);
System.out.println("Encrypted: " + new String(encrypted));
System.out.println("Decrypted: " + new String(decrypted));
}
}
Output:
Original String: Hello worldEncrypted: ?6P??H??u?8???m?
Decrypted: Hello world

8.Write a java program to implement 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);
    }
}
Output:

10. calculate message digest of a text using SHA-1 algo in java.


import java.security.MessageDigest;

import java.util.Scanner;

public class MessageDigestExample {

public static void main(String args[]) throws Exception{


//Reading data from user

Scanner sc = new Scanner(System.in);

System.out.println("Enter the message");

String message = sc.nextLine();

//Creating the MessageDigest object

MessageDigest md = MessageDigest.getInstance("SHA-1");

//Passing data to the created MessageDigest Object

md.update(message.getBytes());

//Compute the message digest

byte[] digest = md.digest();

System.out.println(digest);

//Converting the byte array in to HexString format

StringBuffer hexString = new StringBuffer();

for (int i = 0;i<digest.length;i++) {

hexString.append(Integer.toHexString(0xFF & digest[i]));

System.out.println("Hex format : " + hexString.toString());

Output:
java -cp /tmp/oy4rMs2UiS MessageDigestExample
Enter the message
hi
[B@4d405ef7
Hex format :
c22b5f917834269428d6f51b2c5af4cbde6a42
11.calculate message digest of a text using the md-5
algorithm in 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 = "cryptogrphy";

System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));

Output:
java -cp /tmp/oy4rMs2UiS MD5

Your HashCode Generated by MD5 is: 7a2f82e592d929d2b9e01eaf8685db1e

You might also like