1.
XOR a string with a Zero
AIM: 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>
#include<stdlib.h>
#include<string.h>
int main()
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
str1[i]=str[i]^0;
printf("%c",str1[i]);
printf("\n");
Output:
./a.out
Hello World
2. XOR a string with a 127
AIM: 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<stdlib.h>
#include<string.h>
void main()
char str[]="Hello World";
char str1[11];
char str2[11];
char str3[11];
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
str1[i] = str[i]&127;
-printf("%c",str1[i]);
printf("\n");
for(i=0;i<len;i++)
str3[i] = str2[i]^127;
printf("%c",str3[i]);
printf("\n");
Output:
Hello World
�}�(�*
3. Encryption & Decryption using Cipher Algorithms
AIM: Write a Java program to perform encryption and decryption using the
following algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher
PROGRAM:
d) Ceaser Cipher
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CeaserCipher {
static Scanner sc=new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
System.out.print("Enter any String: ");
String str = br.readLine();
System.out.print("\nEnter the Key: ");
int key = sc.nextInt();
String encrypted = encrypt(str, key);
System.out.println("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("\nDecrypted String is: "
+decrypted); System.out.println("\n");
}
public static String encrypt(String str, int key)
{
String encrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c + (key % 26);
if (c > 'Z')
c = c - 26;
}
else if (Character.isLowerCase(c)) {
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key)
{
String decrypted = "";
for(int i = 0; i < str.length(); i++) {
int c = str.charAt(i);
if (Character.isUpperCase(c)) {
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}
else if (Character.isLowerCase(c)) {
c = c - (key % 26);
if (c < 'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
}
}
Output:
Enter any String: Hello World
Enter the Key: 5
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello World
b) Substitution Cipher
PROGRAM:
import java.io.*;
import java.util.*;
public class SubstitutionCipher {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
String a = "abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";
System.out.print("Enter any string: ");
String str = br.readLine();
String text = "";
char c;
for(int i=0;i<str.length();i++)
{
c = str.charAt(i);
int j = a.indexOf(c);
text = text+b.charAt(j);
}
System.out.println("The encrypted data is: " +text);
}
}
Output:
Enter any string: aceho
The encrypted data is: zxvsl
a) Hill Cipher
PROGRAM:
class Hill
{
static void getKeyMatrix(String key, int keyMatrix[][])
{
int k = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
keyMatrix[i][j] = (key.charAt(k)) % 65;
k++;
}
}
}
static void encrypt(int cipherMatrix[][],
int keyMatrix[][],
int messageVector[][])
{
int x, i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 1; j++)
{
cipherMatrix[i][j] = 0;
for (x = 0; x < 3; x++)
{
cipherMatrix[i][j] +=
keyMatrix[i][x] * messageVector[x][j];
}
cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
}
}
}
static void HillCipher(String message, String key)
{
int [][]keyMatrix = new int[3][3];
getKeyMatrix(key, keyMatrix);
int [][]messageVector = new int[3][1];
for (int i = 0; i < 3; i++)
messageVector[i][0] = (message.charAt(i)) % 65;
int [][]cipherMatrix = new int[3][1];
encrypt(cipherMatrix, keyMatrix, messageVector);
String CipherText="";
for (int i = 0; i < 3; i++)
CipherText += (char)(cipherMatrix[i][0] + 65);
System.out.print(" Ciphertext:" + CipherText);
}
public static void main(String[] args)
{
String message = "HAI";
String key = "GYBNQKURP";
HillCipher(message, key);
}
}
Output:
Ciphertext:YPA
4. Java program for DES algorithm logic
AIM: Write a Java program to implement the DES algorithm logic.
PROGRAM:
import java.util.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
class DES{
public static void main(String[] args) throws IOException, NoSuchAlgorithmException,
InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException
//String we want to encrypt
String message="This is a confidential message.";
byte[] myMessage =message.getBytes(); //string to byte array as DES works on bytes
//Generating Key
KeyGenerator Mygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = Mygenerator.generateKey();
//initializing crypto algorithm
Cipher myCipher = Cipher.getInstance("DES");
//setting encryption mode
myCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] myEncryptedBytes=myCipher.doFinal(myMessage);
//setting decryption mode
myCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] myDecryptedBytes=myCipher.doFinal(myEncryptedBytes);
String encrypteddata=new String(myEncryptedBytes);
String decrypteddata=new String(myDecryptedBytes);
System.out.println("Message : "+ message);
System.out.println("Encrypted - "+ encrypteddata);
System.out.println("Decrypted Message - "+ decrypteddata);
OUTPUT:
Message : This is a confidential message.
Encrypted - ~?0?2??↑*U??>▲????⌂?↑☻??W⌂?yR?
Decrypted Message - This is a confidential message.
5. Program to implement BlowFish algorithm logic
AIM: Write a C/JAVA program to implement the BlowFish algorithm logic.
PROGRAM:
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class BlowfishDemo {
public String encrypt(String msg, String key) throws
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
byte[] KeyData = key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, KS);
String encryptedtext = Base64.getEncoder().
encodeToString(cipher.doFinal(msg.getBytes("UTF-8")));
return encryptedtext;
public String decrypt(String encryptedtext, String key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
byte[] KeyData = key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
byte[] ecryptedtexttobytes = Base64.getDecoder().
decode(encryptedtext);
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, KS);
byte[] decrypted = cipher.doFinal(ecryptedtexttobytes);
String decryptedString =
new String(decrypted, Charset.forName("UTF-8"));
return decryptedString;
public static void main(String[] args) throws Exception {
final String msg = "Nirula";
final String key = "depart369";
System.out.println("Message: " + msg);
BlowfishDemo obj = new BlowfishDemo();
String enc_output = obj.encrypt(msg, key);
System.out.println("Encrypted text: " + enc_output);
String dec_output = obj.decrypt(enc_output, key);
System.out.println("Decrypted text: " + dec_output);
OUTPUT
Message: Nirula
Encrypted text: fSbFKHA3Zn8=
Decrypted text: Nirula
6. Program to implement Rijndael algorithm logic
AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.
PROGRAM:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES
public static String asHex (byte buf[])
StringBuffer strbuf = new StringBuffer(buf.length *2);
int i;
for (i = 0; i < buf.length; i++)
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
return strbuf.toString();
public static void main(String[] args) throws Exception
String message="AES still rocks!!";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message :args[0]).getBytes());
System.out.println("encrypted string: " +asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString + " ");
}
}
OUTPUT:
encrypted string: 9a202b58ce463004fcce14b3791bab257fca7bcb928d28fa56a83b9414ffeb20
Original string: AES still rocks!!
7. Encrypt a string using BlowFish algorithm
AIM: Using Java Cryptography, encrypt the text “Hello world” using BlowFish.
Create your own key using Java keytool.
Program:
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 key generator based upon the Blowfish cipher
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 secret key
cipher.init(Cipher.ENCRYPT_MODE, secretkey);
// get the text to encrypt
String inputText = JOptionPane.showInputDialog("Input your message:");
// encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes());
// re-initialise the cipher to be in decrypt mode
cipher.init(Cipher.DECRYPT_MODE, secretkey);
// decrypt message
byte[] decrypted = cipher.doFinal(encrypted);
// and display the results
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"\nEncrypted text: " + new
String(encrypted) + "\n" + "\nDecrypted text: " + new String(decrypted));
System.exit(0);
OUTPUT:
Input your message: Hello world
Encrypted text: 3ooo&&(*&*4r4
Decrypted text: Hello world
8. RSA Algorithm
AIM: Write a Java program to implement RSA Algoithm.
PROGRAM:
import java.util.*;
import java.math.*;
class RSA
public static void main(String args[])
Scanner sc=new Scanner(System.in);
int p,q,n,z,d=0,e,i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg=sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p=sc.nextInt();
System.out.println("Enter 2nd prime number q");
q=sc.nextInt();
n=p*q;
z=(p-1)*(q-1);
System.out.println("the value of z = "+z);
for(e=2;e<z;e++)
if(gcd(e,z)==1) // e is for public key exponent
break;
System.out.println("the value of e = "+e);
for(i=0;i<=9;i++)
int x=1+(i*z);
if(x%e==0) //d is for private key exponent
d=x/e;
break;
System.out.println("the value of d = "+d);
c=(Math.pow(msg,e))%n;
System.out.println("Encrypted message is : -");
System.out.println(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("Derypted message is : -");
System.out.println(msgback);
}
static int gcd(int e, int z)
if(e==0)
return z;
else
return gcd(z%e,e);
OUTPUT:
Enter the number to be encrypted and decrypted
Enter 1st prime number p
11
Enter 2nd prime number q
13
the value of z = 120
the value of e = 7
the value of d = 103
Encrypted message is : -
85.0
Derypted message is : -
6
9. Diffie-Hellman
AIM: Implement the Diffie-Hellman Key Exchange mechanism. Consider the end user as one of
the parties (Alice) and the other party (bob).
PROGRAM:
import java.util.*;
// create class DiffieHellmanAlgorithmExample to calculate the key for two persons
class DiffieHellmanAlgorithmExample {
public static void main(String[] args)
long P, G, x, a, y, b, ka, kb;
// create Scanner class object to take input from user
Scanner sc = new Scanner(System.in);
System.out.println("Both the users should be agreed upon the public keys G and P");
// take inputs for public keys from the user
System.out.println("Enter value for public key G:");
G = sc.nextLong();
System.out.println("Enter value for public key P:");
P = sc.nextLong();
System.out.println("Enter value for private key a selected by user1 X:");
a = sc.nextLong();
System.out.println("Enter value for private key b selected by user2 Y:");
b = sc.nextLong();
x = calculatePower(G, a, P);
y = calculatePower(G, b, P);
ka = calculatePower(y, a, P);
kb = calculatePower(x, b, P);
// print secret keys of user1 and user2
System.out.println("Secret key for User1 is:" + ka);
System.out.println("Secret key for User2 is:" + kb);
}
// create calculatePower() method to find the value of x ^ y mod P
private static long calculatePower(long x, long y, long P)
long result = 0;
if (y == 1){
return x;
else{
result = ((long)Math.pow(x, y)) % P;
return result;
OUTPUT
Both the users should be agreed upon the public keys G and P
Enter value for public key G: 7
Enter value for public key P: 23
Enter value for private key a selected by user1 X: 3
Enter value for private key b selected by user2 Y: 6
Secret key for User1 is:18
Secret key for User2 is:18
10. SHA-1
AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
PROGRAM:
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAONE {
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 32 bit
while (hashtext.length() < 32) {
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 = "Nirul";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));
String s2 = "abcdefghijklmnopqrstuvwxyz";
System.out.println("\n" + s2 + " : " + encryptThisString(s2));
OUTPUT:
HashCode Generated by SHA-1 for:
Nirula : 6b205d4a49b77372135846f6425b18f1a3b29a25
abcdefghijklmnopqrstuvwxyz : 32d10c7b8cf96570ca04ce37f2a19d84240d3a89
11. Message Digest Algorithm5 (MD5)
AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
PROGRAM:
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 = "Nirula Today";
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
OUTPUT:
Your HashCode Generated by MD5 is: 355ffa6ba8d2aa1102d1db8aa2cc748c