CNS Final Lab Manual
CNS Final Lab Manual
WriteaJavaprogramtoperformencryptionanddecryption
usingthefollowingalgorithms:
3 -
a) CeaserCipher
b) SubstitutionCipher
c) HillCipher
4 WriteaJavaprogramtoimplementtheDESalgorithmlogic -
WriteaC/JAVAprogramtoimplementtheBlowFishalgorithmlogic
5 -
WriteaC/JAVAprogramtoimplementtheRijndaelalgorithmlogic.
6 -
UsingJavaCryptography,encryptthetext“Helloworld”usingBlowFish.
7 -
Createyourow nkeyusingJavakeytool.
8 WriteaJavaprogramtoimplementRSAAlgoithm -
ImplementtheDiffie-HellmanKeyExchangemechanism
usingHTMLandJavaScript.Considertheenduserasone
9 oftheparties(Alice)andtheJ avaScriptapplicationasotherparty -
(bob).
CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA
10 -
.
CalculatethemessagedigestofatextusingtheSHA-1algorithminJAVA
11 -
.
1. XORastringwithaZero
1. XORastringwithaZero
AIM: Write a C program that contains a string(char pointer) with a value World’.
The program should XOR each character in this string with 0 and display the result.
PROGRAM:
\Hello
#include<stdlib.h>
main()
{
charstr[]="HelloWorld";
charstr1[11];
Int i,len;
len=strlen(str);
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf("\n");
}
HelloWorldHelloWorld
Output:
2. XORastringwitha127
AIM:Write a C program that contains a string(char pointer)with a value
World’.
The program should AND or and XOR each character in this string with 127 and display the result.
PROGRAM:
\Hello
#include<stdio.h>
#include<stdlib.h>
voidmain()
{
charstr[]="HelloWorld";
charstr1 [11];
charstr2[11]=str[];
inti,le n;
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++)
{
}
}
HelloWorld
str3[i]=str2[i]^127;
printf("%c",str3[i]);
printf("\n");
Output:
HelloWorldHelloWorld
PROGRAM:
a)CeaserCipher
Import java.io.BufferedReader;
Import java.io.IO Exception;
import java.io.InputStreamReader;
import java.util.Scanner;
publicclassCeaserCipher {
staticScannersc=newScanner(System.in);
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
publicstaticvoidmain(St ring[]args)throwsIOException{
//TODOcodeapplicationlogichere
System.out.print("EnteranyString:");
Stringstr=br. readLine();
System.out.print(" \nEntertheKey:");
intkey=sc.nextInt();
String encrypted = encrypt(str, key);
System.out.println("\nEncryptedStringis:"+
encrypted);
Stringdecrypted=decrypt(encrypted,key);
System.out.println("\nDecrypte dStringis:"+decrypted);
System.out.println("\n");
}
Public static String encrypt(Stringstr, intkey)
{
String encrypted ="";
for(inti=0;i<str.length();i++)
{intc=str.charAt(i);
if(Character.isUpperCase(c)){
c=c+(key%26);
if(c>'Z')
}
c=c-26;
elseif(Character.isLowerCase(c)){
c=c+(key%26);
if(c>'z')
}
encrypted+=(char)c;
}
c=c-26;
returnencrypted;
}
public staticStringdecrypt(String str,int key)
{ String decrypted = "";
for(inti=0;i<str.length();i++)
{intc=str.charAt(i);
if(Character.isUpperCase(c)){
c=c-(key%26);
if(c<'A')
}
c=c+26;
elseif(Character.isLowerCase(c)){
c=c-(key%26);
if(c<'a')
}
c=c+26;
decrypted+=(char)c;
}
returndecrypted;
}
}
Output:
EnteranyString:HelloWorldEnterthe
Key:5
EncryptedString
is:MjqqtBtwqiDecryptedStringis:Hello World
b) SubstitutionCipher
PROGRAM:
import java.io.*;
importjava. util.*;
Public class Substitution Cipher{
static
Scannersc=newScanner(System.in);
staticBufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
publicstaticvoidmain(St ring[]args)throwsIOException{
//
TODOcodeapplicationlogichereStringa="abc
defghij klmnopqrstuvwxyz";
Stringb="zyxwvutsrqponmlkjihgfe dcba";
System.out.print("Enteranystring:");
Stringstr=b r.readLine();
Stringdecrypt="";
charc;
for(inti=0;i<str.length();i
++)
{
c=str.charAt(i);
intj=a.indexOf(
c) ;
decrypt=decrypt+b.cha
rAt(j);
}
System.out.println("Theencrypteddatais:"+decrypt);
}
}
Enterany string:aceho
Output:
Theencrypteddatais:zxvsl
c)
HillCiphe rPROGRAM:
Import java.io.*;
Import java.util.*;
Import java.io.*;
Public class HillCipher{
staticfloat[][]decrypt=newfloat[3][1];
staticfloat[][]a=newfloat[3][3];
staticfloat[][] b = new float[3][3];
staticfloat[][] mes = new float[3][1];
staticfloat[][]res=newfloat[3][1];
static Buffered Reader br = new Buffered Reader(new Input Stream Reader(System.in));
staticScannersc=newScanner(System.in);
Public static void main(String[] args)
throws IOException{
//
TODOcodeapplicationlogicheregetkeymes(
);
for(inti=0;i<3;i++)for(intj=0;j<1;j++)for(int k=0;k<3;k++)
{
res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}System.out.print("\nEncryptedstringis:");
for(int i=0;i<3;i++)
{
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(intj=0;j<1;j++)
for(intk=0;k<3;k++)
{
decrypt[i][j]=decrypt[i][j]+b[i][k]*res[k][j];
}System.out.prin t("\nDecryptedstringis:");
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
public static void getkeymes() throws IOException
{System.out.println("Enter3x3matrixforkey(Itshouldbeinversible):");
for(inti=0;i<3;i++)
for(intj=0;j<3;j++)
a[i][j]=sc.
nextFloat();
System.out.print("\nEntera3letterstring:");
Stringmsg=br.rea dLine();
for(inti=0;i<3;i++)
mes[i]
[0]=msg.charAt(i)-97;
}
publicstaticvoidinverse()
{
floatp,q;
float[][] c = a;
for(inti=0;i<3;i++)
for(intj=0;j<3;j
++)
{
if(i==j)b[i][j]=1;
Else b[i][j]=0;
//a[i][j]=sc.nextFloat();
}
for(intk=0;k<3;k++){for(inti=0;i<3;i++){
p=c[i][k]; q=c[k]
[k];
for(intj=0;j<3;j+
+){if(i!=k){
c[i][j]=c[i][j]*q-p*c[k][j];
b[i][j]=b[i][j]*q-p*b[k][j];
}}}}
for(inti=0;i<3;i++)for(intj=0;j<3;j+
+)
{ b[i][j]=b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\nInverseMatrixis:");
for(inti=0;i<3;i++){
for(intj=0;j<3;j++)
System.out.print(b[i][j]+" ");
System.out.print("\n");}
}}
Output:
Enter a 3 letter string:
haiEncrypted string is
:fdxInverseMatrix is:
0.0833333360.41666666-0.33333334
-0.41666666-0.0833333360.6666667
0.5833333-0.083333336-0.33333334
Decryptedstringis:hai
4.JavaprogramforDESalgorithmlogic
AIM:WriteaJavaprogramtoimplementtheDESalgorithmlogic.
PROGRAM:
importjava.util.*;
import
java.io.BufferedReader;
Import java.io.InputStreamRe ader;
Import java.security.spec.KeySpec;
Import javax.cr ypto.Cipher;
Import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
Import javax.crypto.spec.DESe deKeySpec;
Import sun.misc.BASE64Decoder;
Import sun.misc.BASE64Encoder;
public classDES{ privatestaticfinalStringUNICODE_FORMAT="UTF8";
Public static final String DESEDE_ENCRYPTION_SCHEME="DESede";
privateKeySpecmyKeyS pec;
privateSecretKeyFactorymySecretKeyFactory;
privateCiphercipher;
byte[]keyAsByt es;
privateStringmyEncryptionKey;
privateStringmyEncrypt ionScheme;
SecretKeykey;
static BufferedReader br = new BufferedReader(newInputStreamReader(System.in));
publicDES()throwsException{
//TODOcodeapplicationlogicheremy
EncryptionKey="ThisIsSecretEncryptionKey";
myEncryptionScheme=DESEDE_ENCRYPTION_SCHEME;
keyAsByte s=myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec=newDESedeKeySpec(keyAsBytes);
mySecretKeyFactory=SecretKeyFactory.getInstance(myEncryptionScheme);
cipher=Cipher.getInstance(myEncryptionScheme);
key=mySecretKeyFactory.generateSecret(myKeySpec);
}
publicStringencrypt(StringunencryptedString)
{StringencryptedString=null;
try{ cipher.init(Cipher.ENCRYPT_MODE,key);
byte[]plainText=unencryptedString.getBytes(UNICODE_FORMAT);
byte[]encryptedText=cipher.doFinal(plainText)
BASE64Encoderbase64encoder=newBASE64Encoder();
encryptedString=base64enc oder.encode(encryptedTe xt);
}catch(Exceptione){
e.printStackTrace();
}returnencryptedString;
}
publicStringdecrypt(StringencryptedStrin
g)
{
StringdecryptedText=null;
try{ cipher.init(Cipher.DECRYPT_MOD
E,key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[]encryptedText=base64decoder.decodeBuffer(encryptedString);
byte[]plainText=cipher.doFinal(encryptedText);
decryptedText=bytes2String(plainText
);}
catch (Exception e)
{e.printStackTrace();}
returndecryptedT ext;}
Private static String bytes 2 String(byte[]bytes)
{String Buffer string Buffer=new
String Buffer();
for(inti=0;i<bytes.length;i++)
{stringBuffer.append((char)bytes[i]);
}returnstringBuffer.toString();
} publicstaticvoidmain(Stringargs[])throwsException
{ System.out.print("Enter the string:");
DESmyEncryptor=newDES();
StringstringToEncrypt=br.readLine();
String encrypted = myEncryptor.encrypt(stringToEncrypt);
String decrypted = myEncryptor.decrypt(encrypted);
System.out.println("\nStringToEncrypt:"+stringToEncrypt);
System.out.println("\nEncryptedValue:"+encrypted);
System.out.println("\nDecryptedValue:"+decrypted);System.out.println("");
}
}
EncryptedValue:BPQMwc0wKvg=DecryptedVa
lue:Welcome
5.ProgramtoimplementBlowFishalgorithmlogic
AIM:WriteaC/JAVAprogramtoimplementtheBlowFishalgorithmlogic.
PROGRAM:
Import java.io.*;
Import java.io.FileInputStream;
Import java.io.FileOutputStream;
Import java.security.Key;
Import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
importjavax.crypto.KeyGen erator;
importsun.misc.BASE64Encoder;
Public class BlowFish{
publicstaticvoidmain(String[]args)
throwsException{
//TODOcodeapplicationlogichere
KeyGeneratorkeyGenerator= KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
KeysecretKey= keyGenerator.generateKey(); CiphercipherOut=Cipher.getInstance("Blowfish/
CFB/NoPadding");
cipherOut.init(Ci pher.ENCRYPT_MODE,secretKey);
BASE64Encoderencoder=new BASE64Encoder();
byteiv[]=cipherOut.getIV();
if (iv!=null){
System.out.println("InitializationVectoroftheCipher:"+encoder.encode(iv));}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStreamfout = new FileOutputStream("outputFile.txt");
CipherOutputStreamcout=newCipherOutputStream(fout,cipherOut);
intinput= 0;
while((input=fin.read())!=-1){cout.write(input);}
fin.close();cout.close();}}
OUTPUT:
InitializationVectoroftheCipher:dI1MXzW97oQ=
ContentsofinputFil e.txt:Hello World
ContentsofoutputFile.txt:ùJÖ˜NåI“
6.ProgramtoimplementRijndaelalgorithmlogic
AIM:WriteaC/JAVAprogramtoimplementtheRijndaelalgorithmlogic.
PROGRAM:
import java.security.*;
Import javax.crypto.*;
Import javax.crypto.s pec.*;
importjava.io.*;
publicclassAES{
Public static String as
Hex(bytebuf[]){
String Buffer str buf=new String Buffer(buf.length*2);
inti;
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));
}returnstrbuf.toString ();
}
publicstaticvoidmain(String[]args)
throwsException
{
Stringmessage="AESstillrocks!!";
//GettheKeyGenerator
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
kgen.init(128);
// 192 and 256 bits may not be available
//Generatethesecretkey
specs.SecretKeyskey=kgen.generateKey();
byte []raw=skey.getEncoded();
SecretKeySpecskeySpec=newSecretKeySpec(ra
w,"AES");
//Instantiatethecipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,sk eySpec);
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=ciph er.doFinal(encrypted);
StringoriginalString=newString(original);
System.out.println("Originalstring:"+originalString+""+asHex(original));
}
}
OUTPUT:
Inputyourmessage:HelloSCET
Encryptedtext:3ooo&&(*&*4r4Dec
rypted text:Hello SCET
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"\nEncryptedtext:"+newString(encrypted)
+"\n"+"\nDecryptedtext:"+newString( decrypted));
System.exit(0);
}}
OUTPUT:
Inputyourmessage:HelloworldEnc
rypted text:3ooo&&(*&*4r4
Decryptedtext:Hell oworld
8.RSA Algorithm
import
PROGRAM:
java.io.BufferedReader;
Import java.io.InputStreamReade r;
Import java.math.*;
Import java.util.Random;
import java.util.Scanner;
publicclassRSA{
staticScannersc=new Scanner(System.in);
publicstaticvoidmain(String[]args){
//TODO code applicationlogichere
System.out.print("EnteraPrimenumber:
"); BigInteger p = sc.nextBigInteger(); //
Here's one primenumber..
System.out.print("Enteranotherprime
number:");
BigIntegerq=sc.nextBigInteger();// ..andanother.
BigIntegern=p.multiply(q);
BigIntegern2=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigIntegere=generateE( n2);
BigIntegerd=e.modInverse(n2);//Here'sthemultiplicativeinverse
System.out.println("Decryptionkeysare:"+d+","+n);
}
publicstaticBigIntegergenerateE(BigIntegerfiofn)
{inty,intGCD; BigIntegere;
BigIntegergcd;
Randomx=newRandom();
do{
y=x.nextInt(fiofn.intValue()- 1);
Stringz=Integer.toString(y);
e=newBigInteger(z);
gc d=fiofn.gcd(e);
intGCD=gcd.intValue();
}
while(y<=2||intGCD!=1);
returne;
}}
OUTPUT:
EnteraPrimenumber:5
Enteranotherprime number:11
Encryptionkeys are:33,55
Decryptionkeysare:17,55
9. Diffie-Hellman
AIM:Implement the Diffie- Hellman Key Exchange mechanism using HTML and JavaScript.
Consider The one Of The parties(Alice)andtheJavaScriptapplicationas otherparty (bob).
PROGRAM:
import java.math.BigInteger;
Import java.se curity.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;
publicfinalstatic intXbValue=14;
publicstaticvoidmain(String[]args)throwsException
{//TODOcodeapplicationlogichere
BigIntegerp=new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigIntegerXa=new
BigInteger(Integer.toString(XaValue));
BigIntegerXb=newBigInte ger(Integer.toString(XbValue));
createKey();
intbitLength=512; //512bits
SecureRandomrnd=newSecureRandom();
p=BigInteger.probablePrime(bitLength,rnd);
g=BigInteger.probablePrime(bitLength,rn d);
createSpecificKey(p,g);
}
publicstaticvoidcreateKey()
throwsException{
KeyPairGeneratorkpg=KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPairkp=kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpeckspec=(DHPublicKeySpec)k
factory.getKeySpec(kp.getPublic(),DHPublicKeySpec.class);
System.out.println("Publickeyis:"+kspec);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throwsException
{KeyPairGeneratorkpg=KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpecparam=newDHPa rameterSpec(p,g);
kpg.initialize(param);
KeyPairkp=kpg.generateKeyPair();
KeyFactorykfactory=KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpeckspec=(DHPublicKeySpec)kfactory.getKeySpec(kp.getPublic(),DHPubli
cKeySpec.class);
System.out.println("\nPublickeyis:"+kspec);
}
}
OUTPUT:
Publickeyis:javax.crypto.spec.DHPublicKeySpec@5afd29Public
keyis:javax.crypto.spec.DHPublicKeySpec@9971ad
10. SHA-1
AIM:Calculate the message digest of atext using the SHA-1 algorithm in JAVA.
PROGRAM:
Import java.security.*;
Public classSHA1{
Public static void main(String[]a){
try {
Message Digestmd=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());
by te[]output=md.digest();
System.ou t.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.outprintl n();
System.out.println("SHA1(\""+input+"\")="+bytesToHex(output));
System.out.println("");
} catch(Exceptione){
System.out.println("Exception:"+e);
}
}
publicstaticStringbytesToHex(byte[]b){
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf=newStringBuffer();
for (int j=0; j<b.length; j++)
{
buf.append(hexDigit[(b[j]>>4)&0x0f]);
buf.ap pend(hexDigit[b[j] & 0x0f]);
}returnbuf.toString();}
}
OUTPUT:
Messag
digest object info:Algorithm= SHA1
Provider=SUNversion1.6
ToString = SHA1 Message Digest from SUN, <initialized> SHA1("")
=DA39A3EE5E6B4B0D3255BFEF95601890AFD80709SHA1("abc")
=A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D84240D
3A89
11. MessageDigestAlgorithm5(MD5)
AIM:Calculate the message digest of atext using the SHA-1algorithm in JAVA.
PROGRAM:
Import java.security.*;
public classMD5{
Public static void main(String[]a){
//TODOcodeapplicationlogichere
try{
Message Digestmd=MessageDigest.getInstance("MD5");
System. out.println("Message digest object info: ");
System.out.println("Algorithm= "+md.getAlgorithm());
System.out.println("Provider="+md.getPr ovider());
System.out.println("ToString="+md.toString());
String input =
"";
md.update(input.getBytes());
byte[]output=md.dig est();
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.printl n();
System.out.println("MD5(\""+input+"\")="+bytesToHex(output));
System.out.println("");
}catch(Exceptione)
{System.out.println("Exception:"+e);
}
}
publicstaticStringbytesToHex(byte[]b){
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf=newStringBuffer();
for (int j=0; j<b.length; j++)
{
buf.append(hexDigit[(b[j]>>4)&0x0f]);
buf.ap pend(hexDigit[b[j]&0x0f]);}
returnbuf.toString();}}
OUTPUT:
Messagedigestobjectinfo:Algorithm=MD
5
Provider=SUNversion1.6
ToString=MD5MessageDigestfromSUN,
<initialized>MD5("")=D41D8CD98F00B204E98
00998ECF8427EMD5("abc")=900150983CD24FB0D6963F7D28E17F72MD5("abcdefghij
klmnopqrstuvwxyz")=C3FCD3D76192E4007DFB496CCA67E13B