C&NS Lab Manual
C&NS Lab Manual
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<stdlib.h>
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:
Hello World
Hello World
INFORMATION SECURITY LAB
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
Hello World
Hello World
INFORMATION SECURITY LAB
AIM: Write a Java program to perform encryption and decryption using the
following algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher
PROGRAM:
a) Ceaser Cipher
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
return encrypted;
if (Character.isUpperCase(c))
{ c = c - (key % 26);
if (c < 'A') {
c = c + 26;
}
} else if (Character.isLowerCase(c))
{ c = c - (key % 26);
INFORMATION SECURITY LAB
if (c < 'a') {
c = c + 26;
}
}
decrypted += (char) c;
}
return decrypted;
}
Output:
Enter any String: hello
Enter the Key: 4
Encrypted String is: lipps
Decrypted String is: hello
INFORMATION SECURITY LAB
b) Substitution Cipher
PROGRAM:
import java.io.*;
import java.util.*;
c) Hill Cipher
PROGRAM:
class HillCipher {
public static void main(String args[]) throws Exception {
String plainText, cipherText;
int block;
Scanner scn = new Scanner(System.in);
System.out.println("Enter plain-text:");
plainText = scn.nextLine();
System.out.println("Enter block size of
matrix:"); block = scn.nextInt();
Hill hill = new Hill(block);
plainText = plainText.replaceAll(" ", "");
cipherText = hill.encrypt(plainText);
System.out.println("Encrypted Text is:\n" + cipherText);
String decryptedText = hill.Decrypt(cipherText);
System.out.println("Decrypted Text is:\n" + decryptedText);
}
}
Output:
Enter a 3 letter string: hai
Encrypted string is :fdx
Inverse Matrix is :
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is: hai
INFORMATION SECURITY LAB
PROGRAM:
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DES {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME =
"DESede"; privateKeySpecmyKeySpec;
privateSecretKeyFactorymySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); public DES() throws Exception {
// TODO code application logic here
myEncryptionKey = "ThisIsSecretEncryptionKey";
myEncryptionScheme =
DESEDE_ENCRYPTION_SCHEME; keyAsBytes =
myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec= new DESedeKeySpec(keyAsBytes);
INFORMATION SECURITY LAB
mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
}
public String encrypt(String unencryptedString)
{ String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText); }
catch (Exception e)
{ e.printStackTrace(); }
returnencryptedString; }
public String decrypt(String encryptedString)
{ String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= bytes2String(plainText); }
catch (Exception e)
{ e.printStackTrace(); }
returndecryptedText; }
private static String bytes2String(byte[] bytes)
{ StringBufferstringBuffer = new
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
void generateSymmetricKey()
{ try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey = getRawKey(knumb);
skeyString = new String(skey);
System.out.println("Blowfish Symmetric key = " + skeyString);
} catch (Exception e) {
System.out.println(e);
}
}
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{ SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
OUTPUT:
Blowfish Symmetric key = ?ó? ^EW??&?L??b]
Encrypted message ¶J. "¼?Y
Decrypted message hello
INFORMATION SECURITY LAB
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));
INFORMATION SECURITY LAB
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " + originalString + " " + asHex(original));
}
INFORMATION SECURITY LAB
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;
// 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);
}
}
INFORMATION SECURITY LAB
OUTPUT:
8. RSA Algorithm
PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one primenumber..
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger(); // ..and another.
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
gcd = fiofn.gcd(e);
intGCD = gcd.intValue();
}
while(y <= 2 || intGCD != 1);
return e;
}
}
OUTPUT:
9. Diffie-Hellman
AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML and
JavaScript. Consider the end user as one of the parties (Alice) and the
JavaScript application as other party (bob).
PROGRAM:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
public class DiffeHellman {
public final static int pValue = 47;
public final static int gValue = 71;
public final static int XaValue = 9;
public final static int XbValue = 14;
public static void main(String[] args) throws Exception
{
// TODO code application logic here
BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new BigInteger(Integer.toString(XaValue));
BigInteger Xb =new BigInteger(Integer.toString(XbValue)); createKey();
int bitLength = 512;
// 512 bits
SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
OUTPUT:
Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29
Public key is: javax.crypto.spec.DHPublicKeySpec@9971ad
INFORMATION SECURITY LAB
10. SHA-1
AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
PROGRAM:
import java.security.*;
public class SHA1 {
public static void main(String[] a)
{ try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));
System.out.println(""); }
catch (Exception e)
{ System.out.println("Exception: "
+e);
}
}
public static String bytesToHex(byte[] b) {
INFORMATION SECURITY LAB
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++)
{ buf.append(hexDigit[(b[j] >> 4) &
0x0f]); buf.append(hexDigit[b[j] & 0x0f]);
} return buf.toString(); }
}
OUTPUT:
Message digest object info:
Algorithm = SHA1
Provider = SUN version 1.6
import java.security.*;
public class MD5 {
public static void main(String[] a) {
// TODO code application logic here
try {
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") = "
+bytesToHex(output)); System.out.println("");
}
INFORMATION SECURITY LAB
catch (Exception e)
{ System.out.println("Exception: " +e); }
}
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++)
{ buf.append(hexDigit[(b[j] >> 4) &
0x0f]); buf.append(hexDigit[b[j] & 0x0f]);
} return buf.toString();
}
}
OUTPUT:
Message digest object info:Algorithm = MD5
Provider = SUN version 1.6
ToString = MD5 Message Digest from SUN, <initialized> MD5("")
= D41D8CD98F00B204E9800998ECF8427E MD5("abc")
=
900150983CD24FB0D6963F7D28E17F72 MD5("abcdefghijklmnopqrstuvwxyz")
= C3FCD3D76192E4007DFB496CCA67E13B
INFORMATION SECURITY LAB