CS Record
CS Record
EX.NO:
DATE:
NUMBER THEORY
AIM:
To write a java program to find GCD of given two numbers using
Eucledian Algorithm.
ALGORITHM:
1) Start
2) Read two numbers
3) Recursively replace a with b and b with a%b
4) When b becomes 0 , return a as GCD
5) Stop
PROGRAM:
import java.lang.*;
import java.util.*;
class Main {
public static int gcd(int a, int b)
{
if (a == 0)
return b;
INFERENCE:
It is used to find prime factors of two numbers by iteratingly
reducing the problem to find gcd of 2 numbers until the reminder equals 0.
RESULT:
The Java program to implement Euclidean algorithm was executed
Successfully.
AIM:
To write a java program to find inverse modulo using extended Euclid
algorithm.
ALGORITHM:
1) Start
2) Initialise s1,s2,t1 = 0 and t2=1
3) Recursively find the following till r2 becomes zero
q = r1/r2; r = r1%r2; t = t1-t2*q;
s = s1-s2*q; r1 = r2; r2 = r; t1 = t2; t2 = t; s1 = s2; s2 = t;
4) Call inverseModulo(r1, r2)
5) Stop.
PROGRAM:
import java.lang.*;
import java.util.*;
public class ExtendedEuclid {
static int t1 = 0,t2=1,s1 = 1,s2 =0;
static int t,q,r,s;
public static int[] inverseModulo(int r1,int r2)
{
if(r2==0) {
int a[] = {r1,t1};
return a;
}
q = r1/r2;
r = r1%r2;
t = t1-t2*q;
s = s1-s2*q;
r1 = r2;
r2 = r;
t1 = t2;
INFERENCE:
It is used to find modulo inverse of an integer and to verify the
correctness of GCD.
RESULT:
The Java program to implement Extended Euclidean algorithm was
executed successfully.
AIM:
To write a java program to find to implement Miller and Rabin’s
algorithm for primality check.
ALGORITHM:
1) Start
2) Miller-Rabin-Test (n, a) // n is the number; a is the base
{
Find m and k such that n − 1 = m x 2k
T ← am mod n
If (T = ±1)return "a prime"
for (i ← 1 to k − 1) // k – 1 is the maximum number of steps
{
T ← T2 mod n
if (T = ±1) return "a composite"
if (T = −1) return "a prime"
}
return "a composite"
}
3) Stop
PROGRAM:
import java.util.*;
public class Main {
static ArrayList<Integer> l = new ArrayList<>();
public static int findFactors(int n)
{
int t = n;
while(n%2==0)
{
l.add(2);
n = n/2;
}
int x = o.nextInt();
if(checkPrime(x))
System.out.println("Prime");
else
System.out.println("Composite");
}
}
INFERENCE:
It is a method to find and prove whether the given number is
prime or not.
RESULT:
The Java program to implement Extended Euclidean algorithm was
executed successfully.
AIM:
To write a java program to implement Euler Totient Function.
ALGORITHM:
1) Start
2) Factorize the number
3) Perform p^c – p^(c-1) Where p is factor and c is its count
4) return sum*= p^c – p^(c-1) as output
5) Stop
PROGRAM:
import java.io.*;
class Main {
INFERENCE:
Euler Totient function phi(n) returns integer from one to n that
are relatively prime to n.
RESULT:
The Java program to implement Euler Totient function was
executed successfully.
EX.NO:
DATE:
SUBSTITUTIONS CIPHER
AIM:
To write a java program to implement Caesar Cipher.
ALGORITHM:
1) Start
2) Read the message and shift value (say 3)
3) Encyrption: For every character , corresponding cipher character is 3 positions
ahead
4) Decyrption: For every character , corresponding plain text character is 3
positions behind
5) Stop
PROGRAM:
class Main
{
public static StringBuffer encrypt(String text, int s)
{
StringBuffer result= new StringBuffer();
INFERENCE:
Caesar Cipher is a substitution method where each letter in plain text is
shifted to certain number of places down or up the alphabet.
RESULT:
The Java program to implement Caesar Cipher was executed
successfully.
AIM:
To write a java program to implement Playfair Cipher.
ALGORITHM:
1) Start
2) Input the message and key from user, replace ‘J’ with ‘Z’ wherever present.
3) Form a 5x5 matrix, populate the matrix first with unique characters from key.
4) Fill the rest of the cells with alphabetical order of characters except J.
5) Using the matrix & map, get the corresponding character for each pair of
characters in message.
6) Return the encrypted string
7) Stop.
PROGRAM:
import java.io.*;
import java.util.*;
class Playfair {
String key;
String plainText;
char[][] matrix = new char[5][5];
this.plainText = plainText.toLowerCase();
}
public void cleanPlayFairKey()
{
LinkedHashSet<Character> set
= new LinkedHashSet<Character>();
key = newKey;
}
public void generateCipherKey()
{
Set<Character> set = new HashSet<Character>();
if (!set.contains(ch))
tempKey += ch;
}
for (int i = 0, idx = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
matrix[i][j] = tempKey.charAt(idx++);
if (len % 2 == 1)
message += 'x'; // dummy character
return message;
}
return pairs;
}
return encText;
}
}
}
}
INFERENCE:
Play Phar Cipher is a digraph substitution cipher where each
pair of letters in plain text are mapped to each pair of letters in Cipher text based on
5x5 grid.
RESULT:
The Java program to implement Playfair Cipher was executed
successfully.
AIM:
To write a java program to find to implement Hill Cipher.
ALGORITHM:
1) Start
2) Choose an n * n invertible key matrix K .
3) Convert plaintext letters to numerical values (A=0, B=1, ..., Z=25).
4) Split numerical plaintext into vectors of size n .
5) Multiply each plaintext vector P by the key matrix K , using C = (K * P)mod
26.
6) Convert the resulting numerical values back to letters to get the ciphertext.
7) Stop.
PROGRAM:
class Main
{
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++;
}
}
}
String CipherText="";
HillCipher(message, key);
}
}
INFERENCE:
Hill cipher is a polygraphic substitution cipher based on linear
algebra. In encryption, each block is multiplied by invertible matrix and to decrypt
each block is multiplied by inverse of matrix used for decryption.
RESULT:
The Java program to implement Hill Cipher was executed
successfully.
AIM:
To write a java program to implement Vigenere Cipher .
ALGORITHM:
1) Start
2) Read the Plain Text and key from user .
3) Repeat key until it equals plain text length .
4) Encryption : (P+K) % 26 .
5) Decryption : (C-K)%26
6) Stop.
PROGRAM:
class Main
{
static String generateKey(String str, String key)
{
int x = str.length();
cipher_text+=(char)(x);
}
return cipher_text;
}
static String originalText(String cipher_text, String key)
{
String orig_text="";
// This function will convert the lower case character to Upper case
static String LowerToUpper(String s)
{
StringBuffer str =new StringBuffer(s);
for(int i = 0; i < s.length(); i++)
{
if(Character.isLowerCase(s.charAt(i)))
{
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
}
s = str.toString();
return s;
}
System.out.println("Ciphertext : "
+ cipher_text + "\n");
INFERENCE:
A poly alphabetic substitution of encrypting alphabets by using
keywords to shift the letters in plain text cyclically.
RESULT:
The Java program to implement Vigenere Cipher was executed
successfully.
AIM:
To write a java program to implement One Time Pad Algorithm.
ALGORITHM:
1) Start.
2) Get the message.
3) Generate a key randomly that corresponds to the message size.
4) For Encryption, traverse each character, transform them by moving up the
key positions, and round off if necessary.
5) For Decryption, traverse each character, transform them by moving down
the key positions, and round off if necessary.
6) Stop.
PROGRAM:
import java.io.*;
public class Main {
public static String stringEncryption(String text, String key)
{
String cipherText = "";
int cipher[] = new int[key.length()];
INFERENCE:
One time pad provides perfect secrecy, where each bit or character
in plain text is XOR with corresponding key of same length The key used only once
and need not be repeated.
RESULT:
The Java program to implement One Time Pad (OTP) Algorithm
was executed successfully.
EX.NO:
DATE:
TRANSPOSITIONAL CIPHERS
AIM:
To implement the Rail fence using Java.
ALGORITHM:
1) Start.
2) Read the String
3) Encryption
For rail value = 2
Rail 1 : Even Position
Rail 2 : Odd Position Concatenate to get Cipher Text
4) Decryption
If even length
val = Math.ceil(ct.length()/depth)
len = ct.length()-1
i = (i+val)%len
If odd length
val = Math.ceil(ct.length()/depth)
len = ct.length()
i = (i+val)%len
5) Stop.
import java.util.Arrays;
class Main {
public static String encryptRailFence(String text,int key)
{
return result.toString();
}
public static String decryptRailFence(String cipher,int key)
{
row = 0;
col = 0;
return result.toString();
}
// Encryption
String s="welcome";
System.out.println("Message = "+s);
System.out.println("Cipher Text: ");
System.out.println(encryptRailFence(s, 2));
}
}
INFERENCE:
RESULT:
Thus the Java program to implement Rail Fence Cipher was
executed successfully.
AIM:
To implement the Row-Column Transformation Cipher using Java.
ALGORITHM:
1) Start.
2) Read string and key
3) No of columns = key size
4) Store Plain text in Row wise
5) Read Plain text in column wise depends on key gives Cipher Text
6) Create another matrix to store cipher text characters based on key
7) Read Cipher Text Characters column wise gives Plain Text back
8) Stop.
PROGRAM:
import java.util.*;
col = key.length();
return cipher.toString();
}
int index = 0;
for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) {
entry.setValue(index++);
}
return msg.toString();
}
INFERENCE:
The row column transformation rearranges the character of plain
text by writing into a grid of specified dimension, then reading the column in
particular order to form the cipher text. Decoding involves the reconstruction of with
and reading the rows to give the original message.
RESULT:
Thus the Java program to implement row column transformation
was executed successfully.
EX.NO:
DATE:
S-DES ALGORITHM
AIM:
To implement the S-DES Algorithm using Java.
ALGORITHM:
1) Start.
2) Key Generation
Generate two sub keys for rounds using the 10 bit master key
3) Encryption
* The 8 bit Plain Text is converted into 8 bit Cipher Text in Two rounds
* Apply Initial Permutation
* In Round Function , use of Expansion Permutation (EP) , Sbox , P4
which processes PT
* Apply Inverse Initial Permutation
4) Decryption
* The 8 bit CipherText is converted into 8 bit PlainText in Two rounds
* It is same as Encryption , only difference is keys are interchanged in
rounds
5) Stop.
import java.io.*;
public class Main {
// int key[]= {0,0,1,0,0,1,0,1,1,1};
int key[] = {
1, 0, 1, 0, 0, 0, 0, 0, 1, 0
};
int P10[] = { 3, 5, 2, 7, 4, 10, 1, 9, 8, 6 };
int P8[] = { 6, 3, 7, 4, 8, 5, 10, 9 };
int[] IP = { 2, 6, 3, 1, 4, 8, 5, 7 };
int[] EP = { 4, 1, 2, 3, 2, 3, 4, 1 };
int[] P4 = { 2, 4, 3, 1 };
int[] IP_inv = { 4, 1, 3, 5, 7, 2, 8, 6 };
int[][] S0 = { { 1, 0, 3, 2 },
{ 3, 2, 1, 0 },
{ 0, 2, 1, 3 },
{ 3, 1, 3, 2 } };
int[][] S1 = { { 0, 1, 2, 3 },
{ 2, 0, 1, 3 },
{ 3, 0, 1, 0 },
{ 2, 1, 0, 3 } };
void key_generation()
{
int key_[] = new int[10];
System.out.println();
System.out.println("Your Key-2 :");
return ciphertext;
}
return output;
}
return decrypted;
}
System.out.println();
System.out.println("Your plain Text is :");
for (int i = 0; i < 8; i++) // printing the
// plaintext
System.out.print(plaintext[i] + " ");
System.out.println();
System.out.println(
System.out.println();
System.out.println(
"Your decrypted Text is :"); // printing the // decrypted text
for (int i = 0; i < 8; i++)
System.out.print(decrypted[i] + " ");
}
}
INFERENCE:
In S-DES Algorithm, a random key is used to encrypt plain text
into ciphertext using symmetric encryption ensures security during transmission of
data by using same key to decrypt ciphertext back, it provides the original data only
authorised users access the data.
RESULT:
Thus, the Java program to implement sdes algorithm was executed
successfully.
EX.NO:
DATE:
RSA ALGORITHM
AIM:
To implement the RSA Algorithm using Java.
ALGORITHM:
1) Start
2) Read two very large prime numbers (p,q)
3) Calculate n = p * q .
4) Calculate the Euler Totient Function as phi = (p-1)*(q-1)
5) Calculate the public key e such that it is co-prime to phi(n) and private key d
such that e*d mod phi(n) = 1
6) Cipher Text , C = P^e(mod n) .
7) Plain Text , P = C^d(mod n).
8) Stop.
PROGRAM:
import java.math.*;
import java.util.*;
class Main {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;
p = 3;
INFERENCE:
The RSA Algorithm encrypts and decrypts data using a pair of keys
derived from very large prime numbers. The security relies on the difficulty of
factoring the product of this prime numbers.
RESULT:
Thus the Java program to implement RSA algorithm was executed
successfully.
EX.NO:
DATE:
DIFFIEE-HELLMAN EXCHANGE ALGORITHM
AIM:
To implement Diffiee-Hellman Exchange Algorithm using Java.
ALGORITHM:
1) Start
2) Choose prime number (p) and its primitive root (alpha)
3) Read Private Key of A
4) Calculate Public Key of A using Math.pow(alpha, privateA))% p
5) Read Private Key of B
6) Calculate Public Key of B using Math.pow(alpha, privateB)% p
7) Generate key at User A Math.pow(publicB, privateA)%p
8) Generate key at User B Math.pow(publicA, privateB)%p
9) Stop
PROGRAM:
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static BigInteger findPrimitiveRoot(BigInteger p) {
ArrayList<BigInteger> list = new ArrayList<>();
for (BigInteger i= BigInteger.valueOf(2); i.compareTo(p) < 0;
i=i.add(BigInteger.ONE))
{
boolean isPrimitiveRoot = true;
for (BigInteger j = BigInteger.ONE; j.compareTo(p.subtract(BigInteger.ONE)) <= 0; j
= j.add(BigInteger.ONE))
INFERENCE:
In Diffiee-Hellman algorithm even if an attacker intercepts the
public key, they cannot easily derive the shared secret key due to the complexity of
computing discrete logarithms.
RESULT:
Thus the java program to implement Diffiee-Hellman was executed
successfully.
EX.NO:
DATE:
ELGAMAL DIGITAL SIGNATURE
AIM:
To implement Elgamal digital signature algorithm using Java.
ALGORITHM:
1) Start.
2) Select a Prime number (q) and find its primitive root
3) Generate random integer Xa (1,q-1)
4) Calculate Ya = (primitive_root)^Xa mod q
5) Generate hash code for message m [1,q-1]
6) Generate random k [1,q-1] and gcd(k,q-1)=1
7) Create Signatures
S1 = (primitive_root)^Xa mod q
S2 = K-1(m-XaS1) mod q-1
8) Verify Signatures
V1 = (primitive_root)^m mod q
V2 = (Ya)^S1 (S1)^S2 mod q *
9) If V1==V2 means , Signature is Valid
10) Stop.
import java.math.BigInteger;
import java.util.*;
public class Main {
public static BigInteger findPrimitiveRoot(BigInteger p) {
ArrayList<BigInteger> list = new ArrayList<>();
for (BigInteger i = BigInteger.valueOf(2); i.compareTo(p) < 0; i =
i.add(BigInteger.ONE))
{
boolean isPrimitiveRoot = true;
for (BigInteger j = BigInteger.ONE; j.compareTo(p.subtract(BigInteger.ONE)) <= 0; j
=
j.add(BigInteger.ONE)) {
BigInteger mod = i.modPow(j, p);
if (list.contains(mod)) {
isPrimitiveRoot = false;
break;
}
list.add(mod);
}
if (isPrimitiveRoot) {
BigInteger n = p.subtract(BigInteger.ONE); //int n = p-1
BigInteger sum = n.multiply(n.add(BigInteger.ONE)).divide(BigInteger.valueOf(2));
BigInteger ls = BigInteger.ZERO;
for (BigInteger ele : list) {
ls = ls.add(ele);
}
if (ls.equals(sum)) {
return i;
}
}
list.clear();
}
return BigInteger.valueOf(-1);
}
static int t1 = 0,t2=1;
static int t,q,r;
public static int inverseModulo(int r1,int r2)
{
if(r2==0)
return t1;
INFERENCE:
ElGamal digital signature is a cryptographic algorithm based on
the ElGamal encryption scheme, relying on the difficulty of solving discrete
logarithms. It involves signing a message using a private key and verifying the
signature with a corresponding public key.Thus the security of the signature relies on
the difficulty of solving the discrete logarithm problem within finite fields.
RESULT:
Thus the java program to implement Elgamal digital signature
algorithm was executed successfully.