Page 1
Information & System Security AND Network & Internet Security
INDEX
SR. NO. PRACTICAL NAME PG NO. SIGNDATE
1 Symmetric Key Cryptography 04 – 10
2 Asymmetric Key Cryptography 11 – 17
3 Simple Cryptography 18 – 22
4 Caesar Cipher 23 – 25
5 String Encryption using a Pass Phrase 26 – 31
6 String Encryption using Secret Key 32 – 35
7 AES String Encryption and Decryption 36 – 39
8 AES File Encryption and Decryption 40 – 44
9 RSA Algorithm 45 – 48
10 Login Authentication 49 – 50
11 Message Digest 51 – 56
12 Exporting and Importing Keys 57 – 60
13 Hash Functions: RSHash, JSHash, PJWHash 61 – 65
14 66 – 69
Page | 1
Page 2
Information & System Security AND Network & Internet Security
Hash Functions: ELFHash, BKDRHash, SDBMHash
15 Hash Functions: DJBHash, APHash 70 – 72
16 Permissions 73 – 77
Frequently Used Terms in Security and Cryptography
Page | 2
Page 3
Information & System Security AND Network & Internet Security
Security
In the computer industry, ‘SECURITY’ refers to techniques for ensuring that data stored in a
computer cannot be read or compromised by any individuals without authorization. Most security
measures involve data encryption and passwords. Data encryption is the translation of data into a
form that is unintelligible without a deciphering mechanism. A password is a secret word or
phrase that gives a user access to a particular program or system.
Cryptography
The art of protecting information by transforming it (encrypting it) into cipher text. Only those
who possess a secret key can decipher (or decrypt) the message into plain text. Encrypted
messages can sometimes be broken by cryptanalysis, also called codebreaking, although modern
cryptography techniques are virtually unbreakable.
Plain Text refers to any message that is not encrypted.
Plain text is also called clear text.
Cipher Text is the data that has been encrypted or encoded. Cipher text is unreadable until it
has been converted into plain text (decrypted) with a key
Encryption is the translation of data into a secret code.
Encryption is the most effective way to achieve data security. To read an encrypted file, you must
have access to a secret key or password that enables you to decrypt it. Unencrypted data is
called plain text Encrypted data is referred to as cipher text .
There are two main types of encryption:
Asymmetric encryption (also called public-key encryption)
Symmetric encryption .
Asymmetric Key Encryption is a cryptographic system that uses two keys a public key known
to everyone and a private or secret key known only to the recipient of the message.
Symmetric Key Encryption is a type of encryption where the same key is used to encrypt and
decrypt the message. This differs from asymmetric (or public-key) encryption, which uses one key
to encrypt a message and another to decrypt the message.
Decryption is the process of decoding data that has been encrypted into a secret format.
Decryption requires a secret key or password.
Page | 3
Page 4
Information & System Security AND Network & Internet Security
Practical No.:1
Topic: Symmetric Key Cryptography
Aim: Write a program to generate Symmetric Keys of DES, AES, Blowfish, TripleDES, HmacMD5,
HmacSHA1.
Description:
Private Key or Symmetric Key Encryption
Private Key Encryption also referred to as conventional, single-key or symmetric
encryption was the only available option prior to the advent of Public Key encryption in
1976.
This form of encryption has been used throughout history by Julius Caesar, the Navaho
Indians, German U-Boat commanders to present day military, government and private
sector applications.
It is an encryption system in which the sender and receiver of a message share a single,
common key that is used to encrypt and decrypt the message.
A conventional encryption scheme has five major parts:
o Plaintext - this is the text message to which an algorithm is applied.
o Encryption Algorithm - it performs mathematical operations to conduct
substitutions and transformations to the plaintext.
o Secret Key - This is the input for the algorithm as the key dictates the encrypted
outcome.
o Ciphertext - This is the encrypted or scrambled message produced by applying the
algorithm to the plaintext message using the secret key.
o Decryption Algorithm - This is the encryption algorithm in reverse. It uses the
ciphertext, and the secret key to derive the plaintext message.
The most popular symmetric-key system is the Data Encryption Standard (DES), Advanced
Encryption Standard (AES), Blowfish, Triple DES, HmacMD5 etc.
Cipher Algorithms/Encryption Algorithms: It’s a mathematical procedure for performing
encryption on data. Through the use of an algorithm, information is made into meaningless cipher
Page | 4
Page 5
Information & System Security AND Network & Internet Security
text and requires the use of a key to transform the data back into its original form. Blowfish, AES
RC4, RC5, and RC6 are examples of encryption algorithms.
Advanced Encryption Standard (AES): It’s a symmetric 128-bit block data encryption
technique developed by Belgian cryptographers Joan Daemen and Vincent Rijmen.
Data Encryption Standard, (DES): It’s a popular symmetric-key encryption method developed
in 1975 and standardized by ANSI in 1981 as ANSI X.3.92. DES uses a 56-bit key and uses the
block cipher method, which breaks text into 64-bit blocks and then encrypts them.
Triple DES: It’s a mode of the DES encryption algorithm that encrypts data three times. Three
64-bit keys are used, instead of one, for an overall key length of 192 bits (the first encryption is
encrypted with second key, and the resulting cipher text is again encrypted with a third key).
BlowFish: It’s a symmetric encryption algorithm designed by Bruce Schneier in 1993 as an
alternative to existing encryption algorithms, such as DES. Blowfish is a 64-bit block cipher (i.e., a
cryptographic key and algorithm are applied to a block of data rather than single bits) that uses a
key length that can vary between 32 and 448 bits.
Used Class / Interface Details:
1) Class Name: KeyGenerator
o Package: javax.crypto:
o Info: This class provides the functionality of a (symmetric) key generator.
2) Class Name: SecretKeySpec
o Package: javax.crypto.spec.SecretKeySpec
o Info: This class specifies a secret key in a provider-independent fashion. It can be used
to construct a SecretKey from a byte array.
3) Interface Name: SecretKey
o Package: javax.crypto:
o Info: Its only purpose is to group (and provide type safety for) secret keys.
Page | 5
Page 6
Information & System Security AND Network & Internet Security
Source Code:
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
class AlgoSpecificKeyGeneraor
{
String encryptAlgo;
KeyGenerator keyGen;
SecretKey secKey1, secKey2;
AlgoSpecificKeyGeneraor()
{
this.encryptAlgo = "NULL";
}
void setEncryptAlgo(String encryptAlgo)
{
this.encryptAlgo = encryptAlgo;
}
String getEncryptAlgo()
{
return encryptAlgo;
}
void generateSymmetricKeys()
{
try{
keyGen = KeyGenerator.getInstance(encryptAlgo); // a static method from
KeyGenerator class
secKey1 = keyGen.generateKey(); // Generates a 1st secret key.
/* Display encryption algo */
System.out.println("Encryption Algorithm: : " + keyGen.getAlgorithm());
/* Display generated key */
System.out.println("Generated Secret Key : " + secKey1);
/* Display provider */
Page | 6
Page 7
Information & System Security AND Network & Internet Security
System.out.println("Provider of KeyGenerator Object : " +
keyGen.getProvider());
byte[] keyBytes = secKey1.getEncoded(); // generating Key Bytes
/* Constructs a 2nd secret key from the given byte array. */
secKey2 = new SecretKeySpec(keyBytes, encryptAlgo);
System.out.println("Newly generated Secret Key : " + secKey2);
/* Checking for the equality of both secret keys */
System.out.println("Both the Generated Symmetric Keys are equal
(true/false) : " + secKey1.equals(secKey2));
}catch(Exception e){
System.err.println(e);
}
}
}
class GenerateSymKeys
{
public static void main(String[] args)
{
AlgoSpecificKeyGeneraor algoSpecificKeyGenerator = new
AlgoSpecificKeyGeneraor();
/* Blowfish */
algoSpecificKeyGenerator.setEncryptAlgo("Blowfish");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
/* DES */
algoSpecificKeyGenerator.setEncryptAlgo("DES");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
/* AES */
algoSpecificKeyGenerator.setEncryptAlgo("AES");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
Page | 7
Page 8
Information & System Security AND Network & Internet Security
/* DESede: Triple DES Encryption (DES-EDE). */
algoSpecificKeyGenerator.setEncryptAlgo("DESede");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
/* HmacMD5 */
algoSpecificKeyGenerator.setEncryptAlgo("HmacMD5");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
/* HmacSHA 1 */
algoSpecificKeyGenerator.setEncryptAlgo("HmacSHA1");
System.out.println("\n(*) " + algoSpecificKeyGenerator.getEncryptAlgo() + "
Details\n");
algoSpecificKeyGenerator.generateSymmetricKeys();
}
}
Page | 8
Page 9
Information & System Security AND Network & Internet Security
Output:
(*) Blowfish Details
Encryption Algorithm: : Blowfish
Generated Secret Key : javax.crypto.spec.SecretKeySpec@d97ae59a
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@d97ae59a
Both the Generated Symmetric Keys are equal (true/false) : true
(*) DES Details
Encryption Algorithm: : DES
Generated Secret Key : com.sun.crypto.provider.DESKey@fffe7a11
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@fffe7a11
Both the Generated Symmetric Keys are equal (true/false) : true
(*) AES Details
Encryption Algorithm: : AES
Generated Secret Key : javax.crypto.spec.SecretKeySpec@fffe88c3
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@fffe88c3
Both the Generated Symmetric Keys are equal (true/false) : true
(*) DESede Details
Encryption Algorithm: : DESede
Generated Secret Key : com.sun.crypto.provider.DESedeKey@4f964a76
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@4f964a76
Both the Generated Symmetric Keys are equal (true/false) : true
(*) HmacMD5 Details
Encryption Algorithm: : HmacMD5
Generated Secret Key : javax.crypto.spec.SecretKeySpec@c2f27d8c
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@c2f27d8c
Page | 9
Page 10
Information & System Security AND Network & Internet Security
Both the Generated Symmetric Keys are equal (true/false) : true
(*) HmacSHA1 Details
Encryption Algorithm: : HmacSHA1
Generated Secret Key : javax.crypto.spec.SecretKeySpec@64b05f60
Provider of KeyGenerator Object : SunJCE version 1.5
Newly generated Secret Key : javax.crypto.spec.SecretKeySpec@64b05f60
Both the Generated Symmetric Keys are equal (true/false) : true
Page | 10
Page 11
Information & System Security AND Network & Internet Security
Practical No.: 2
Topic: Asymmetric Key Cryptography
Aim: Write a program to generate a 1024-bit Digital Signature Algorithm (DSA) key pair, a 576-bit
DH key pair and a 1024-bit RSA key pair.
Description:
Asymmetric Key Cryptography or Public Key Cryptography:
1976 saw the introduction of a radical new idea into the field of cryptography. This idea
centered around the premise of making the encryption and decryption keys different -
where the knowledge of one key would not allow a person to find out the other.
Public key encryption algorithms are based on the premise that each sender and recipient
has a private key, known only to him/her and a public key, which can be known by anyone.
Each encryption/decryption process requires at least one public key and one private key. A
key is a randomly generated set of numbers/ characters that is used to encrypt/decrypt
information.
A public key encryption scheme has six major parts:
o Plaintext - this is the text message to which an algorithm is applied.
o Encryption Algorithm - it performs mathematical operations to conduct
substitutions and transformations to the plaintext.
o Public and Private Keys - these are a pair of keys where one is used for encryption
and the other for decryption. Ciphertext - this is the encrypted or scrambled
message produced by applying the algorithm to the plaintext message using key.
o Decryption Algorithm - This algorithm generates the ciphertext and the matching
key to produce the plaintext.
In public key cryptography, the private key is generally kept secret, while the public key
may be widely distributed. In a sense, one key "locks" a lock; while the other is required to
unlock it.
RSA, a public-key encryption technology developed by RSA Data Security, Inc. The acronym
stands for Rivest, Shamir, and Adelman, the inventors of the technique. The RSA algorithm is
Page | 11
Page 12
Information & System Security AND Network & Internet Security
based on the fact that there is no efficient way to factor very large numbers. Deducing an RSA
key, therefore, requires an extraordinary amount of computer processing power and time.
The RSA algorithm has become the de facto standard for industrial-strength encryption, especially
for data sent over the Internet.
The Digital Signature Algorithm (DSA) is a United States Federal Government standard or
FIPS for digital signatures. It was proposed by the National Institute of Standards and Technology
(NIST) in August 1991 for use in their Digital Signature Standard (DSS).
Diffie-Hellman (D-H) key exchange is a cryptographic protocol that allows two parties that have
no prior knowledge of each other to jointly establish a shared secret key over an insecure
communications channel. This key can then be used to encrypt subsequent communications
using a symmetric key cipher.
Used Class Details:
1) Class Name: KeyPair
o Package: java.security
o Info: This class is a simple holder for a key pair.
2) Class Name: KeyPairGenerator
o Package: java.security.KeyPairGenerator
o Info: The KeyPairGenerator class is used to generate pairs of public and private keys
o Method:
Name: genKeyPair
Prototype: public final KeyPair genKeyPair()
Description: Generates a key pair. If this KeyPairGenerator has not been initialized
explicitly, provider-specific defaults will be used for the size and other (algorithm-
specific) values of the generated keys. This will generate a new key pair every time
it is called.
3) Class Name: EncodedKeySpec
o Package: java.security.spec.EncodedKeySpec
o Info: This class represents a public or private key in encoded format.
4) Class Name: PKCS8EncodedKeySpec
o Package: java.security.spec.PKCS8EncodedKeySpec
o Info: This class represents the ASN.1 encoding of a private key
5) Class Name: X509EncodedKeySpec
Page | 12
Page 13
Information & System Security AND Network & Internet Security
o Package: java.security.spec.X509EncodedKeySpec
o Info: This class represents the ASN.1 encoding of a public key
Used Interfaces Details:
1) Interface Name: PrivateKey
o Package: java.security:
o Info: It merely serves to group (and provide type safety for) all private key interfaces.
o Method:
Name: getEncoded
Prototype: byte[] getEncoded()
Description: Returns the key in its primary encoding format, or null if this key does not
support encoding.
2) Interface Name: PublicKey
o Package: java.security:
o Info: It merely serves to group (and provide type safety for) all public key interfaces.
o Method:
Name: getEncoded
Prototype: byte[] getEncoded()
Description: Returns the key in its primary encoding format, or null if this key does not
support encoding
Page | 13
Page 14
Information & System Security AND Network & Internet Security
Source Code:
import java.security.*;
import java.security.spec.*;
class AlgoSpecificKeyGeneraor
{
String encryptAlgo;
KeyPairGenerator kpg;
KeyPair keyPair;
PrivateKey privateKey;
PublicKey publicKey;
AlgoSpecificKeyGeneraor(String encryptAlgo)
{
this.encryptAlgo = encryptAlgo;
}
void startProcessing()
{
try
{
kpg = KeyPairGenerator.getInstance(encryptAlgo); // creating an object of
KeyPairGeneartor for specified Algorithm
System.out.println("\n(*) Asymmetric Key Encryption using " +
kpg.getAlgorithm()+ " Algorithm.");
keyPair = kpg.genKeyPair(); // creating an object of KeyPair
privateKey = keyPair.getPrivate();
publicKey = keyPair.getPublic();
/* Priniting Private & Public key Formats */
System.out.println("\n(*) Format of the Private Key : " +
privateKey.getFormat());
System.out.println("(*) Format of the Public Key : " +
publicKey.getFormat());
/* Retrieving bytes for Private & Public Keys */
byte[] privateKeyByte = privateKey.getEncoded();
byte[] publicKeyByte = publicKey.getEncoded();
/* Printing Encoded format of Private & Public Keys */
Page | 14
Page 15
Information & System Security AND Network & Internet Security
System.out.println("\n(*) Encoded Format of the Private Key : " +
privateKeyByte);
System.out.println("(*) Encoded Format of the Public Key : " +
publicKeyByte);
/* Generating Encoded Private & Public Keys Spec */
KeyFactory keyFact = KeyFactory.getInstance(encryptAlgo);
PKCS8EncodedKeySpec privateKeySpec = new
PKCS8EncodedKeySpec(privateKeyByte);
X509EncodedKeySpec publicKeySpec = new
X509EncodedKeySpec(publicKeyByte);
/* Generating Encoded Private & Public Keys */
PrivateKey newPrivateKey = keyFact.generatePrivate(privateKeySpec);
PublicKey newPublicKey = keyFact.generatePublic(publicKeySpec);
/* Printing Encoded format of Newbie Private & Public Keys */
System.out.println("\n(*) Encoded Format of the New Private Key : " +
newPrivateKey.getEncoded());
System.out.println("(*) Encoded Format of the New Public Key : " +
newPublicKey.getEncoded());
/* Printing Original & Newbie Public & Private Keys */
System.out.println("\n*********** Original Private & Public Keys
***********");
System.out.println("(*) Private Key: " + privateKey);
System.out.println("(*) Public Key: " + publicKey);
System.out.println("\n*********** Newly Generated Private & Public Keys
***********");
System.out.println("(*) Private Key: " + newPrivateKey);
System.out.println("(*) Public Key: " + newPublicKey);
/* Checking whether Old and Newbie Keys are same */
System.out.println("\n(*) Both the Generated Private Keys are equal
(true/false) : " + privateKey.equals(newPrivateKey));
System.out.println("(*) Both the Generated Public Keys are equal (true/false)
: " + publicKey.equals(newPublicKey));
Page | 15
Page 16
Information & System Security AND Network & Internet Security
System.out.println("\n+++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++\n");
} catch(Exception e){
System.out.println(e);
}
}
}
class GenerateAsymmetricKeys
{
public static void main(String[] args)
{
AlgoSpecificKeyGeneraor askg1 = new AlgoSpecificKeyGeneraor("DSA");
askg1.startProcessing();
AlgoSpecificKeyGeneraor askg2 = new AlgoSpecificKeyGeneraor("DH");
askg2.startProcessing();
AlgoSpecificKeyGeneraor askg3 = new AlgoSpecificKeyGeneraor("RSA");
askg3.startProcessing();
}
}
Output:
(*) Asymmetric Key Encryption using DSA Algorithm.
(*) Format of the Private Key : PKCS#8
(*) Format of the Public Key : X.509
(*) Encoded Format of the Private Key : [B@16caf43
(*) Encoded Format of the Public Key : [B@66848c
(*) Encoded Format of the New Private Key : [B@8813f2
(*) Encoded Format of the New Public Key : [B@1d58aae
(*) Both the Generated Private Keys are equal (true/false) : true
(*) Both the Generated Public Keys are equal (true/false) : true
++++++++++++++++++++++++++++++++++++++++++++++++++++
Page | 16
Page 17
Information & System Security AND Network & Internet Security
(*) Asymmetric Key Encryption using DH Algorithm.
(*) Format of the Private Key : PKCS#8
(*) Format of the Public Key : X.509
(*) Encoded Format of the Private Key : [B@157f0dc
(*) Encoded Format of the Public Key : [B@863399
(*) Encoded Format of the New Private Key : [B@109a4c
(*) Encoded Format of the New Public Key : [B@201f9
(*) Both the Generated Private Keys are equal (true/false) : true
(*) Both the Generated Public Keys are equal (true/false) : true
++++++++++++++++++++++++++++++++++++++++++++++++++++
(*) Asymmetric Key Encryption using RSA Algorithm.
(*) Format of the Private Key : PKCS#8
(*) Format of the Public Key : X.509
(*) Encoded Format of the Private Key : [B@3a6727
(*) Encoded Format of the Public Key : [B@4a65e0
(*) Encoded Format of the New Private Key : [B@665753
(*) Encoded Format of the New Public Key : [B@ef22f8
(*) Both the Generated Private Keys are equal (true/false) : true
(*) Both the Generated Public Keys are equal (true/false) : true
++++++++++++++++++++++++++++++++++++++++++++++++++++
Practical No.: 3
Topic: Simple Cryptography
Page | 17
Page 18
Information & System Security AND Network & Internet Security
Aim: To write a program to create a standard cryptogram, as it is found in newspapers. The
program will read the quotation to be scrambled into a cryptogram from the standard input. The
resulting table and cryptogram are outputted as a standard output.
E.g. Input Text : TEXT TO BE SCRAMBLED
Output Text : LMBL LG TM RNICDTSMA
Description:
Cryptogram
Cryptogram is a short piece of text encrypted with a simple substitution cipher in which
each letter is replaced by a different letter.
How to solve a cryptogram: This is usually done by frequency analysis and by recognizing
letter patterns in words, such as one letter words.
To solve the puzzle, one must recover the original lettering.
Though once used in more serious applications, they are now mainly printed for
entertainment in newspapers and magazines.
Page | 18
Page 19
Information & System Security AND Network & Internet Security
Source Code:
import java.util.*;
class ProcessCryptogram
{
char [] originalChars = new char[26];
char [] encodedChars = new char[26];
ProcessCryptogram()
{
for(int i=0;i<26;i++)
originalChars[i] = (char)('A' + i);
}
void initialiseEncodedArray()
{
int x=0;
Random rand = new Random();
ArrayList arr = new ArrayList();
for(int i=0;i<26;i++)
{
do
{
x = rand.nextInt(26);
}while(arr.contains(x));
arr.add(x);
encodedChars[i] = (char)('A' + x);
}
arr.clear();
}
void printMapping()
{
System.out.println("\nOriginal Character\tEncoded Character\n");
for(int i=0;i<26;i++)
System.out.println("\t" + originalChars[i] + "\t\t\t" + encodedChars[i]);
}
Page | 19
Page 20
Information & System Security AND Network & Internet Security
void encodeText(String str)
{
System.out.println("\nOriginal Text: " + str);
String s = "\nEncoded Text: ";
char ch;
for(int i=0;i<str.length();i++)
{
ch = str.charAt(i);
if(Character.isUpperCase(ch))
ch = encodedChars[ch-'A'] ;
s+=String.valueOf(ch);
}
System.out.println(s);
}
}
class Cryptogram
{
public static void main(String []args)
{
String inputText="";
do
{
inputText = javax.swing.JOptionPane.showInputDialog(null, "Enter
The Input Text");
}while(inputText.equals("") || !checkString(inputText));
inputText = inputText.toUpperCase();
ProcessCryptogram pc = new ProcessCryptogram();
pc.initialiseEncodedArray();
pc.printMapping();
pc.encodeText(inputText);
}
public static boolean checkString(String str)
{
Page | 20
Page 21
Information & System Security AND Network & Internet Security
boolean flag = true;
for(int i=0 ; i<str.length() ; i++)
{
if(Character.isDigit(str.charAt(i)) == true)
{
flag = false;
break;
}
}
return flag;
}
}
Page | 21
Page 22
Information & System Security AND Network & Internet Security
Output:
Original Character Encoded Charac
A Z
B H
C B
D L
E S
F W
G E
H V
I X
J O
K N
L Q
M U
N F
O R
P P
Q G
R I
S T
T Y
U D
V K
W A
X J
Y C
Z M
Original Text: I LOVE CRYPTOGRAPHY
Encoded Text: X QRKS BICPYREIZPVC
Page | 22
Page 23
Information & System Security AND Network & Internet Security
Practical No.: 4
Topic: Caesar Cipher
Aim: To write a program to perform substitution ciphers to encrypt the plain text to Caesar cipher
and to decrypt it back to plain text
Description:
Caesar Cipher
In cryptography, a Caesar cipher, also known as a Caesar's cipher or the shift cipher, is
one of the simplest and most widely-known encryption techniques.
It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter
some fixed number of positions further down the alphabet.
For example, with a shift of 3, A would be replaced by D, B would become E, and so on.
The method is named after Julius Caesar, who used it to communicate with his generals.
The encryption step performed by a Caesar cipher is often incorporated as part of more
complex schemes, such as the Vigenère cipher, and still has modern application in the
ROT13 system.
As with all single alphabet substitution ciphers, the Caesar cipher is easily broken and in
practice offers essentially no communication security.
Page | 23
The action of a Caesar cipher is to move each letter a number of places down the alphabet. This example is with a shift of three, so that a B in the plaintext becomes E in the ciphertext.
Page 24
Information & System Security AND Network & Internet Security
Source Code:
class CaesarCipherImplementation
{
String originalMsg, encryptedText, decryptedText;
public CaesarCipherImplementation(String originalMsg)
{
this.originalMsg = originalMsg;
encryptedText="";
decryptedText="";
}
public String getEncryptedText()
{
char ch;
for(int i=0;i<originalMsg.length();i++)
{
ch = originalMsg.charAt(i);
if((ch >= 'A' && ch <= 'W') || (ch >= 'a' && ch <= 'w'))
ch = (char)(ch+3);
else if((ch >= 'X' && ch <= 'Z') || (ch >= 'x' && ch <= 'z'))
ch = (char)(ch-23);
encryptedText+=String.valueOf(ch);
} // end for
return encryptedText;
} // end getEncryptedText()
public String getDecryptedText()
{
char ch;
for(int i=0;i<encryptedText.length();i++)
{
ch = encryptedText.charAt(i);
if((ch >= 'D' && ch <= 'Z') || (ch >= 'd' && ch <= 'z'))
ch = (char)(ch-3);
else if((ch >= 'A' && ch <= 'C') || (ch >= 'a' && ch <= 'c'))
Page | 24
Page 25
Information & System Security AND Network & Internet Security
ch = (char)(ch+23);
decryptedText+=String.valueOf(ch);
} // end for
return decryptedText;
} // end getDecryptedText()
} // end of class CaesarCipherImplementation
class CaesarCipher
{
public static void main(String[] args)
{
String inputText="";
do
{
inputText = javax.swing.JOptionPane.showInputDialog(null, "Enter the input
text : ");
}while(inputText.equals(""));
CaesarCipherImplementation cci = new CaesarCipherImplementation(inputText);
System.out.println("\n++++++ Caesar Cipher Demo ++++++");
System.out.println("\n(*) Original Input Text : " + inputText);
System.out.println("\n(*) After Encryption : " + cci.getEncryptedText());
System.out.println("\n(*) After Decryption : " + cci.getDecryptedText());
}
}
Output:
++++++ Caesar Cipher Demo ++++++
(*) Original Input Text : I am very tired
(*) After Encryption : L dp yhub wluhg
(*) After Decryption : I am very tired
Page | 25
Page 26
Information & System Security AND Network & Internet Security
Practical No.: 5
Topic: String Encryption using a Pass Phrase
Aim: To write a program to encrypt an input string by using any input phrase. A salt must be
specified in a SecretKey creation method, and to perform the decryption on the encrypted string
and to compare the decrypted string with the input string.
Note: Use “MD5 and DES” algorithms for encryption and decryption.
E.g.
Input String: Welcome to the world of Cryptography
Input Phrase: My Pass Phrase
Salt: salt ={
(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
(byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
};
Used Interface Details:
1) Interface Name: KeySpec
o Package: java.security.spec
o Info: A (transparent) specification of the key material that constitutes a cryptographic key.
2) Interface Name: SecretKeyFactory
o Package: javax.crypto
o Info: This class represents a factory for secret keys. Key factories are used to convert keys
(opaque cryptographic keys of type Key) into key specifications (transparent
representations of the underlying key material), and vice versa. Secret key factories
operate only on secret (symmetric) keys.
3) Interface Name: AlgorithmParameterSpec
o Package: java.security.spec
o Info: A (transparent) specification of cryptographic parameters. This interface contains no
methods or constants. Its only purpose is to group (and provide type safety for) all
parameter specifications. All parameter specifications must implement this interface.
Page | 26
Page 27
Information & System Security AND Network & Internet Security
Used Class Details:
1) Class Name: Cipher
o Package: javax.crypto.
o Info: This class provides the functionality of a cryptographic cipher for encryption and
decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
Methods:
I) Name: init
Prototype: public final void init(int opmode, Key key,
AlgorithmParameters params)
throws InvalidKeyException,
InvalidAlgorithmParameterExceptio
Description: Initializes this cipher with a key and a set of algorithm parameters. The
cipher is initialized for one of the following four operations: encryption, decryption, key
wrapping or key unwrapping, depending on the value of opmode.
II) Name: doFinal
Prototype: public final byte[] doFinal(byte[] input)
throws IllegalBlockSizeException, BadPaddingException
Description: Encrypts or decrypts data in a single-part operation, or finishes a multiple-
part operation. The data is encrypted or decrypted, depending on how this cipher was
initialized. The bytes in the input buffer, and any input bytes that may have been
buffered during a previous update operation, are processed, with padding (if requested)
being applied. The result is stored in a new buffer.
III) Name: getInstance
Prototype: public static final Cipher getInstance
(String transformation)
throws NoSuchAlgorithmException,
NoSuchPaddingException
Description: Generates a Cipher object that implements the specified transformation. If
the default provider package supplies an implementation of the requested transformation,
an instance of Cipher containing that implementation is returned. If the transformation is
not available in the default provider package, other provider packages are searched.
2) Class Name: PBEKeySpec
Package: javax.crypto.spec
Description: A user-chosen password that can be used with password-based encryption
(PBE). The password can be viewed as some kind of raw key material, from which the
encryption mechanism that uses it derives a cryptographic key.
Page | 27
Page 28
Information & System Security AND Network & Internet Security
Source Code:
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
/**
* -----------------------------------------------------------------------------
* The following example implements a class for encrypting and decrypting
* strings using several Cipher algorithms. The class is created with a key and
* can be used repeatedly to encrypt and decrypt strings using that key.
* Some of the more popular algorithms are:
* Blowfish
* DES
* DESede
* PBEWithMD5AndDES
* PBEWithMD5AndTripleDES
* TripleDES
* -----------------------------------------------------------------------------
*/
class PassPhrase
{
Cipher encrCipher;
Cipher decrCipher;
/**
* Constructor used to create this object. Responsible for setting
* and initializing this object's encrypter and decrypter Chipher instances
* given an input string
*/
public PassPhrase(String iptStr)
{
byte[] salt =
{
(byte)0xA9,(byte)0x9B,(byte)0xC8,(byte)0x32,
(byte)0x56,(byte)0x34,(byte)0xE3,(byte)0x03
};
int iteration = 19;
Page | 28
Page 29
Information & System Security AND Network & Internet Security
try
{
KeySpec keySpec = new PBEKeySpec(iptStr.toCharArray(), salt, iteration);
/*
PBE stands for Password Base Encryption
Algorithm --> PBEWithMD5AndDES
*/
SecretKey secKey =
SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keyS
pec);
/* Cipher Initialisation*/
encrCipher = Cipher.getInstance(secKey.getAlgorithm());
decrCipher = Cipher.getInstance(secKey.getAlgorithm());
AlgorithmParameterSpec algoParam = new
PBEParameterSpec(salt,iteration);
/*Initializes this cipher with a key and a set of algorithm parameters. */
encrCipher.init(Cipher.ENCRYPT_MODE,secKey,algoParam);
decrCipher.init(Cipher.DECRYPT_MODE,secKey,algoParam);
}catch(Exception e){
System.err.println(e);
}
}
public String getEncryptedString(String str)
{
try
{
// Encodes the string into bytes using utf – 8
byte[] utf8 = str.getBytes("UTF8");
// Encrypts or decrypts the data in single part operation
byte[] enc = encrCipher.doFinal(utf8);
// Encodes bytes to Base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}catch(Exception e){
System.err.println(e);
}
return "";
}
Page | 29
Page 30
Information & System Security AND Network & Internet Security
public String getDecryptedString(String str)
{
/* Follow reverse procedure in Decryption */
try
{
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); // Decode
Base64 to get bytes
byte[] utf8 = decrCipher.doFinal(dec); // Decrypt
return new String(utf8,"UTF8");
}catch(Exception e){
System.err.println(e);
}
return "";
}
public static void main(String[] args)
{
System.out.println("\nString Encryption using Pass Phrase");
String secretString = "I Love Security!!!";
String passPhrase = "My Pass Phrase" ;
/* Create Encrypter & Decrypter class */
PassPhrase desEncrypter = new PassPhrase(passPhrase);
/* String Encryption */
String encrStr = desEncrypter.getEncryptedString(secretString);
/* String Decryption */
String decrStr = desEncrypter.getDecryptedString(encrStr);
/* Print Results */
System.out.println("\n\nPBEWithMDAndDES Encrypted Algorithm");
System.out.println("\n\n(*) Inut String: " + secretString);
System.out.println("\n(*) Encrypted String: " + encrStr);
System.out.println("\n(*) Decrypted String: " + decrStr);
}
}
Output:
Page | 30
Page 31
Information & System Security AND Network & Internet Security
String Encryption using Pass Phrase
PBEWithMDAndDES Encrypted Algorithm
(*) Inut String: I Love Security!!!
(*) Encrypted String: aUUYx4A15bPkktti9pwa2vG8XBic23lz
(*) Decrypted String: I Love Security!!!
Page | 31
Page 32
Information & System Security AND Network & Internet Security
Practical No.: 6
Topic: String Encryption using Secret Key
Aim: To write a program that encrypt input string by using SecretKey of the following algorithms,
and then decrypt the encrypted string and compare the decrypted string with the input string:
DES
BlowFish
Triple DES
E.g.
Input String: Welcome to the world of Cryptography
Input Phrase: My Pass Phrase
Description:
DES and Triple DES: The Data Encryption Standard (DES) was developed and endorsed by the
U.S. government in 1977 as an official standard and forms the basis not only for the Automatic
Teller Machines (ATM) PIN authentication but a variant is also utilized in UNIX password
encryption. DES is a block cipher with 64-bit block size that uses 56-bit keys. Due to recent
advances in computer technology, some experts no longer consider DES secure against all
attacks; since then Triple-DES (3DES) has emerged as a stronger method. Using standard DES
encryption, Triple-DES encrypts data three times and uses a different key for at least one of the
three passes giving it a cumulative key size of 112-168 bits.
Blowfish: Blowfish is a symmetric block cipher just like DES or IDEA. It takes a variable-length
key, from 32 to 448 bits, making it ideal for both domestic and exportable use. Bruce Schneier
designed Blowfish in 1993 as a fast, free alternative to the then existing encryption algorithms.
Since then Blowfish has been analyzed considerably, and is gaining acceptance as a strong
encryption algorithm.
Page | 32
Page 33
Information & System Security AND Network & Internet Security
Source Code:
import javax.crypto.*;
class SecKeyEncryptionImplementation
{
String inputText, encrText;
SecretKey secKey;
Cipher encrCipher, decrCipher;
SecKeyEncryptionImplementation(String inputText, String inputAlgo)
{
this.inputText = inputText;
try
{
secKey = KeyGenerator.getInstance(inputAlgo).generateKey();
/* Creating Cipher objects for Encryption & Decryption */
encrCipher = Cipher.getInstance(inputAlgo);
decrCipher = Cipher.getInstance(inputAlgo);
/* Initializing this cipher with a key. */
// for encryption
encrCipher.init(Cipher.ENCRYPT_MODE,secKey);
// for decryption
decrCipher.init(Cipher.DECRYPT_MODE,secKey);
} catch(Exception e){
System.out.println(e);
}
}
String getEncryptedText()
{
try
{
byte[] encrCipherBytes = encrCipher.doFinal(inputText.getBytes());
encrText = new sun.misc.BASE64Encoder().encode(encrCipherBytes);
return encrText;
}catch(Exception e){
System.out.println(e);
Page | 33
Page 34
Information & System Security AND Network & Internet Security
}
return "";
}
String getDecryptedText()
{
try
{
byte[] decrCipherBytes = new
sun.misc.BASE64Decoder().decodeBuffer(encrText);
byte[] dcb = decrCipher.doFinal(decrCipherBytes);
return new String(dcb);
}catch(Exception e){
System.out.println(e);
}
return "";
}
}
class SecKeyEncryption
{
public static void main(String[] args)
{
String inputText="";
do
{
inputText = javax.swing.JOptionPane.showInputDialog(null,"Enter The text
to be Encrypted : ");
} while(inputText.equals(""));
SecKeyEncryptionImplementation sei1 = new
SecKeyEncryptionImplementation(inputText, "DES");
System.out.println("\n(*) Algorithm Used : DES");
System.out.println("(*) Original Text : " + inputText);
System.out.println("(*) Input Text after Encryption : " + sei1.getEncryptedText());
System.out.println("(*) Input Text after Decryption : " + sei1.getDecryptedText());
SecKeyEncryptionImplementation sei2 = new
SecKeyEncryptionImplementation(inputText, "BlowFish");
Page | 34
Page 35
Information & System Security AND Network & Internet Security
System.out.println("\n(*) Algorithm Used : BlowFish");
System.out.println("(*) Original Text : " + inputText);
System.out.println("(*) Input Text after Encryption : " + sei2.getEncryptedText());
System.out.println("(*) Input Text after Decryption : " + sei2.getDecryptedText());
SecKeyEncryptionImplementation sei3 = new
SecKeyEncryptionImplementation(inputText, "DESede");
System.out.println("\n(*) Algorithm Used : DESede");
System.out.println("(*) Original Text : " + inputText);
System.out.println("(*) Input Text after Encryption : " + sei3.getEncryptedText());
System.out.println("(*) Input Text after Decryption : " + sei3.getDecryptedText());
}
}
Output:
(*) Algorithm Used : DES
(*) Original Text : My Name is Rohan
(*) Input Text after Encryption : 8YLiUXaAKustHn25MJToYIdUrRFngGHO
(*) Input Text after Decryption : My Name is Rohan
(*) Algorithm Used : BlowFish
(*) Original Text : My Name is Rohan
(*) Input Text after Encryption : 5dpLwd92vYhRKi5JyQIr9fpOrbuMYWXZ
(*) Input Text after Decryption : My Name is Rohan
(*) Algorithm Used : DESede
(*) Original Text : My Name is Rohan
(*) Input Text after Encryption : 9e3IKjn9Etgh4pSSjRtsgAu5wRxV85fx
(*) Input Text after Decryption : My Name is Rohan
Page | 35
Page 36
Information & System Security AND Network & Internet Security
Practical No.: 7
Topic: AES String Encryption and Decryption
Aim: To write a program to encrypt an input string and decrypt it back to plain-text by making
use of AES algorithm.
Description:
Advanced Encryption Standard:
In cryptography, the Advanced Encryption Standard (AES), also known as Rijndael, is a
block cipher adopted as an encryption standard by the US government.
It is expected to be used worldwide and analysed extensively, as was the case with its
predecessor, the Data Encryption Standard (DES).
The cipher was developed by two Belgian cryptographers, Joan Daemen and Vincent
Rijmen, and submitted to the AES selection process under the name "Rijndael", a
portmanteau comprising the names of the inventors.
For encryption, each round of AES (except the last round) consists of four
Stages of AES Encryption:
1. AddRoundKey — each byte of the state is combined with the round key; each round
key is derived from the cipher key using a key schedule.
2. SubBytes — a non-linear substitution step where each byte is replaced with another
according to a lookup table.
3. ShiftRows — a transposition step where each row of the state is shifted cyclically a
certain number of steps.
4. MixColumns — a mixing operation which operates on the columns of the state,
combining the four bytes in each column using a linear transformation.
The final round replaces the MixColumns stage with another instance of AddRoundKey.
Page | 36
Page 37
Information & System Security AND Network & Internet Security
Source Code:
import javax.crypto.*;
class AESEncrDecrImplementation
{
String orginalText, encrText, decrText;
Cipher encrCipher, decrCipher;
KeyGenerator keyGen;
SecretKey secKey;
AESEncrDecrImplementation(String orginalText)
{
this.orginalText = orginalText;
try
{
/* Creating Cipher objects for Encryption & Decryption */
encrCipher = Cipher.getInstance("AES");
decrCipher = Cipher.getInstance("AES");
/* Generating a KeyGenerator object for the specified algorithm. */
keyGen = KeyGenerator.getInstance("AES");
/* Generating a secret key */
secKey = keyGen.generateKey();
/* Initializing this cipher with a key. */
// for encryption
encrCipher.init(Cipher.ENCRYPT_MODE,secKey);
// for decryption
decrCipher.init(Cipher.DECRYPT_MODE,secKey);
} catch(Exception e) {
System.out.println(e);
}
}
String getEncryptedText()
{
try
{
/** UTF8: Eight-bit UCS Transformation Format
Page | 37
Page 38
Information & System Security AND Network & Internet Security
* java.nio.charset.Charset
*/
/** Other way
byte[] encrCipherBytes =
encrCipher.doFinal(orginalText.getBytes("UTF8")); // Encrypt the text
encrText = new sun.misc.BASE64Encoder().encode(encrCipherBytes);
*/
byte[] encrCipherBytes =
encrCipher.doFinal(orginalText.getBytes());
encrText = new sun.misc.BASE64Encoder().encode(encrCipherBytes);
return encrText;
} catch(Exception e) {
System.out.println(e);
}
return "";
}
String getDecryptedText()
{
try
{
/** Other way
byte[] decrCipherBytes = new
sun.misc.BASE64Decoder().decodeBuffer(encrText);
byte[] utf = decrCipher.doFinal(decrCipherBytes);
decrText = new String(dcb,"UTF8");
*/
byte[] decrCipherBytes = new
sun.misc.BASE64Decoder().decodeBuffer(encrText);
byte[] dcb = decrCipher.doFinal(decrCipherBytes);
decrText = new String(dcb);
return decrText;
} catch(Exception e) {
System.out.println("e" + e);
}
return "";
}
Page | 38
Page 39
Information & System Security AND Network & Internet Security
}
class AESEncrDecr
{
public static void main(String[] args)
{
String inputStr="";
do
{
inputStr = javax.swing.JOptionPane.showInputDialog(null,"Enter a text for
Encryption : ");
}while(inputStr.equals(""));
AESEncrDecrImplementation aed = new AESEncrDecrImplementation(inputStr);
System.out.println("\n(*) Original Text : " + inputStr);
System.out.println("(*) Input Text after Encryption : " + aed.getEncryptedText());
System.out.println("(*) Input Text after Decryption : " + aed.getDecryptedText());
}
}
Output:
(*) Original Text : Security is a nice topic
(*) Input Text after Encryption : IwDAEPoXLe55nkaTHfTLbEQCFAWi88551ZK5j/lgztQ=
(*) Input Text after Decryption : Security is a nice topic
Practical No.: 8
Topic: AES File Encryption and Decryption
Page | 39
Page 40
Information & System Security AND Network & Internet Security
Aim: To write a program that encrypt an input file and decrypt it back to original text file by
making use of AES algorithm. Use the following initialization vector for an algorithm parameter
specification:
8-byte initialization vector:
iv = {
(byte)0x8E, 0x12, 0x39, (byte)0x9C,
0x07, 0x72, 0x6F, 0x5A
};
Used Class Details:
1) Class Name: CipherInputStream
o Package: javax.crypto
o Description: A CipherInputStream is composed of an InputStream and a Cipher so that
read() methods return data that are read in from the underlying InputStream but have
been additionally processed by the Cipher. The Cipher must be fully initialized before
being used by a CipherInputStream. For example, if the Cipher is initialized for decryption,
the CipherInputStream will attempt to read in data and decrypt them, before returning the
decrypted data.
2) Class Name: CipherOutputStream
o Package: javax.crypto
o Description: A CipherOutputStream is composed of an OutputStream and a Cipher so
that write() methods first process the data before writing them out to the underlying
OutputStream. The cipher must be fully initialized before being used by a
CipherOutputStream. For example, if the cipher is initialized for encryption, the
CipherOutputStream will attempt to encrypt data before writing out the encrypted data.
Page | 40
Page 41
Information & System Security AND Network & Internet Security
Source Code:
import java.security.*;
import javax.crypto.*;
import java.security.spec.*;
import javax.crypto.spec.*;
import java.io.*;
class AESFileEncrDecr
{
Cipher eCipher;
Cipher dCipher;
KeyGenerator keyGen;
SecretKey secKey;
byte[] buffer = new byte[100];
AESFileEncrDecr()
{
try
{
byte[]initialisationVec = new byte[]
{
(byte)0x8E, 0x12, 0x39, (byte)0x9C,
0x07, 0x72, 0x6F, 0x5A
};
/* This class specifies an initialization vector (IV). */
AlgorithmParameterSpec paramSpec = new
IvParameterSpec(initialisationVec);
/* Generateting Keys */
keyGen = KeyGenerator.getInstance("DES");
secKey = keyGen.generateKey();
/* Cipher Creation */
/* Specified Transformation is of the form: algorithm/mode/padding */
eCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
dCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
/* Initialise the Cipher for Encryption & Decryption */
eCipher.init(Cipher.ENCRYPT_MODE, secKey, paramSpec);
Page | 41
Page 42
Information & System Security AND Network & Internet Security
dCipher.init(Cipher.DECRYPT_MODE, secKey, paramSpec);
}catch(Exception e){
System.err.println(e);
}
}
/* Encrypt data in file using AES Algorithm */
public void encryptData(InputStream iptStrm, OutputStream optStrm)
{
int byteRead = 0;
try
{
/* Encrypted Bytes will be written OutputStream */
optStrm = new CipherOutputStream(optStrm, eCipher);
/* Read the bytes one by one and write them to Output Stream */
while((byteRead = iptStrm.read(buffer)) >= 0)
{
optStrm.write(buffer, 0 , byteRead);
}
optStrm.close();
}catch(Exception e){
System.err.println(e);
}
}
/* Decrypt data in file using AES Algorithm */
public void decryptData(InputStream iptStrm, OutputStream optStrm)
{
int byteRead = 0;
try
{
/* Decrypted Bytes will be written OutputStream */
iptStrm = new CipherInputStream(iptStrm, dCipher);
/* Read the bytes one by one and write them to Output Stream */
while((byteRead = iptStrm.read(buffer)) >= 0)
{
Page | 42
Page 43
Information & System Security AND Network & Internet Security
optStrm.write(buffer, 0 , byteRead);
}
optStrm.close();
}catch(Exception e){
System.err.println(e);
}
}
public static void main(String[] args)
{
try
{
AESFileEncrDecr afed = new AESFileEncrDecr();
afed.encryptData(new FileInputStream("MainFile.txt"), new
FileOutputStream("Encrypted.txt"));
afed.decryptData(new FileInputStream("Encrypted.txt"), new
FileOutputStream("Decrypted.txt"));
}catch(Exception e){
System.err.println(e);
}
}
}
Output:
Running the program:
Page | 43
Page 44
Information & System Security AND Network & Internet Security
Make 3 files in the same directory where program is stored.
1. MainFile.txt
2. Encrypted.txt
3. Decrypted.txt
Main File Contents:
Hello, I am Rohan. You can call me Ron. I am doing my MSc from University Department of
Computer Science. I like to study Security.
Thank you Guys!!!
Encrypted File Contents:
¥})ÛˆÞƒ}Ý·ôŽ¤…Mß~¡¬¿Ø”°l¬«Œ¤Œ%Ùü&éüí7� éð'v€ßPGÜÇÈUL—‚åðˆ
ñPtÌnµÖZxUœÙ¬®3FW�
L¤¤àP?èÁ“µ¿ÉÎl Ë*…9ZÚ\ZÝ!ÑñyíqîþA¾þv/ïxÐròƒ*,1à³NòÞ§´º}.O�
Decrypted File Contents:
Hello, I am Rohan.You can call me Ron. I am doing my MSc from University Department of
Computer Science. I like to study Security.
Thank you Guys!!!
Page | 44
Page 45
Information & System Security AND Network & Internet Security
Practical No.: 9
Topic: RSA Algorithm
Aim: To write a program to input a number and encrypt that number and then decrypt it back to
original, with the help of RSA algorithm.
Description:
RSA algorithm
RSA algorithm is mainly a public key encryption technique used widely in network
communication like in Virtual Private Networks (VPNs).
In public key encryption technique, a key is split into two keys and they are called as
public and private keys. Public key is advertised to the world and private key is kept
secret. It is not possible to generate private key using the public key. So, someone who
knows the public key cannot decrypt a message after it has been encrypted using the
public key.
RSA algorithm is a block cipher technique in which plain text and cipher texts are integers
between ‘0’ and ‘n-1’ from some ‘n’.
In RSA algorithm encryption and decryption are of following form, for some plain text M and
cipher text C:
C = Me mod n
M = C^d mod n
Both sender and receiver must know the value of ‘n’. The sender knows the value of ‘e’
and only receiver knows the value of‘d’. Thus, this is a public-key encryption algorithm
with a public key of KU= {e, n} and private key of KR= {d, n}. For the algorithm to be
satisfactory for public-key encryption, the following requirement must be met:
1. It is possible to find values of e, d, n such that Med = M mod n for all M<n.
2. It is relatively easy to calculate Me and Cd for all values of M<n.
3. It is infeasible to determine d given e and n.
Page | 45
Page 46
Information & System Security AND Network & Internet Security
Source Code:
import java.security.*;
import javax.crypto.Cipher;
class RSAAlgoImplementation
{
String inputNo, encrNo, decrNo;
KeyPairGenerator kpg;
KeyPair kp;
Cipher encrCipher, decrCipher;
PrivateKey privKey;
PublicKey pubKey;
RSAAlgoImplementation(int input)
{
inputNo = String.valueOf(input);
encrNo = "";
decrNo = "";
try{
kpg = KeyPairGenerator.getInstance("RSA");
kp = kpg.generateKeyPair();
privKey = kp.getPrivate();
pubKey = kp.getPublic();
encrCipher = Cipher.getInstance("RSA");
decrCipher = Cipher.getInstance("RSA");
encrCipher.init(Cipher.ENCRYPT_MODE, pubKey); // initialising Cipher for
Encryption using receivers Public Key at Sender's side
decrCipher.init(Cipher.DECRYPT_MODE, privKey); // initialising Cipher for
Decryption using receivers Private Key at reciver's side
}catch(Exception e){
System.out.println(e);
}
}
void generateEncryptedText()
{
try{
Page | 46
Page 47
Information & System Security AND Network & Internet Security
byte []encrBytes = encrCipher.doFinal(inputNo.getBytes());
encrNo = new sun.misc.BASE64Encoder().encode(encrBytes)
; // encryption process
System.out.println("(*) Input No after Encryption : " + encrNo);
}catch(Exception e){
System.out.println(e);
}
}
void generateDecryptedText()
{
try{
byte[] decrBytes = new sun.misc.BASE64Decoder().decodeBuffer(encrNo);
// decryption process
byte[] finalDecrBytes = decrCipher.doFinal(decrBytes);
decrNo = new String(finalDecrBytes);
System.out.println("(*) Input No after Decryption : " + decrNo);
}catch(Exception e){
System.out.println(e);
}
}
}
class RSAAlgo
{
public static void main(String[] args)
{
String str="";
do
{
str = javax.swing.JOptionPane.showInputDialog(null, "Enter the number for
Encryption : ");
}while(!isNumber(str));
RSAAlgoImplementation rsai = new RSAAlgoImplementation(Integer.parseInt(str));
System.out.println("\n ************* RSA Implementation *************");
System.out.println("\n(*) Input No : " + str);
rsai.generateEncryptedText();
rsai.generateDecryptedText();
Page | 47
Page 48
Information & System Security AND Network & Internet Security
}
public static boolean isNumber(String num)
{
boolean flag = true;
for(int i=0 ; i<num.length() ; i++)
{
if(Character.isLetter(num.charAt(i)) ||
Character.isWhitespace(num.charAt(i)))
{
flag = false;
break;
}
}
if(num.equals(""))
flag = false;
return flag;
}
}
Output:
************* RSA Implementation *************
(*) Input No : 123
(*) Input No after Encryption :
Jn0MWptxKxeiMmG/PLdK0qiZQZ4YxHF9N4P4+xbxjK5gMU9AC1mVWUeEIcMEytTdzlbukggvXSGo
aVIS6y0yn8da5DImKyhJJpKIMw/OFXuWErdBy/2jnFff7jYHmOOlCga26or1Xle47iXlq4eQMkFE
RuH35LM+YfP5FTiMDXE=
(*) Input No after Decryption : 123
Page | 48
Page 49
Information & System Security AND Network & Internet Security
Practical No.: 10
Topic: Login Authentication
Aim: To write a client-server program in which the Server authenticates a Client and displays the
authentication information accordingly
Source Code:
import java.io.*;
class LoginAuthentication
{
public static void main(String[] args) throws Exception
{
System.out.println("\n(*) Login Authentication (*)\n");
System.out.print("(*) Enter the Username: ");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String userName = bf.readLine();
System.out.print("\n(*) Enter the Password: ");
bf = new BufferedReader(new InputStreamReader(System.in));
String pwd = bf.readLine();
if(userName.equals("rohan") && pwd.equals("ron"))
{
System.out.println("\nWelcome!!!\nLogin Successful.");
System.exit(0);
}
else if(userName.equals("raj") && pwd.equals("rohan"))
{
System.out.println("\nWelcome!!!\nLogin Successful.");
System.exit(0);
}
if(userName.equals("ron") && pwd.equals("raj"))
{
System.out.println("\nWelcome!!!\nLogin Successful.");
System.exit(0);
}
else
Page | 49
Page 50
Information & System Security AND Network & Internet Security
{
System.out.println("\nGet Lost!!!\nYou can't hack my System. :P");
System.exit(0);
}
}
}
Output:
Case 1: Successful Login
(*) Login Authentication (*)
(*) Enter the Username: rohan
(*) Enter the Password: ron
Welcome!!!
Login Successful.
Case 2: Unsuccessful Login
(*) Login Authentication (*)
(*) Enter the Username: ron
(*) Enter the Password: rohan
Get Lost!!!
You can't hack my System. :P
Page | 50
Page 51
Information & System Security AND Network & Internet Security
Practical No.: 11
Topic: Message Digest
Aim: To write a program to input a string and with the help of Message Digest (MD) check
whether the data is not corrupted.
Description:
What is a message digest?
A message digest is a number which is created algorithmically from a file and represents
that file uniquely. If the file changes, the message digest will change.
A message digest is a 128-bit cryptographically strong one-way hash function of the
message. It is somewhat analogous to a "checksum" or CRC error checking code, in that it
compactly "represents" the message and is used to detect changes in the message. Unlike
a CRC, however, it is computationally infeasible for an attacker to devise a substitute
message that would produce an identical message digest. The message digest gets
encrypted by the secret key to form a signature.
In addition to allowing us to determine if a file has changed, message digests can also help
to identify duplicate files.
The hash function has two important properties.
1. It is impossible to recover the original message from the message digest.
2. If the hash function is applied to two different messages, then the resulting message
digests are different with very high probability.
The message digest is always the same size
Used Class Details:
1) Class Name: MessageDigest
o Package: java.security
o Prototype: public abstract class MessageDigest extends MessageDigestSpi
o Description: This MessageDigest class provides applications the functionality of a message
digest algorithm, such as MD5 or SHA. Message digests are secure one-way hash
functions that take arbitrary-sized data and output a fixed-length hash value. A
MessageDigest object starts out initialized. The data is processed through it using the
Page | 51
Page 52
Information & System Security AND Network & Internet Security
update methods. At any point reset can be called to reset the digest. Once all the data to
be updated has been updated, one of the digest methods should be called to complete
the hash computation.
o Methods Used:
1. Name: getInstance
Prototype: public static MessageDigest getInstance(String algorithm)
throws NoSuchAlgorithmException
Description: Generates a MessageDigest object that implements the specified
digest algorithm. If the default provider package provides an implementation of the
requested digest algorithm, an instance of MessageDigest containing that
implementation is returned. If the algorithm is not available in the default package,
other packages are searched.
2. Name: update
Prototype: public void update(byte[] input)
Description: Updates the digest using the specified array of bytes.
2) Class Name: ObjectInputStream
o Package: java.io
o Description: An ObjectInputStream deserializes primitive data and objects
previously written using an ObjectOutputStream. ObjectOutputStream and
ObjectInputStream can provide an application with persistent storage for graphs of
objects when used with a FileOutputStream and FileInputStream respectively.
ObjectInputStream is used to recover those objects previously serialized. Other
uses include passing objects between hosts using a socket stream or for marshaling
and unmarshaling arguments and parameters in a remote communication system.
o Methods Used:
Name: readObject
Prototype: public final Object readObject()
throws IOException, ClassNotFoundException
Description: Read an object from the ObjectInputStream. The class of the
object, the signature of the class, and the values of the non-transient and
non-static fields of the class and all of its supertypes are read. Default
deserializing for a class can be overriden using the writeObject and
readObject methods. Objects referenced by this object are read
transitively so that a complete equivalent graph of objects is reconstructed
by readObject.
Page | 52
Page 53
Information & System Security AND Network & Internet Security
Page | 53
Page 54
Information & System Security AND Network & Internet Security
3) Class Name: ObjectOutputStream
o Package: java.io
o Description: An ObjectOutputStream writes primitive data types and graphs of Java
objects to an OutputStream. The objects can be read (reconstituted) using an
ObjectInputStream. Persistent storage of objects can be accomplished by using a
file for the stream. If the stream is a network socket stream, the objects can be
reconstituted on another host or in another process. Only objects that support the
java.io.Serializable interface can be written to streams. The class of each
serializable object is encoded including the class name and signature of the class,
the values of the object's fields and arrays, and the closure of any other objects
referenced from the initial objects.
o Methods Used:
Name: writeObject
Prototype: public final void writeObject(Object obj)
throws IOException
Description: Write the specified object to the ObjectOutputStream. The
class of the object, the signature of the class, and the values of the non-
transient and non-static fields of the class and all of its supertypes are
written. Default serialization for a class can be overridden using the
writeObject and the readObject methods. Objects referenced by this object
are written transitively so that a complete equivalent graph of objects can
be reconstructed by an ObjectInputStream.
Source Code:
Program 1
MessageDigest Reader Class:
/**
This class os the Message Digest Reader class.
Author: Rohan H. Pathak
*/
import java.io.*;
import java.security.*;
class MsgDigestReader
{
public static void main(String[] args)
Page | 54
Page 55
Information & System Security AND Network & Internet Security
{
try
{
FileInputStream fis = new FileInputStream("MyMessageDigest.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
String readString = "";
byte []readBytes= null;
boolean flag = true;
/* Trying to read the objects written in the defined order */
Object obj = ois.readObject();
if( !(obj instanceof String) )
{
System.err.println("Error is encountered while reading 1st object!!!");
flag = false;
}
else
{
readString = obj.toString();
System.out.println("Read String: " + readString);
}
obj = ois.readObject();
if( !(obj instanceof byte[]) )
{
System.err.println("Error is encountered while reading 2nd
object!!!");
flag = false;
}
else
{
readBytes = (byte[])obj;
System.out.println("Read Bytes: " + readBytes);
}
if(flag)
{
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(readString.getBytes());
Page | 55
Page 56
Information & System Security AND Network & Internet Security
if(MessageDigest.isEqual(md.digest(), readBytes))
System.out.println("The message received is correct");
else
System.out.println("The message received is not correct");
}
}catch(Exception e){
//System.out.println("Exception " + e +" caught at Line No: 59");
e.printStackTrace();
}
}
}
Program 2
Message Digest Writer Class
/**
This class os the Message Digest Write class.
Author: Rohan H. Pathak
*/
import java.io.*;
import java.security.*;
class MsgDigestWriter
{
public static void main(String[] args)
{
String str = "Hello!!! Take Care...";
try
{
FileOutputStream fos = new
FileOutputStream("MyMessageDigest.txt");
MessageDigest md = MessageDigest.getInstance("SHA");
ObjectOutputStream oos = new ObjectOutputStream(fos);
byte[] buffer = str.getBytes();
md.update(buffer);
Page | 56
Page 57
Information & System Security AND Network & Internet Security
oos.writeObject(str);
oos.writeObject(md.digest());
System.out.println("Message Digest is written successfully");
}catch(Exception e){
System.out.println("Exception " + e +" caught at Line No: 29");
}
}
}
Output:
Steps:
1. Run MessageDigestWriter JAVA File. It writes a file
MyMessageDigest.txt with some sample text using FileOutputStream class.
2. Run MessageDigestReader JAVA File.
Read String: Hello!!! Take Care...
Read Bytes: [B@1f6a7b9
The message received is correct
Page | 57
Page 58
Information & System Security AND Network & Internet Security
Practical No.: 12
Topic: Exporting and Importing Keys
Aim: To write a program to export and import a DSA (Digital Signature Algorithm) key
Description:
Usually the secret key is stored into a text file and can be retrieved back by providing the
specification of that key.
Key is signed with the help of Digital Signature Algorithm (DSA) and stored into a text file.
When importing the key from the text file the DSA key specification must be specified.
If someone makes some changes in a file then the signature of the file get changed and
hence the actual key can not be retrieved from the file.
Used Class Details:
1) Class Name: SecureRandom
o Package: java.security.SecureRandom
o Info: This class provides a cryptographically strong random number generator (RNG).
2) Class Name: DSAPrivateKeySpec
o Package: java.security.spec
o Description: This class specifies a DSA private key with its associated parameters.
o Constructor: public DSAPrivateKeySpec(BigInteger x, BigInteger p, BigInteger q,
BigInteger g)
Description: Creates a new DSAPrivateKeySpec with the specified parameter values.
Parameters:
x - the private key.
p - the prime.
q - the sub-prime.
g - the base.
Page | 58
Page 59
Information & System Security AND Network & Internet Security
Source Code:
Export.java
Import java.security.*;
import java.security.spec.DSAPrivateKeySpec;
import java.io.*;
class Export
{
public static void main(String[] args)
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
/* Size should of the range from 512 to 1024 */
kpg.initialize(1024, new SecureRandom());
KeyPair kp = kpg.generateKeyPair();
Class keySpec = Class.forName("java.security.spec.DSAPrivateKeySpec");
KeyFactory kf = KeyFactory.getInstance("DSA");
DSAPrivateKeySpec dsapks =
(DSAPrivateKeySpec)kf.getKeySpec(kp.getPrivate(), keySpec);
/* Creates an output file stream to write to the file with the specified name.
A new FileDescriptor object is created to represent this file connection. */
FileOutputStream fos = new FileOutputStream("Exported Key");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(dsapks.getX()); // Writes the private key x.
oos.writeObject(dsapks.getP()); // Writes the prime p.
oos.writeObject(dsapks.getQ()); // Writes the sub-prime q.
oos.writeObject(dsapks.getG()); // Writes the base g.
System.out.println("Private Key is Exported...");
}catch(Exception e){
System.out.println(e);
}
}
Page | 59
Page 60
Information & System Security AND Network & Internet Security
}
Import.java
import java.security.*;
import java.security.spec.DSAPrivateKeySpec;
import java.io.*;
import java.math.BigInteger;
class Import
{
public static void main(String[] args)
{
try
{
/*Creates a FileInputStream by opening a connection to an actual file, the file named by the
path name name in the file system.*/
FileInputStream fis = new FileInputStream("Exported Key");
/* Creating ObjectInputStream object to read the contents of the created file */
ObjectInputStream ois = new ObjectInputStream(fis);
DSAPrivateKeySpec dsapks = new DSAPrivateKeySpec((BigInteger) ois.readObject(),
(BigInteger) ois.readObject(), (BigInteger) ois.readObject(),
(BigInteger) ois.readObject());
KeyFactory kf = KeyFactory.getInstance("DSA");
PrivateKey pk = kf.generatePrivate(dsapks);
System.out.println("Private Key is Imported...");
System.out.println("Private Key Format: " + pk.getFormat());
}catch(Exception e){
System.out.println(e);
}
}
}
Page | 60
Page 61
Information & System Security AND Network & Internet Security
Output:
Step I
> java Export
Output:Private Key is Exported...
Step II
>java Import
Output:
Private Key is Imported...
Private Key Format: PKCS#8
Exported Key: This is the file which is generated containing some gibberish text
Page | 61
Page 62
Information & System Security AND Network & Internet Security
Practical No.: 13
Topic: Hash Functions: RSHash, JSHash, PJWHash
Aim: To write a program to implement following hash functions:
1. RSHash
2. JSHash
3. PJWHash
Description:
RS Hash Function: It is a simple hash function from Robert Sedgwicks Algorithms in C
book.
Pseudo Code:
Function RSHash(integer : a, integer : b, text: str)
hash = 0;
I = 0;
for I < length(str)
hash = hash*a + str(I);
I = I + 1;
a = a*b;
end for
return (hash AND 0x7FFFFFFF);
End Function
JS Hash Function: A bitwise hash function written by Justin Sobel
Pseudo Code:
Function JSHash(integer : hash, text: str)
hash = 0;
I = 0;
for I < length(str)
hash = hash ^ [Left-shift of hash by 5] + str(I) + [Right-shift of hash by 2];
I = I + 1;
end for
Page | 62
Page 63
Information & System Security AND Network & Internet Security
return (hash AND 0x7FFFFFFF);
End Function
PJW Hash Function: This hash algorithm is based on work by Peter J. Weinberger of AT&T
Bell Labs.
Pseudo Code:
Function PJWHash(integer : BitsInUnsignedInt, text: str)
ThreeQuarters = ( (BitsInUnsignedInt * 3) / 4);
HighBits = Left-shift (0xFFFFFFFF) by (BitsInUnsignedInt - OneEighth);
OneEighth = (BitsInUnsignedInt / 8);
hash = 0;
test = 0;
I = 0;
for I < length(str)
hash = [Left-shift of hash by OneEighth] + str(I);
if (test = hash AND HighBits) NOT EQUAL TO 0
hash = (( hash ^ (Right-shift test by ThreeQuarters)) AND (~HighBits));
end if
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
Page | 63
Page 64
Information & System Security AND Network & Internet Security
Source Code:
Hash Functions: RSHash, JSHash, PJWHash
/**
* This program demonstrates implimentations of various Hash function
* The Hash functions covered in this programs are RSHash, JS Hash, PJW Hash Functions
* RSHash: Robert Sedgwcks Hash function
* JSHash: Justine Sobels Hash function
* PJWHash: Peter J. Weinberger
*/
class RJPHashFunctionsImplementation
{
String strToBeHashed="";
RJPHashFunctionsImplementation(String strToBeHashed)
{
this.strToBeHashed = strToBeHashed;
}
/* If input value is too large we have to modify the datatype from int to long for all the
following functions */
int getRSHashVal()
{
int hashVal=0;
int i=0, a=12456, b=34677;
for(i=0;i<strToBeHashed.length();i++)
{
hashVal = hashVal * a + strToBeHashed.charAt(i);
a = a * b;
}
return ( hashVal & 0x7FFFFFFF);
}
int getJSHashVal()
{
int hashVal=34352357;
int i=0;
for(i=0;i<strToBeHashed.length();i++)
Page | 64
Page 65
Information & System Security AND Network & Internet Security
{
hashVal = hashVal ^ (hashVal << 5) + strToBeHashed.charAt(i) + (hashVal
>> 2);
}
return ( hashVal & 0x7FFFFFFF);
}
int getPJWHashVal()
{
int bitsInUnsignedInt = 32;
int threeQuarters = (bitsInUnsignedInt * 3) / 4;
int oneEighth = (bitsInUnsignedInt / 8);
int highBits = (int)(0xFFFFFFFF << (bitsInUnsignedInt - oneEighth));
int hashVal=0, test=0;
for(int i=0;i<strToBeHashed.length();i++)
{
hashVal = (hashVal << oneEighth) + strToBeHashed.charAt(i);
test = hashVal & highBits;
if(test != 0)
{
hashVal = (hashVal ^ (test >> threeQuarters)) & ~highBits;
}
}
return ( hashVal & 0x7FFFFFFF);
}
}
class RJPHashFunctions
{
public static void main(String[] args)
{
String str="";
do
{
str = javax.swing.JOptionPane.showInputDialog(null, "Enter the data for
Hashing : ");
}while(str.equals(""));
Page | 65
Page 66
Information & System Security AND Network & Internet Security
RJPHashFunctionsImplementation obj = new RJPHashFunctionsImplementation(str);
System.out.println("\n>>>>>> : Hash Functions Demonstration : <<<<<<");
System.out.println("\n(*) Input Text: " + str);
System.out.println("\n(*) RS Algorithmic Hashed Value: " + obj.getRSHashVal());
System.out.println("\n(*) JS Algorithmic Hashed Value: " + obj.getJSHashVal());
System.out.println("\n(*) PJW Algorithmic Hashed Value: " + obj.getPJWHashVal());
}
}
Output:
>>>>>> : Hash Functions Demonstration : <<<<<<
(*) Input Text: Hashing Demo!!!
(*) RS Algorithmic Hashed Value: 1642976841
(*) JS Algorithmic Hashed Value: 1714182653
(*) PJW Algorithmic Hashed Value: 214100737
Page | 66
Page 67
Information & System Security AND Network & Internet Security
Practical No.: 14
Topic: Hash Functions: ELFHash, BKDRHash, SDBMHash
Aim: To write a program to implement following hash functions:
1. ELFHash
2. BKDRHash
3. SDBMHash
Description:
ELF Hash Function: Similar to the PJW Hash function, but tweaked for 32-bit processors.
Its the hash function widely used on most UNIX systems.
Pseudo Code:
Function ELFHash(text: str)
hash = 0;
x = 0;
I = 0;
for I < length(str)
hash = (Left-shift hash by 4) + str.charAt(i);
if((x = hash & 0xF0000000L) != 0)
hash = hash ^ (Right-shift x by 24);
hash = hash AND ~x;
end if
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
BKDR Hash Function: This hash function comes from Brian Kernighan and Dennis
Ritchie's book "The C Programming Language". It is a simple hash function using a strange
set of possible seeds which all constitute a pattern of 31....31...31 etc, it seems to be very
similar to the DJB hash function.
Pseudo Code:
Function BKDRHash(integer: seed, text: str)
hash = 0;
Page | 67
Page 68
Information & System Security AND Network & Internet Security
I = 0;
for I < length(str)
hash = hash*seed + str(I);
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
SDBM Hash Function: This is the algorithm of choice which is used in the open source
SDBM project. The hash function seems to have a good over-all distribution for many
different data sets. It seems to work well in situations where there is a high variance in the
MSBs of the elements in a data set.
Pseudo Code:
Function SDBMHash(text: str)
hash = 0;
I = 0;
for I < length(str)
hash = str(I) + (Left-shift hash by 6) + (Left-shift hash by 16) - hash;
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
Source Code:
Hash Functions: ELFHash, BKDRHash, SDBMHash
class EBSHashFunctionsImplementation
{
String strToBeHashed="";
EBSHashFunctionsImplementation(String strToBeHashed)
{
this.strToBeHashed = strToBeHashed;
}
/* If input value is too large we have to modify the datatype from int to long for all the
following functions */
long getELFHashVal()
Page | 68
Page 69
Information & System Security AND Network & Internet Security
{
long hashVal=0;
long x=0;
for(int i=0;i<strToBeHashed.length();i++)
{
hashVal = (hashVal << 4) + strToBeHashed.charAt(i);
x = hashVal & 0xF0000000L;
if(x != 0)
{
hashVal ^= (x >> 24);
hashVal &= ~x;
}
}
return (hashVal & 0x7FFFFFFF);
}
int getBKDRHashVal()
{
int hashVal=0;
/* Seed value can be any pattern of 3, 1*/
int seed = 131; // 31 131 1313 13131 131313 etc..
int i=0;
for(i=0;i<strToBeHashed.length();i++)
hashVal = (hashVal * seed) + strToBeHashed.charAt(i);
return ( hashVal & 0x7FFFFFFF);
}
int getSDBMHashVal()
{
int hashVal=0;
for(int i=0;i<strToBeHashed.length();i++)
hashVal = strToBeHashed.charAt(i) + (hashVal << 6) + (hashVal << 16) -
hashVal;
return ( hashVal & 0x7FFFFFFF);
}
Page | 69
Page 70
Information & System Security AND Network & Internet Security
}
class EBSHashFunctions
{
public static void main(String[] args)
{
String str="";
do
{
str = javax.swing.JOptionPane.showInputDialog(null, "Enter the data for
Hashing : ");
}while(str.equals(""));
EBSHashFunctionsImplementation obj = new
EBSHashFunctionsImplementation(str);
System.out.println("\n>>>>>> : Hash Functions Demonstration : <<<<<<");
System.out.println("\n(*) Input Text: " + str);
System.out.println("\n(*) ELF Algorithmic Hashed Value: " + obj.getELFHashVal());
System.out.println("\n(*) BKDR Algorithmic Hashed Value: " +
obj.getBKDRHashVal());
System.out.println("\n(*) SDBM Algorithmic Hashed Value: " +
obj.getSDBMHashVal());
}
}
Output:
>>>>>> : Hash Functions Demonstration : <<<<<<
(*) Input Text: Good Morning!!!
(*) ELF Algorithmic Hashed Value: 27335617
(*) BKDR Algorithmic Hashed Value: 1114789748
(*) SDBM Algorithmic Hashed Value: 1103946272
Page | 70
Page 71
Information & System Security AND Network & Internet Security
Practical No.: 15
Topic: Hash Functions: DJBHash, APHash
Aim: To write a program to implement following hash functions:
1. DJBHash
2. APHash
Description:
DJBHash Hash Function: An algorithm produced by Professor Daniel J. Bernstein and
shown first to the world on the usenet newsgroup comp.lang.c. It is one of the most
efficient hash functions ever published.
Pseudo Code:
Function DJBHash(text: str)
hash = 5381;
I = 0;
for I < length(str)
hash = (Left-shift hash by 5) + hash + str(I);
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
APHash Hash Function: An algorithm was written by Arash Partow.
Pseudo Code:
Function APHash(text: str)
hash = 0;
I = 0;
for I < length(str)
if ((i & 1) == 0)
{
hash = hash^((Left-shift hash by 7) ^ str(I) ^ (Right-shift hash by 3));
}
Page | 71
Page 72
Information & System Security AND Network & Internet Security
else
{
hash=hash^(~((Left-shift hash by 11)^ str(I)^ (Right-shift hash by 5)));
}
I = I + 1;
end for
return (hash AND 0x7FFFFFFF);
End Function
Source Code:
Hash Functions: DJBHash, APHash
class DJBnAPHashFunctions
{
private String inputStr="";
public DJBnAPHashFunctions(String inputStr)
{
this.inputStr = inputStr;
}
/* DJB Hash Function */
public int getDJBHashVal()
{
int hash = 5381;
for(int i = 0; i < inputStr.length(); i++)
hash = ((hash << 5) + hash) + inputStr.charAt(i);
return (hash & 0x7FFFFFFF);
}
/* AP Hash Function */
public int getAPHashVal()
{
int hash = 0;
for(int i = 0; i < inputStr.length(); i++)
Page | 72
Page 73
Information & System Security AND Network & Internet Security
{
if((i & 1) == 0)
hash = hash ^ ((hash << 7) ^ inputStr.charAt(i) ^ (hash >> 3));
else
hash = hash ^ (~((hash << 11) ^ inputStr.charAt(i) ^ (hash >> 5)));
}
return (hash & 0x7FFFFFFF);
}
public static void main(String[] args)
{
String str="";
do
{
str = javax.swing.JOptionPane.showInputDialog(null, "Enter the data for
Hashing : ");
}while(str.equals(""));
DJBnAPHashFunctions obj = new DJBnAPHashFunctions(str);
System.out.println("\n>>>>>> : Hash Functions Demonstration : <<<<<<");
System.out.println("\n(*) Input Text: " + str);
System.out.println("\n(*) DJB Algorithmic Hashed Value: " + obj.getDJBHashVal());
System.out.println("\n(*) AP Algorithmic Hashed Value: " + obj.getAPHashVal());
}
}
Output:
>>>>>> : Hash Functions Demonstration : <<<<<<
(*) Input Text: Welcome to the world of Security...
(*) DJB Algorithmic Hashed Value: 490796212
(*) AP Algorithmic Hashed Value: 411344760
Page | 73
Page 74
Information & System Security AND Network & Internet Security
Practical No.: 16
Topic: Permissions
Aim: To write a program that creates a permission that controls access to pages of a book.
Description:
The permission name consists of a book id, a colon, and a set of allowable pages. The set
of allowable pages is specified as a comma-separated list of page ranges.
For example, 88:1,3-4 specifies that pages 1, 3, and 4 are accessible in the book whose id
is 88.
Used Class Details:
1) Class Name: BitSet
o Package: java.util
o Description: This class implements a vector of bits that grows as needed. Each
component of the bit set has a boolean value. The bits of a BitSet are indexed by
nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet
may be used to modify the contents of another BitSet through logical AND, logical
inclusive OR, and logical exclusive OR operations. By default, all bits in the set initially
have the value false.
o Methods Used:
Name: or
Prototype: public void or(BitSet set)
Description: Performs a logical OR of this bit set with the bit set argument. This bit
set is modified so that a bit in it has the value true if and only if it either already
had the value true or the corresponding bit in the bit set argument has the value
true.
2) Class Name: BasicPermission
o Package: java.security
o Prototype: public abstract class BasicPermission
extends Permission implements Serializable
o Description: The BasicPermission class extends the Permission class, and can be used as
the base class for permissions that want to follow the same naming convention as
BasicPermission. The name for a BasicPermission is the name of the given permission (for
example, "exit", "setFactory", "print.queueJob", etc). The naming convention follows the
Page | 74
Page 75
Information & System Security AND Network & Internet Security
hierarchical property naming convention. An asterisk may appear by itself, or if
immediately preceded by a "." may appear at the end of the name, to signify a wildcard
match. For example, "*" and "java.*" are valid, while "*java", "a*b", and "java*" are not
valid.
o Method Used:
Name: implies
Prototype: public abstract boolean implies(Permission permission)
Description: Checks if the specified permission's actions are "implied by" this
object's actions. This must be implemented by subclasses of Permission, as they
are the only ones that can impose semantics on a Permission object. The implies
method is used by the AccessController to determine whether or not a requested
permission is implied by another permission that is known to be valid in the current
execution context.
3) Class Name: String
o Package: java.lang
o Method Name: spit
o Description: Splits this string around matches of the given regular expression. This
method works as if by invoking the two-argument split method with the given expression
and a limit argument of zero. Trailing empty strings are therefore not included in the
resulting array.
E.g. The string "boo:and:foo", for example, yields the following results with these
expressions:
Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
Page | 75
Page 76
Information & System Security AND Network & Internet Security
Source Code:
import java.io.*;
import java.security.BasicPermission;
import java.security.Permission;
import java.util.BitSet;
public class BookPermission extends BasicPermission implements Serializable
{
String bookId="";
String pgRange[];
int end = 0;
BitSet pages;
public BookPermission(String str)
{
/* Creates a new BasicPermission with the specified name. */
super(str);
/* Splits this string around matches of the given regular expression. */
String[] field = str.split(":");
bookId = field[0];
pgRange = field[1].split(",");
pages = new BitSet();
// Getting Range of permissible pages
for(int i=0;i<pgRange.length;i++)
{
String[] partrange = pgRange[i].split("-");
int start = Integer.parseInt(partrange[0]);
if(partrange.length > 1)
end = Integer.parseInt(partrange[1]);
else
end = start;
}
}
/* Overriding implies method in BasicPermission class */
public boolean implies(Permission p)
{
Page | 76
Page 77
Information & System Security AND Network & Internet Security
BookPermission bp = (BookPermission)p;
if(!bookId.equals(bp.bookId))
return false;
BitSet bkpgs = (BitSet)bp.pages.clone();
bkpgs.or(pages);
return (pages.equals(bkpgs));
}
public boolean equals(Object obj)
{
//System.out.println("I am inside");
if(!(obj instanceof BookPermission))
return false;
BookPermission bp = (BookPermission)obj;
return pages.equals(bp.pages) && bookId.equals(bp.bookId);
}
public static void main(String[] args)
{
Permission p1 = new BookPermission("B123:1-3,5,6");
Permission p2 = new BookPermission("B123:1-3,5,6");
boolean b = p1.implies(p2);
if(b)
System.out.println("\nAccess granted for B123:1-3,5,6 and B123:2");
else
System.out.println("\nAccess denied for B123:1-3,5,6 and B123:2");
Permission p3 = new BookPermission("B123:1-3,5,6");
Permission p4 = new BookPermission("B1234:1-3,5,6");
b = p3.implies(p4);
if(b)
System.out.println("\nAccess granted for B123:1-3,5,6 and B1234:1-3,5,6");
else
System.out.println("\nAccess denied for B123:1-3,5,6 and B1234:1-3,5,6");
Page | 77
Page 78
Information & System Security AND Network & Internet Security
}
}
Output:
Access granted for B123:1-3,5,6 and B123:2
Access denied for B123:1-3,5,6 and B1234:1-3,5,6
Page | 78