0% found this document useful (0 votes)
10 views

Cis Lab Notes

The document discusses several encryption algorithms including Hill Cipher, Playfair cipher, Vigenere cipher, Rail Fence cipher, Affine cipher, and DES. Code examples are provided for encrypting and decrypting text using each of the algorithms.
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)
10 views

Cis Lab Notes

The document discusses several encryption algorithms including Hill Cipher, Playfair cipher, Vigenere cipher, Rail Fence cipher, Affine cipher, and DES. Code examples are provided for encrypting and decrypting text using each of the algorithms.
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/ 12

HILL CIPHER:

import java.util.Scanner;

public class EncryptionDecryption {


public static void main(String[] args) {
// a[][] denotes encryption key K
// b[][] denotes K inverse
int[][] a = {{17, 17, 5}, {21, 18, 21}, {2, 2, 19}};
int[][] b = {{4, 9, 15}, {15, 17, 6}, {24, 0, 17}};

int[] c = new int[20];


int[] d = new int[20];
char[] msg;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter plain text: ");


msg = scanner.nextLine().toUpperCase().toCharArray();

int n = msg.length;

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


c[i] = msg[i] - 65;
System.out.print(c[i] + " ");
}

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


int t = 0;
for (int j = 0; j < 3; j++) {
t = t + (c[j] * a[j][i]);
}
d[i] = t % 26;
}

System.out.print("\nEncrypted Cipher Text: ");


for (int i = 0; i < 3; i++)
System.out.print((char) (d[i] + 65) + " ");

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


int t = 0;
for (int j = 0; j < 3; j++) {
t = t + (d[j] * b[j][i]);
}
c[i] = t % 26;
}

System.out.print("\nDecrypted Cipher Text: ");


for (int i = 0; i < 3; i++)
System.out.print((char) (c[i] + 65) + " ");

scanner.close();
}
}

pLAYFAIR:
key=input("Enter key")
key=key.replace(" ", "")
key=key.upper()
def matrix(x,y,initial):
return [[initial for i in range(x)] for j in range(y)]

result=list()
for c in key: #storing key
if c not in result:
if c=='J':
result.append('I')
else:
result.append(c)
flag=0
for i in range(65,91): #storing other character
if chr(i) not in result:
if i==73 and chr(74) not in result:
result.append("I")
flag=1
elif flag==0 and i==73 or i==74:
pass
else:
result.append(chr(i))
k=0
my_matrix=matrix(5,5,0) #initialize matrix
for i in range(0,5): #making matrix
for j in range(0,5):
my_matrix[i][j]=result[k]
k+=1

def locindex(c): #get location of each character


loc=list()
if c=='J':
c='I'
for i ,j in enumerate(my_matrix):
for k,l in enumerate(j):
if c==l:
loc.append(i)
loc.append(k)
return loc

def encrypt(): #Encryption


msg=str(input("ENTER MSG:"))
msg=msg.upper()
msg=msg.replace(" ", "")
i=0
for s in range(0,len(msg)+1,2):
if s<len(msg)-1:
if msg[s]==msg[s+1]:
msg=msg[:s+1]+'X'+msg[s+1:]
if len(msg)%2!=0:
msg=msg[:]+'X'
print("CIPHER TEXT:",end=' ')
while i<len(msg):
loc=list()
loc=locindex(msg[i])
loc1=list()
loc1=locindex(msg[i+1])
if loc[1]==loc1[1]:
print("{}{}".format(my_matrix[(loc[0]+1)%5]
[loc[1]],my_matrix[(loc1[0]+1)%5][loc1[1]]),end=' ')
elif loc[0]==loc1[0]:
print("{}{}".format(my_matrix[loc[0]]
[(loc[1]+1)%5],my_matrix[loc1[0]][(loc1[1]+1)%5]),end=' ')
else:
print("{}{}".format(my_matrix[loc[0]]
[loc1[1]],my_matrix[loc1[0]][loc[1]]),end=' ')
i=i+2
def decrypt(): #decryption
msg=str(input("ENTER CIPHER TEXT:"))
msg=msg.upper()
msg=msg.replace(" ", "")
print("PLAIN TEXT:",end=' ')
i=0
while i<len(msg):
loc=list()
loc=locindex(msg[i])
loc1=list()
loc1=locindex(msg[i+1])
if loc[1]==loc1[1]:
print("{}{}".format(my_matrix[(loc[0]-1)%5]
[loc[1]],my_matrix[(loc1[0]-1)%5][loc1[1]]),end=' ')
elif loc[0]==loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1]-
1)%5],my_matrix[loc1[0]][(loc1[1]-1)%5]),end=' ')
else:
print("{}{}".format(my_matrix[loc[0]]
[loc1[1]],my_matrix[loc1[0]][loc[1]]),end=' ')
i=i+2

while(1):
choice=int(input("\n 1.Encryption \n 2.Decryption: \n 3.EXIT"))
if choice==1:
encrypt()
elif choice==2:
decrypt()
elif choice==3:
exit()
else:
print("Choose correct choice")
VIGNERE:

import java.util.Scanner;

public class StreamCipher {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the key stream: ");
int kl = scanner.nextInt();

System.out.print("Enter the length of the plain text stream (Without spaces): ");
int pl = scanner.nextInt();

System.out.println("\nEnter the Key: ");


char[] k = new char[kl];
for (int i = 0; i < kl; ++i) {
k[i] = scanner.next().charAt(0);
}

System.out.println("\nEnter the Plain text: ");


char[] p = new char[pl];
for (int i = 0; i < pl; ++i) {
p[i] = scanner.next().charAt(0);
}

int[][] s = new int[3][pl];

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


if (65 <= p[i] && p[i] <= 91)
s[0][i] = p[i] % 65;
else
s[0][i] = p[i] % 97;
}

for (int i = 0; i < pl; ++i)


System.out.print(s[0][i] + " ");

int count = 0;
while (count < pl) {
for (int i = 0; i < kl; ++i) {
if (65 <= k[i] && k[i] <= 91)
s[1][count + i] = k[i] % 65;
else
s[1][count + i] = k[i] % 97;
}
count = count + kl;
}

System.out.println("\n");
for (int i = 0; i < pl; ++i)
System.out.print(s[1][i] + " ");
System.out.println("\n");
for (int i = 0; i < pl; ++i)
System.out.print(s[2][i] + " ");

System.out.println("\n\nThe cipher text is: ");


char[] cipher = new char[kl];
for (int i = 0; i < pl; ++i) {
s[2][i] = (s[0][i] + s[1][i]) % 26;
cipher[i] = (char) (s[2][i] + 65);

System.out.print(cipher[i] + " ");


}

scanner.close();
}
}

Railfence :

import java.util.Scanner;

public class CipherText {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.next();

char[] s = inputString.toCharArray();
char[] a = new char[10];
char[] b = new char[10];
int k = 0, l = 0, m = 0;

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


if (i % 2 == 0) {
a[k] = s[i];
k++;
} else {
b[l] = s[i];
l++;
}
}

System.out.println("Even positions: ");


for (int i = 0; i < k; i++) {
System.out.print(a[i] + " ");
s[m] = a[i];
m++;
}

System.out.println("\nOdd positions: ");


for (int i = 0; i < l; i++) {
System.out.print(b[i] + " ");
s[m] = b[i];
m++;
}

System.out.println("\n\nCipher text is: " + new String(s));

scanner.close();
}
}

AFFINE CIPHER:

import java.util.*;
public class Affine
{
static int a;
static int b;
public static String encrypt(int a,int b,String msg){
String cipher =" ";
for(int i=0;i<msg.length();i++){
if (msg.charAt(i)!=' '){
cipher=cipher+(char)((((a * (msg.charAt(i) - 'A')) + b)
% 26) + 'A');
}
else{
cipher=cipher+msg.charAt(i);
}
}
return cipher;
}
public static String decrypt(int a,int b,String cipher){
String msg = "";
int a_inv = 0;
int flag = 0;
for(int i=0;i<26;i++){
flag=(a*i)%26;
if(flag==1){
a_inv=i;
}
}
for (int i = 0; i < cipher.length(); i++)
{

if (cipher.charAt(i) != ' ')


{
msg = msg + (char) (((a_inv *
((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
}
else //else simply append space character
{
msg += cipher.charAt(i);
}
}

return msg;
}

public static void main(String[] args){


Scanner sc=new Scanner(System.in);
a=sc.nextInt();
b=sc.nextInt();
String plain = sc.next();
System.out.println(plain);
String encrypted = encrypt(a,b,plain);
System.out.println("CIPHER TEXT:");
System.out.println(encrypted);
String decrypted = decrypt(a,b,encrypted);
System.out.println("DECRYPTED CIPHER TEXT:");
System.out.println(decrypted);

sc.close();
}
}

DES:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;

class Des {

private static final String ALGORITHM = "DES/CBC/PKCS5Padding";


private static final String KEY_ALGORITHM = "DES";

private Cipher encryptCipher;


private Cipher decryptCipher;

public Des(byte[] key, byte[] iv) throws Exception {


SecretKeySpec keySpec = new SecretKeySpec(key, KEY_ALGORITHM);
IvParameterSpec ivSpec = new IvParameterSpec(iv);

encryptCipher = Cipher.getInstance(ALGORITHM);
encryptCipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);

decryptCipher = Cipher.getInstance(ALGORITHM);
decryptCipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
}

public String encrypt(String str) throws Exception {


byte[] utf8 = str.getBytes("UTF-8");
byte[] encrypted = encryptCipher.doFinal(utf8);
return Base64.getEncoder().encodeToString(encrypted);
}
public String decrypt(String str) throws Exception {
byte[] dec = Base64.getDecoder().decode(str);
byte[] decrypted = decryptCipher.doFinal(dec);
return new String(decrypted, "UTF-8");
}

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


Scanner sc=new Scanner(System.in);
final String secretText = sc.nextLine();
System.out.println("Secret Text: " + secretText);

// Generate a random key securely


SecureRandom random = new SecureRandom();
byte[] key = new byte[8];
random.nextBytes(key);

// Generate a random initialization vector


byte[] iv = new byte[8];
random.nextBytes(iv);

Des encrypter = new Des(key, iv);


String encrypted = encrypter.encrypt(secretText);
System.out.println("Encrypted Value: " + encrypted);
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted: " + decrypted);
sc.close();
}
}

MD5:

Python 3 code to demonstrate the


# working of MD5 (string - hexadecimal)

import hashlib

# initializing string
str2hash = input("ENTER MESSAGE :");

# encoding GeeksforGeeks using encode()


# then sending to md5()
result = hashlib.md5(str2hash.encode())

# printing the equivalent hexadecimal value.


print("The hexadecimal equivalent of hash is : ", end ="")
print(result.hexdigest())

SHA ALGORITHM:
import sys
import hashlib

if sys.version_info < (3, 6):


import sha3

# initiating the "s" object to use the


# sha3_224 algorithm from the hashlib module.
s = hashlib.sha3_224()

# will output the name of the hashing algorithm currently in use.


print(s.name)

# will output the Digest-Size of the hashing algorithm being used.


print(s.digest_size)
message=input()

# providing the input to the hashing algorithm.


s.update(message.encode())

print(s.hexdigest())

DIGITAL SIGNATURE:

import hashlib
import base64
from Crypto.PublicKey import DSA
from Crypto.Signature import DSS
from Crypto.Random import get_random_bytes

def sign(datafile, prvKey):


with open(datafile, 'rb') as f:
message = f.read()
hash_object = hashlib.sha256(message)
hash_value = hash_object.digest()
signer = DSS.new(prvKey, 'fips-186-3')
signature = signer.sign(hash_value)
return signature

def verify(datafile, pubKey, sigbytes):


with open(datafile, 'rb') as f:
message = f.read()
hash_object = hashlib.sha256(message)
hash_value = hash_object.digest()
verifier = DSS.new(pubKey, 'fips-186-3')
try:
verifier.verify(hash_value, sigbytes)
return True
except ValueError:
return False

def main():
# Generate a key-pair
key = DSA.generate(1024)
pubk = key.publickey()
prvk = key

datafile = input("Enter the file name for Digital Signature : ")

sigbytes = sign(datafile, prvk)


print("Signature(in hex):", sigbytes.hex())

result = verify(datafile, pubk, sigbytes)


print("Signature Verification Result =", result)

if __name__ == "__main__":
main()

You might also like