Exp - No: 1 Caeser Cipher Date: Aim

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

EXP.

NO: CAESER CIPHER


1
Date:
AIM:
To implement a program for encrypting a plain text and decrypting a cipher text using
Caesar Cipher (shift cipher) substitution technique

ALGORITHM
1.It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some
fixed number of positions down the alphabet. For example, with a left shift of 3, D would be
replaced by A, E would become B, and so on.
2. The method is named after Julius Caesar, who used it in his private correspondence.
3. The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain
alphabet rotated left or right by some number of positions.
4.The encryption can also be represented using modular arithmetic by first transforming the letters into
numbers, according to the scheme, A = 0, B = 1, Z = 25.
5. Encryption of a letter x by a shift n can be described
mathematically as, En(x) =(x + n) mod26
6. Decryption is performed similarly, Dn (x)=(x - n)
mod26

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void decrypt(char
arr[])
{
int i;
for(i = 0; i<strlen(arr); i++)
{
arr[i] = arr[i] + 10;
}
}
void encrypt(char arr[])
{
int i;
for(i = 0; i<strlen(arr); i++)
{
arr[i] = arr[i] - 10;
}
}
int main()
{

char password[40]; int ch;


printf("Enter a Password:\t"); scanf("%s", password); printf("\nPassword:\t
%s\n",password); encrypt(password); printf("\nEncrypted Password:\t%s\n", password);
decrypt(password);
printf("\nDecrypted Password:\t%s\n", password); return
0; }
OUTPUT:

RESULT:
EXP.NO:7 PLAY FAIR CIPHER
Date:

AIM:
To implement a program to encrypt a plain text and decrypt a cipher text using play fair Cipher
substitution technique.

ALGORITHM

1. The Playfair cipher uses a 5 by 5 table containing a key word or phrase.


2. To generate the key table, first fill the spaces in the table with the letters of the keyword, then
fill the remaining spaces with the rest of the letters of the alphabet in order (usually omitting "
Q" to reduce the alphabet to fit; other versions put both "I" and "J" in the same space).
3.The key can be written in the top rows of the table, from left to right, or in some other pattern, such
as a spiral beginning in the upper-left-hand corner and ending in the center.
4. The keyword together with the conventions for filling in the 5 by 5 table constitutes the cipher
key. To encrypt a message, one would break the message into diagrams (groups of 2 letters) such
that, for example, "HelloWorld" becomes "HE LL OW OR LD", and map them out on the key
table. Then apply the following 4 rules, to each pair of letters in the plaintext:
5. If both letters are the same (or only one letter is left), add an "X" after the first letter. Encrypt the
new pair and continue. Some variants of Playfair use "Q" instead of "X", but any letter, itself
uncommon as a repeated pair, will do.
6.If the letters appear on the same row of your table, replace them with the letters to their
immediate right respectively (wrapping around to the left side of the row if a letter in the
original pair was on the right side of the row).
7.If the letters appear on the same column of your table, replace them with the letters
immediately below respectively (wrapping around to the top side of the column if a letter in
the original pair was on the bottom side of the column).
8.If the letters are not on the same row or column, replace them with the letters on the same
row respectively but at the other pair of corners of the rectangle defined by the original pair.
The order is important - the first letter of the encrypted pair is the one that lies on the same
row as the first letter of the plaintext pair.
9.To decrypt, use the INVERSE (opposite) of the last 3 rules, and the 1st as-is (dropping any extra
"X"s, or "Q"s that do not make sense in the final message when finished).

PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define MX 5
void playfair(char ch1, char ch2, char key[MX][MX])
{ int i, j, w, x, y, z; FILE * out; if ((out =
fopen("cipher.txt", "a+")) == NULL)
{ printf("File Currupted.");
} for (i = 0; i < MX; i+
+)
{ for (j = 0; j < MX; j++)
{ if (ch1 == key[i][j])
{ w = i;
x = j;
} else if (ch2 == key[i][j])
{ y = i; z = j;
}
}
}
//printf("%d%d %d
%d",w,x,y,z); if (w == y) { x =
(x + 1) % 5;
z = (z + 1) % 5;
printf("%c%c", key[w][x], key[y][z]);
fprintf(out, "%c%c", key[w][x], key[y][z]);
} else if (x == z)
{ w = (w + 1) %
5; y = (y + 1) %
5; printf("%c%c", key[w][x], key[y][z]);
fprintf(out, "%c%c", key[w][x], key[y]
[z]);
} else { printf("%c%c", key[w][z], key[y]
[x]); fprintf(out, "%c%c", key[w][z],
key[y][x]);
}
fclose(out);
}

void main() { int i, j, k = 0,

l, m = 0, n;

char key[MX][MX], keyminus[25], keystr[10], str[25] =


{0
}; char
alpa[26] =
{ 'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y ',
'Z' };
printf("\nEnter key:");
gets(keystr);
printf("\nEnter the plain text:");
gets(str); n =
strlen(keystr);
//convert the characters to uppertext
for (i = 0; i < n; i++) {
if (keystr[i] == 'j') keystr[i] = 'i'; else
if (keystr[i] == 'J') keystr[i] = 'I';
keystr[i] = toupper(keystr[i]);
}
//convert all the characters of plaintext to uppertext for (i = 0; i < strlen(str); i++) {
if (str[i] == 'j') str[i] = 'i'; else if (str[i] == 'J') str[i] = 'I';
str[i] = toupper(str[i]);
}
// store all characters except
key j = 0; for (i = 0; i < 26; i++)
{ for (k = 0; k < n; k++)
{ if (keystr[k] == alpa[i]) break;
else if (alpa[i] == 'J') break;
} if (k == n)
{ keyminus[j] = alpa[i];
j++;
}
}
//construct key keymatrix
k = 0; for (i = 0; i < MX;
i++)
{ for (j = 0; j < MX; j++)
{ if (k < n) {
key[i][j] = keystr[k]; k+
+;
} else { key[i][j] =
keyminus[m]; m++; }
printf("%c ", key[i][j]);
}
printf("\n");
}
// construct diagram and convert to cipher text
printf("\n\nEntered text :%s\nCipher Text :", str);
for (i = 0; i < strlen(str); i++) {

if (str[i] == 'J') str[i] = 'I'; if (str[i + 1] ==


'\0') playfair(str[i], 'X', key); else {
if (str[i + 1] == 'J') str[i + 1] = 'I'; if (str[i] ==
str[i + 1]) playfair(str[i], 'X', key); else {

playfair(str[i], str[i + 1], key); i+


+;
}
}
}
getch();
}

OUTPUT:
RESULT:

EXP.NO: HILL CIPHER


2
Date:
AIM
To implement a program to encrypt and decrypt using the Hill cipher substitution technique.

ALGORITHM
1.The Hill cipher is a substitution cipher invented by Lester S. Hill in 1929.
2.Each letter is represented by a number modulo 26. To encrypt a message, each block of n letters is
multiplied by an invertible n × n matrix, again modulus 26.
3.To decrypt the message, each block is multiplied by the inverse of the matrix used for
encryption. The matrix used for encryption is the cipher key, and it should be chosen randomly
from the set of invertible n × n matrices (modulo 26).
4.The ciph er can, be adapted to an alphabet with any number of letters.

6. All arithmetic just needs to be done modulo the number of letters instead of modulo 26.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{ int i,j,ans[25][1],sum=0,mtrx[25][25],end;
char txt[25];
printf("\nEnter the string : ");
scanf("%s",txt);
for(i=0;i<25;i++)
{ if(txt[i]>=97 && txt[i]<122) {
}
else
{ end=i;
break;
}
} for(i=0;i<end;i+
+)
{
txt[i]=txt[i]-'a';
} printf("\nEnter %dX%d key matrix row by
row.\n",end,end); for(i=0;i<end;i++)
{ for(j=0;j<end;j++)
{ printf("key[%d][%d] :
",i,j);
scanf("%d",&mtrx[i][j]);
}
}
printf("\n");

printf("Key matrix is :\n");


for(i = 0; i <end; i++)
{ for(j = 0; j <end; j++)
printf("%d\t", mtrx[i][j]);
printf("\n"); }

for(i=0;i<end;i++)
{ sum=0;
for(j=0;j<end;j++)
{
sum+=mtrx[i][j]*(int)txt[j];
} ans[i]
[0]=sum; }

printf("\nCipher Text is: "); for(i=0;i<end;i+


+)
{ printf(" %c",((ans[i][0])%26)+97);
} getch();
}
OUTPUT:
RESULT:
EXP.NO: DIFFIEE-HELLMAN
3
Date:
AIM:

Develop a program to implement Diffie Hellman Key Exchange Algorithm for encryption and
Decryption.

DESCRIPTION.:
1.Diffie-Hellman key exchange (D-H) is a specific method of securely exchanging cryptographic
keys over a public channel and was one of the first public-key protocols. T
2.he Diffie-Hellman key exchange method allows two parties that have no prior knowledge of each
other to jointly establish a shared secret key over an insecure channel.
3.This key can then be used to encrypt subsequent communications using a symmetric key cipher.
ALGORITHM

Global Public Elements:

1. User A Key Generation: Select private XA where XA < q


XA
Calculate public YA where YA mod q
2. User B Key Generation:
Select private XB where XB < q
XB
Calculate public YB where YB mod q
3. Calculation of Secret Key by User A K = (YB) XA mod q
4. Calculation of Secret Key by User B:

PROGRAM:
import java.util.*;
class Diffe
{ public static void main(String
args[])
{
Scanner sc=new Scanner(System.in); System.out.println("Enter
modulo(p)");
int p=sc.nextInt();
System.out.println("Enter primitive root of "+p); int
g=sc.nextInt();
System.out.println("Choose 1st secretno(Alice)"); int
a=sc.nextInt();
System.out.println("Choose 2nd secretno(BOB)");
int b=sc.nextInt(); int A = (int)Math.pow(g,a)%p;
int B = (int)Math.pow(g,b)%p; int S_A
=(int)Math.pow(B,a)%p;
int S_B =(int)Math.pow(A,b)%p if(S_A==S_B)
{ System.out.println("ALice and Bob can communicate with each other!!!");
System.out.println("They share a secret no = "+S_A);
}else
{
System.out.println("ALice and Bob cannot communicate with each other!!!");
}}}

OUTPUT

RESULT:
EXP.NO: MD5
4
Date:
AIM:
Develop a program to implement Message Digest Algorithm.

ALGORITHM DESCRIPTION:
1. The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-
bit (16-byte) hash value, typically expressed in text format as a 32-digit hexadecimal number.

2. MD5 has been utilized in a wide variety of cryptographic application and is also commonly used to
verify data integrity.

PROGARM:
import java.math.BigInteger; import
java.security.MessageDigest; import
java.security.NoSuchAlgorithmException;
public class MD5 {
public static String getMd5(String input)
{ try
{

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext =
no.toString(16); while
(hashtext.length() < 32)
{ hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e)
{ throw new RuntimeException(e);
} } public static void main(String
args[]) throws
NoSuchAlgorithmException
{
String s = "The quick brown fox jumps overthe lazy dog";
System.out.println("Your HashCode Generated by MD5 is: " +
getMd5(s)); }
}
OUTPUT:
RESULT:
EXP.NO:5 SHA
Date:
AIM:

To develop a program to implement Secure Hash Algorithm (SHA-1)

ALGORITHM DESCRIPTION:

Secured Hash Algorithm-1 (SHA-1):

Step 1: Append Padding Bits….


Message is “padded” with a 1 and as many 0’s as necessary to bring the message
length to 64 bits less than an even multiple of 512.

Step 2: Append Length....

64 bits are appended to the end of the padded message. These bits hold the binary format
of 64 bits indicating the length of the original message.

Step 3: Prepare Processing Functions….


SHA1 requires 80 processing functions defined as:
f(t;B,C,D) = (B AND C) OR ((NOT B) AND D) ( 0 <= t <= 19)
f(t;B,C,D) = B XOR C XOR D (20 <= t <= 39)
f(t;B,C,D) = (B AND C) OR (B AND D) OR (C AND D) (40 <= t<=59) f(t;B,C,D) =
B XOR C XOR D (60 <= t <= 79)
Step 4: Prepare Processing Constants....
SHA1 requires 80 processing constant words defined as:

K(t) = 0x5A827999 ( 0 <= t <= 19)


K(t) = 0x6ED9EBA1 (20 <= t <= 39) K(t) = 0x8F1BBCDC (40
<= t <= 59) K(t) =
0xCA62C1D6 (60 <= t <= 79)
Step 5: Initialize Buffers….
SHA1 requires 160 bits or 5 buffers of words (32 bits):

H0 = 0x67452301
H1 = 0xEFCDAB89 H2 = 0x98BADCFE H3 = 0x10325476 H4 = 0xC3D2E1F0

PROGRAM:

import java.math.BigInteger; import


java.security.MessageDigest; import
java.security.NoSuchAlgorithmException;

public class SHA1 { 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 = "saveetha university";
System.out.println("\n" + s1 + " : " + encryptThisString(s1));

String s2 = "hello world";


System.out.println("\n" + s2 + " : " +
encryptThisString(s2)); }
}

OUTPUT:
RESULT
EXP.NO:6 IMPLEMENTATION OF DIGITAL SIGNATURE STANDARD(DSS)
Date:

AIM:

To write a program to implement the digital signature scheme in java.

ALGORITHM:
Sender Side :
1.The hash code.
2.The random number ‘k’ generated for that particular signature.
3.The private key of the sender i.e., PR(a).
4.A global public key(which is a set of parameters for the communicating principles) i.e., PU(g). These
input to the function will provide us with the output signature containing two components – ‘s’ and ‘r’.
Therefore, the original message concatenated with the signature is sent to the receiver.
Receiver Side :
1.The hash code generated by the receiver.
2.Signature components ‘s’ and ‘r’.
3.Public key of the sender.
4.Global public key.

PROGRAM:
import java.security.KeyPair;
importjava.security.KeyPairGenerato
r; import java.security.PrivateKey;
importjava.security.Signature;
import java.util.Scanner;
public class DSS {
public static void main(String args[]) throws
Exception{ Scanner sc = new Scanner(System.in);

System.out.println("Enter some text");


String msg = sc.nextLine();
KeyPairGeneratorkeyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(2048);KeyPair pair = keyPairGen.generateKeyPair();
PrivateKeyprivKey = pair.getPrivate();
Signature sign = Signature.getInstance("SHA256withDSA");

sign.initSign(privKey); byte[] bytes = "msg".getBytes();


sign.update(bytes);
byte[] signature = sign.sign();
System.out.println("Digital signature for given text: "+new String(signature, "UTF8"));
}
}

RESULT:
EXP NO :8 POLYALPHABETIC CIPHER
DATE:

AIM: To implement a program for encrypting a plain text and decrypting a cipher text using
Poly alphabetic technique.

PROGRAM:
#include <stdio.h>
#include<conio.h>
#include <ctype.h>
#include <string.h>
void encipher();
void decipher();
void main()
{
int choice;
while(1)
{
printf("\n1. Encrypt Text");
printf("\t2. Decrypt Text");
printf("\t3. Exit");
printf("\n\nEnter Your Choice : ");
scanf("%d",&choice);
if(choice == 3)
exit(0);
else if(choice == 1)
encipher();
else if(choice == 2)
decipher();
else
printf("Please Enter Valid Option.");
}
}
void encipher()
{
unsigned int i,j;
char input[50],key[10];
printf("\n\nEnter Plain Text: ");
scanf("%s",input);
printf("\nEnter Key Value: ");
scanf("%s",key);
printf("\nResultant Cipher Text: ");
for(i=0,j=0;i<strlen(input);i++,j++)
{
if(j>=strlen(key))
{ j=0;
}
printf("%c",65+(((toupper(input[i])-65)+(toupper(key[j])-65))%26));

}}
void decipher()
{
unsigned int i,j;
char input[50],key[10];
int value;
printf("\n\nEnter Cipher Text: ");
scanf("%s",input);
printf("\n\nEnter the key value: ");
scanf("%s",key);
for(i=0,j=0;i<strlen(input);i++,j++)
{
if(j>=strlen(key))
{ j=0; }
value = (toupper(input[i])-64)-(toupper(key[j])-64);
if( value < 0)
{ value = value * -1;
}
printf("%c",65 + (value % 26));
}}

OUTPUT:
RESULT:

You might also like