UNIT1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

UNIT 1

Introduction:

This is the age of universal electronic connectivity, where the activities like
hacking, viruses, electronic fraud are very common. Unless security measures
are taken, a network conversation or a distributed application can be
compromised easily.

Some simple examples are:

i. Online purchases using a credit/debit card.

ii. A customer unknowingly being directed to a false website.

iii. A hacker sending a message to person pretending to be someone else.

Network Security has been affected by two major developments over the last
several decades.

First one is introduction of computers into organizations and the second one
being introduction of distributed systems and the use of networks and
communication facilities for carrying data between users & computers. These
two developments lead to ‘computer security’ and ‘network security’, where the
computer security deals with collection of tools designed to protect data and to
thwart hackers. Network security measures are needed to protect data during
transmission. But keep in mind that, it is the information and our ability to
access that information that we are really trying to protect and not the
computers and networks

SECURITY GOALS

Let us first discuss three security goals: confidentiality, integrity, and


availability

Confidentiality

Confidentiality is probably the most common aspect of information security. We


need to protect our confidential information. An organization needs to guard
against those malicious actions that endanger the confidentiality of its
information.
Integrity

Information needs to be changed constantly. In a bank, when a customer


deposits or withdraws money, the balance of her account needs to be changed.
Integrity means that changes need to be done only by authorized entities and
through authorized mechanisms. Integrity violation is not necessarily the result
of a malicious act; an interruption in the system, such as a power surge, may
also create unwanted changes in some information.

Availability

The third component of information security is availability. The information


created and stored by an organization needs to be available to authorized
entities. Information is useless if it is not available. Information needs to be
constantly changed, which means it must be accessible to authorized entities.
The unavailability of information is just as harmful for an organization as the
lack of confidentiality or integrity. Imagine what would happen to a bank if the
customers could not access their accounts for transactions.

ATTACKS

Our three goals of security: confidentiality, integrity, and availability

can be threatened by security attacks. Although the literature uses different


approaches to categorizing the attacks, we will first divide them into three
groups related to the security goals.

Attacks Threatening Confidentiality :

In general, two types of attacks threaten the confidentiality of information:


snooping and traffic analysis.

Snooping :
Snooping refers to unauthorized access to or interception of data. For example,
a file transferred through the Internet may contain confidential information. An
unauthorized entity may intercept the transmission and use the contents for her
own benefit. To prevent snooping, the data can be made nonintelligible to the
intercepter by using encipherment techniques.

Traffic Analysis

Although encipherment of data may make it nonintelligible for the intercepter,


she can obtain some other type information by monitoring online traffic. For
example, she can find the electronic address (such as the e-mail address) of the
sender or the receiver. She can collect pairs of requests and responses to help
her guess the nature of transaction.

Attacks Threatening Integrity

The integrity of data can be threatened by several kinds of attacks: modification,


masquerading, replaying, and repudiation.

Modification After intercepting or accessing information, the attacker modifies


the information to make it beneficial to herself. For example, a customer sends a
message to a bank to do some transaction. The attacker intercepts the message
and changes the type of transaction to benefit herself. Note that sometimes the
attacker simply deletes or delays the message to harm the system or to benefit
from it.

Masquerading Masquerading, or spoofing, happens when the attacker


impersonates somebody else. For example, an attacker might steal the bank
card and PIN of a bank customer and pretend that she is that customer.
Sometimes the attacker pretends instead to be the receiver entity. For example,
a user tries to contact a bank, but another site pretends that it is the bank and
obtains some information from the user.

Replaying Replaying is another attack. The attacker obtains a copy of a


message sent by a user and later tries to replay it. For example, a person sends
a request to her bank to ask for payment to the attacker, who has done a job for
her. The attacker intercepts the message and sends it again to receive another
payment from the bank.

Repudiation This type of attack is different from others because it is performed


by one of the two parties in the communication: the sender or the receiver. The
sender of the message might later deny that she has sent the message; the
receiver of the message might later deny that he has received the message. An
example of denial by the sender would be a bank customer asking her bank to
send some money to a third party but later denying that she has made such a
request. An

SECURITY MECHANISMS
One of the most specific security mechanisms in use is cryptographic techniques.
Encryption or encryption-like transformations of information are the most
common means of providing security. Some of the mechanisms are

1 Encipherment

2 Digital Signature

3 Access Control

SECURITY ATTACKS

There are four general categories of attack which are listed below.

Interruption An asset of the system is destroyed or becomes unavailable or


unusable. This is an attack on availability e.g., destruction of piece of hardware,
cutting of a communication line or Disabling of file management system.

Interception An unauthorized party gains access to an asset. This is an attack


on confidentiality. Unauthorized party could be a person, a program or a
computer.e.g., wire tapping to capture data in the network, illicit copying of files

Modification

An unauthorized party not only gains access to but tampers with an asset. This
is an attack on integrity. e.g., changing values in data file, altering a program,
modifying the contents of messages being transmitted in a network.
Eavesdropper or forger

Fabrication

An unauthorized party inserts counterfeit objects into the system. This is an


attack on authenticity. e.g., insertion of spurious message in a network or
addition of records to a file.

Cryptographic Attacks

Passive Attacks

Passive attacks are in the nature of eavesdropping on, or monitoring of,


transmissions. The goal of the opponent is to obtain information that is being
transmitted. Passive attacks are of two types:

Release of message contents: A telephone conversation, an e-mail message


and a transferred file may contain sensitive or confidential information. We
would like to prevent the opponent from learning the contents of these
transmissions.

Traffic analysis: If we had encryption protection in place, an opponent might


still be able to observe the pattern of the message. The opponent could
determine the location and identity of communication hosts and could observe
the frequency and length of messages being exchanged. This information might
be useful in guessing the nature of communication that was taking place.

Passive attacks are very difficult to detect because they do not involve any
alteration of data. However, it is feasible to prevent the success of these attacks.
Active attacks

These attacks involve some modification of the data stream or the creation of a
false stream. These attacks can be classified in to four categories:

Masquerade – One entity pretends to be a different entity.

Replay – involves passive capture of a data unit and its subsequent


transmission to produce an unauthorized effect.

Modification of messages – Some portion of message is altered or the


messages are delayed or recorded, to produce an unauthorized effect.

Denial of service – Prevents or inhibits the normal use or management of


communication facilities. Another form of service denial is the disruption of an
entire network, either by disabling the network or overloading it with messages
so as to degrade performance. It is quite difficult to prevent active attacks
absolutely, because to do so would require physical protection of all
communication facilities and paths at all times. Instead, the goal is to detect
them and to recover from any disruption or delays caused by them.

Basic Concepts
Cryptography The art or science encompassing the principles and methods of
transforming an intelligible message into one that is unintelligible, and then
retransforming that message back to its original form

Plaintext The original intelligible message

Cipher text The transformed message

Cipher An algorithm for transforming an intelligible message into one that is


unintelligible by transposition and/or substitution methods

Key Some critical information used by the cipher, known only to the sender&
receiver

Encipher (encode) The process of converting plaintext to cipher text using a


cipher and a key

Decipher (decode) the process of converting cipher text back into plaintext
using a cipher and a key

Cryptanalysis The study of principles and methods of transforming an


unintelligible message back into an intelligible message without knowledge of
the key. Also called code breaking

Cryptology Both cryptography and cryptanalysis

Code An algorithm for transforming an intelligible message into an unintelligible


one using a code-book

CRYPTOGRAPHY:

Cryptography is the art and science of making a cryptosystem that is capable of


providing information security. Cryptography deals with the actual securing of
digital data. It refers to the design of mechanisms based on mathematical
algorithms that provide fundamental information security services.

CRYPTOSYSTEM A cryptosystem is an implementation of cryptographic


techniques and their accompanying infrastructure to provide information security
services. A cryptosystem is also referred to as a cipher system.
Cryptosystem shown in fig.1, is th study of secure communications techniques
that allow only the sender and intended recipient of a message to view its
contents. When transmitting electronic data, the most common use of
cryptography is to encrypt and decrypt email and other plain-text messages. It
reformats and transform our data, making it safer on its trip between
computers. The technology is based on the essentials of secret codes,
augmented by modern mathematics that protects our data in powerful ways.

Network Security - measures to protect data during their transmission

Internet Security - measures to protect data during their transmission over a


collection of interconnected networks.

Cryptography

Cryptographic systems are generally classified along 3 independent dimensions:

Type of operations used for transforming plain text to cipher text

All the encryption algorithms are based on two general principles: substitution,
in which each element in the plaintext is mapped into another element, and
transposition, in which elements in the plaintext are rearranged.

The number of keys used

If the sender and receiver uses same key then it is said to be symmetric key
(or)

single key (or) conventional encryption.

If the sender and receiver use different keys then it is said to be public key
encryption.

The way in which the plain text is processed


A block cipher processes the input and block of elements at a time, producing
output block for each input block.

A stream cipher processes the input elements continuously, producing output


element one at a time, as it goes along.

Cryptanalysis

The process of attempting to discover X or K or both is known as cryptanalysis.


The strategy used by the cryptanalysis depends on the nature of the encryption
scheme and the information available to the cryptanalyst.

There are various types of cryptanalytic attacks based on the amount of

information known to the cryptanalyst.

Cipher text only – A copy of cipher text alone is known to the cryptanalyst.

Known plaintext – The cryptanalyst has a copy of the cipher text and the
corresponding plaintext.

Chosen plaintext – The cryptanalysts gains temporary access to the encryption


machine. They cannot open it to find the key, however; they can encrypt a large
number of suitably chosen plaintexts and try to use the resulting cipher texts to
deduce the key.

Chosen cipher text – The cryptanalyst obtains temporary access to the


decryption machine, uses it to decrypt several string of symbols, and tries to use
the results to deduce the key.

What is The Purpose of Cryptography?


Cryptography aims to keep data and messages private and inaccessible to
possible threats or bad actors. It frequently works invisibly to encrypt and
decrypt the data you send through email, social media, applications, and website
interactions.

There are several uses for symmetric cryptography, including:

o Payment applications and card transactions

o Random number generation

o Verify the sender's signature to be sure they are who they claim they are

There are several uses for asymmetric cryptography, including:

o Email messages

o SIM card authentication

o Web security

o Exchange of private keys

There are three main types of cryptography:

Symmetric key Cryptography: With the encryption technique, the sender and the
recipient use the same shared key to encrypt and decrypt messages.
Although symmetric key systems are quicker and easier to use, they have the
drawback of requiring a secure key exchange between the sender and the
receiver. Data Encryption System (DES) is the most widely used symmetric key
encryption method.

Hash Functions: In this algorithm, no key is used. The plain text is used to
produce a hash value that has a fixed length, making it challenging to retrieve
the plain text's information. Hash functions are widely used by operating
systems to encrypt passwords.

Asymmetric Key Cryptography: This approach uses a set of keys to encrypt


and decrypt data. Public keys are used for encryption, whereas private keys are
used for decryption

Features of Cryptography

Cryptography has the following features:

o Confidentiality: The only person who can access information is the one it
is intended for, which is the primary feature of cryptography.
o Integrity: Information cannot be altered while it is being stored or sent
from the sender to the intended destination without the recipient spotting
the addition of new information in Cryptography.
o Non-repudiation: The creator/sender of a message cannot deny his
intent to send information at a future point.
o Authentication: The identities of the sender and the recipient have been
confirmed. Furthermore, the information's source and final destination are
confirmed.
o Availability: It also ensures that the required information is available to
authorized users at the appropriate time.
o Key Management: The creation, distribution, storage, and alteration of
cryptographic keys take place in this process.
o Algorithm: Mathematical formulae are used in cryptography to encrypt
and decrypt messages.
o Digital Signatures: A signature that can be applied to messages to
protect the message's authenticity and sender identification.

Encryption and Decryption

Cryptography involves two phases at its most fundamental level: Encryption


and Decryption.

Encryption uses a cipher to encrypt and transform the plaintext into ciphertext.
On the other hand, decryption transforms the ciphertext into plaintext by
employing the same cipher.

The most popular application of cryptography when sending electronic data is


encrypting and decrypting emails and other plaintext messages. The simplest
method is the "secret key" or symmetric approach.
The secret key is used to encrypt data, and after decoding, the secret key and
encoded message are sent to the recipient. What is the problem, then? A third
party is all they need to decode and analyze the message if it is intercepted.

Cryptologists developed the asymmetric or "public key" approach to solve this


issue. Each user, in this case, has two keys: a private key and a public key.
Senders request the recipient's public key before encrypting and sending the
message.

Cryptographic Algorithms

Cryptosystems encrypt and decrypt information using cryptographic algorithms,


or ciphers, to secure communications between computer systems, devices, and
applications.

A cipher suite uses three different algorithms: one for encryption, message
authentication, and key exchange. This process, integrated into protocols and
developed using software that runs on operating systems (OS) and networked
computer systems, involves:

o Data encryption and decryption using the production of public and private
keys
o To authenticate messages, use digital signature and verification
o Key exchange

Advantages

Access Management: Access control can use cryptography to guarantee that


only individuals with the appropriate authorizations are granted access to a
resource. The resource is encrypted and can only be accessed by those with the
proper decryption key.
Secure Communication: Cryptography is essential for private communication
over the Internet. It provides safe methods for sending sensitive data like bank
account numbers, passwords, and other private information over the Internet.

Protection against attacks: Attacks like replay and man-in-the-middle attacks


can be defended against with the help of cryptography. It provides techniques
for identifying and preventing these assaults.

Applications of Cryptography

Computer passwords: Cryptography is frequently used in computer security,


especially when creating and managing passwords. When users log in, their
password is hashed and contrasted with the previously saved hash. To store
them, passwords are first hashed and encrypted. This method encrypts the
passwords so that even if hackers can access the password database, they can't
comprehend the passwords.

Digital Currencies: Cryptography is also used by digital currencies like Bitcoin


to secure transactions and prevent fraud. Since advanced algorithms and
cryptographic keys safeguard transactions, tampering with or creating fake
transactions is practically impossible.

Secure web browsing: Cryptography protects users from eavesdropping in on


their conversations and man-in-the-middle attacks and provides online browsing
security. The Secure Sockets Layer (SSL) and Transport Layer Security (TLS)
protocols use public key cryptography to encrypt data between the web server
and the client, creating a secure communication channel.

Digital signatures: Digital signatures are used to sign papers and act as the
handwritten signature's digital copy. Cryptography is used to create digital
signatures, and public key cryptography is used to verify them. Digital
signatures are becoming more widely used, and many countries have laws that
make them legally binding.

Authentication: When logging into a computer, cryptography is employed as


the authentication method, for example, a bank account or a secure network.
The authentication protocols use cryptographic techniques to validate the user's
identity and possession of the necessary access privileges to the resource.

Cryptocurrencies: Cryptocurrencies like Bitcoin and Ethereum largely rely on


cryptography to protect transactions, prevent fraud, and uphold the integrity of
the network. Transactions are protected by complicated algorithms and
cryptographic keys, making it nearly impossible to tamper with or fake
transactions.

End-to-End Encryption: Email, instant messages, and video chats are all
examples of two-way communications protected by end-to-end encryption. Even
if a message is encrypted, this guarantees that only the intended recipients can
decode it. End-to-end encryption is frequently employed in messaging apps like
Whats App and Signal, offering users high protection and anonymity.
CLASSICAL ENCRYPTION TECHNIQUES

There are two basic building blocks of all encryption techniques: substitution and

transposition.

SUBSTITUTION TECHNIQUES
A substitution technique is one in which the letters of plaintext are replaced by
other letters or by numbers or symbols. If the plaintext is viewed as a sequence
of bits, then substitution involves replacing plaintext bit patterns with cipher text
bit patterns.
Caesar cipher (or) shift cipher
The earliest known use of a substitution cipher and the simplest was by Julius
Caesar. The
Caesar cipher involves replacing each letter of the alphabet with the letter
standing 3 places
further down the alphabet.
Special case of Substitution cipher is known as Caesar cipher where the
key is taken as 3.

e.g., plain text : pay more money

Cipher text: SDB PRUH PRQHB


Note that the alphabet is wrapped around, so that letter following „z‟ is
„a‟.

Mathematical representation

The encryption can be represented using modular arithmetic by first


transforming the letters into numbers, according to the scheme, A = 0, B
= 1,…, Z = 25. Encryption of a letter by a shift n can be described
mathematically as.

For each plaintext letter p, substitute the cipher text letter c such that
C = E(p) = (p+3) mod 26
A shift may be any amount, so that general Caesar algorithm is
C = E (p) = (p+k) mod 26
Where k takes on a value in the range 1 to 25. The decryption algorithm is
simply
P = D(C) = (C-k) mod 26
Algorithm for Substitution Cipher:
Input:
 A String of both lower and upper case letters, called PlainText.
 An Integer denoting the required key.
Procedure:
 Create a list of all the characters.
 Create a dictionary to store the substitution for all characters.
 For each character, transform the given character as per the rule,
depending on whether we’re encrypting or decrypting the text.
 Print the new string generated.

// Java implementation of Substitution Cipher


import java.io.*;
import java.util.*;
import java.util.HashMap;
import java.util.Map;

public class CaesarCipher {


public static void main(String[] args) {
String allLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHI" +
"JKLMNOPQRSTUVWXYZ";

// create a dictionary to store the substitution for the given


alphabet in the plain text based on the key
Map<Character, Character> dict1 = new HashMap<>();
int key = 4;
for (int i = 0; i < allLetters.length(); i++) {
dict1.put(allLetters.charAt(i),
allLetters.charAt((i + key) %
allLetters.length()));
}

String plainText = "I am studying Data Encryption";


StringBuilder cipherText = new StringBuilder();
// loop to generate ciphertext
for (char c : plainText.toCharArray()) {
if (allLetters.indexOf(c) != -1) {
cipherText.append(dict1.get(c));
} else {
cipherText.append(c);
}
}

System.out.println("Cipher Text is: " + cipherText);

// create a map to store the substitution for the given alphabet in


the cipher text based on the key
Map<Character, Character> dict2 = new HashMap<>();
for (int i = 0; i < allLetters.length(); i++) {
dict2.put(allLetters.charAt(i),
allLetters.charAt((i - key + allLetters.length())
% allLetters.length()));
}

StringBuilder decryptedText = new StringBuilder();

// loop to recover plain text


for (char c : cipherText.toString().toCharArray()) {
if (allLetters.indexOf(c) != -1) {
decryptedText.append(dict2.get(c));
} else {
decryptedText.append(c);
}
}

System.out.println("Recovered plain text: " + decryptedText);


}
}

Output
Cipher Text is: M eq wxyhCmrk Hexe IrgvCtxmsr
Recovered plain text : I am studying Data Encryption

Monoalphabetic Cipher

Monoalphabetic cipher is a substitution cipher, where the cipher alphabet for


each plain text alphabet is fixed, for the entire encryption.

In simple words, if the alphabet ‘p’ in the plain text is replaced by the cipher
alphabet ‘d’. Then in the entire plain text wherever alphabet ‘p’ is used, it will be
replaced by the alphabet ‘d’ to form the ciphertext.

Playfair Cipher

Playfair cipher is a substitution cipher which involves a 5X5 matrix. Let us


discuss the technique of this Playfair cipher with the help of an example:

Plain Text: meet me tomorrow

Key: KEYWORD

Now, we have to convert this plain text to ciphertext using the given key. We
will discuss the further process in steps.

Step 1: Create a 5X5 matrix and place the key in that matrix row-wise from left
to right. Then put the remaining alphabet in the blank space.

Note: If a key has duplicate alphabets, then fill those alphabets only once in the
matrix, and I & J should be kept together in the matrix even though they occur
in the given key.

Step 2: Now, you have to break the plain text into a pair of alphabets.

Plain Text: meet me tomorrow

Pair: me et me to mo rx ro wz
Note

 Pair of alphabets must not contain the same letter. In case, pair has the same
letter then break it and add ‘x’ to the previous letter. Like in our example letter
‘rr’ occurs in pair so, we have broken that pair and added ‘x’ to the first ‘r’.
 In case while making pair, the last pair has only one alphabet left then we add
‘z’ to that alphabet to form a pair as in our above example, we have added ‘z’ to
‘w’ because ‘w’ was left alone at last.
 If a pair has ‘xx’ then we break it and add ‘z’ to the first ‘x’, i.e. ‘xz’ and ‘x_’.

Step 3: In this step, we will convert plain text into ciphertext. For that, take the
first pair of plain text and check for cipher alphabets for the corresponding in the
matrix. To find cipher alphabets follow the rules below.

Note

 If both the alphabets of the pair occur in the same row replace them with the
alphabet to their immediate right. If an alphabet of the pair occurs at extreme
right then replace it with the first element of that row, i.e. the last element of
the row in the matrix circularly follows the first element of the same row.
 If the alphabets in the pair occur in the same column, then replace them with
the alphabet immediate below them. Here also, the last element of the column
circularly follows the first element of the same column.
 If the alphabets in the pair are neither in the same column and nor in the
same row, then the alphabet is replaced by the element in its own row and the
corresponding column of the other alphabet of the pair.

Pair: me et me to mo rx ro wz

Cipher Text: kn ku kn kz ks ta kc yo

So, this is how we can convert a plain text to ciphertext using Playfair cipher.
When compared with monoalphabetic cipher Playfair cipher is much more
advanced. But still, it is easy to break.

One-Time Pad

The one-time pad cipher suggests that the key length should be as long as
the plain text to prevent the repetition of key. Along with that, the key should
be used only once to encrypt and decrypt the single message after that the key
should be discarded.

Onetime pad suggests a new key for each new message and of the same length
as a new message. Now, let us see the one-time pad technique to convert plain
text into ciphertext. Assume our plain text and key be:

Plain text: Binary

Key: Cipher
Now again convert the plain text and key into the numeric form. For that
number the alphabets such as A=0, B=1, C=2, …………, Z=25. So, our plain text
and key in numeric form would be:

Plain text: 1 8 13 0 17 24

Key: 2 8 15 7 4 17

Now, you have to add the number of the plain text alphabet, to the number of
its corresponding key alphabet. That means, for this example, we will add:

B+C = 1+2 = 3

I+I = 8+8 = 16

N+P = 13+15 = 28

A+H = 0+7 = 7

R+E = 17+4 = 21

Y+R = 24+17 = 41

The resultant ciphertext numbers we get are (3, 16, 28, 7, 21, 41

If the addition of any plain text number and the key number is >26, then
subtract only that particular number from 26. We have the addition of two pair
of plain text number and a key number, greater than 26, i.e. N+P=28 &
Y+R=41.

Subtract them by 26.

N+P = 28 – 26 = 2

Y+R = 41 – 26 = 15

So, the final ciphertext numbers are (3, 16, 2, 7, 21, 15). Now convert this
number to alphabets assuming A to be numbered 0 and B to be 1…..Z to 25.

Ciphertext: dqchvp.

In this way, we can convert plain text to cipher text using a one-time pad.

So, this is all about the substitution cipher techniques. It has a monoalphabetic
cipher and polyalphabetic cipher technique. Substitution technique is also called
classical substitution technique.

Transposition Technique in Cryptography


Transposition technique is an encryption method which is achieved by
performing permutation over the plain text. Mapping plain text into cipher text
using transposition technique is called transposition cipher.
On the one hand, the substitution technique substitutes a plain text symbol with
a cipher text symbol. On the other hand, the transposition technique executes
permutation on the plain text to obtain the cipher text.

Rail Fence Cipher

The rail fence cipher is the simplest transposition cipher. The steps to obtain
cipher text using this technique are as follow:

Step 1: The plain text is written as a sequence of diagonals.

Step 2: Then, to obtain the cipher text the text is read as a sequence of rows.
To understand this in a better way, let us take an example:

Plain Text: meet me Tomorrow

Now, we will write this plain text sequence wise in a diagonal form as you can
see below:
import java.util.*;

public class ColumnarTranspositionCipher {


// Key for Columnar Transposition
static final String key = "HACK";
static Map<Character, Integer> keyMap = new HashMap<>();

static void setPermutationOrder() {


// Add the permutation order into the map
for (int i = 0; i < key.length(); i++) {
keyMap.put(key.charAt(i), i);
}
}

// Encryption
static String encryptMessage(String msg) {
int row, col;
StringBuilder cipher = new StringBuilder();

/* Calculate the number of columns in the matrix */


col = key.length();

/* Calculate the maximum number of rows in the matrix */


row = (int) Math.ceil((double) msg.length() / col);

char[][] matrix = new char[row][col];

for (int i = 0, k = 0; i < row; i++) {


for (int j = 0; j < col; ) {
if (k < msg.length()) {
char ch = msg.charAt(k);
if (Character.isLetter(ch) || ch == ' ') {
matrix[i][j] = ch;
j++;
}
k++;
} else {
/* Add padding character '_' */
matrix[i][j] = '_';
j++;
}
}
}

for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) {


int columnIndex = entry.getValue();

// Get the cipher text from the matrix column-wise using the
permuted key
for (int i = 0; i < row; i++) {
if (Character.isLetter(matrix[i][columnIndex]) ||
matrix[i][columnIndex] == ' ' || matrix[i][columnIndex] == '_') {
cipher.append(matrix[i][columnIndex]);
}
}
}

return cipher.toString();
}

// Decryption
static String decryptMessage(String cipher) {
/* Calculate the number of columns for the cipher matrix */
int col = key.length();

int row = (int) Math.ceil((double) cipher.length() / col);


char[][] cipherMat = new char[row][col];

/* Add characters into the matrix column-wise */


int k = 0;
for (int j = 0; j < col; j++) {
for (int i = 0; i < row; i++) {
cipherMat[i][j] = cipher.charAt(k);
k++;
}
}

/* Update the order of the key for decryption */


int index = 0;
for (Map.Entry<Character, Integer> entry : keyMap.entrySet()) {
entry.setValue(index++);
}

/* Arrange the matrix column-wise according to the permutation


order */
char[][] decCipher = new char[row][col];
for (int l = 0; l < key.length(); l++) {
int columnIndex = keyMap.get(key.charAt(l));
for (int i = 0; i < row; i++) {
decCipher[i][l] = cipherMat[i][columnIndex];
}
}

/* Get the message using the matrix */


StringBuilder msg = new StringBuilder();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (decCipher[i][j] != '_') {
msg.append(decCipher[i][j]);
}
}
}

return msg.toString();
}

public static void main(String[] args) {


/* Message */
String msg = "Geeks for Geeks";

setPermutationOrder();

// Calling encryption function


String cipher = encryptMessage(msg);
System.out.println("Encrypted Message: " + cipher);

// Calling Decryption function


System.out.println("Decrypted Message: " +
decryptMessage(cipher));
}
}

Output:
Encrypted Message: e kefGsGsrekoe_
Decrypted Message: Geeks for Geeks

Columnar Transposition Technique

The columnar transposition cipher is more complex as compared to the rail


fence. The steps to obtain cipher text using this technique are as follow:

Step 1: The plain text is written in the rectangular matrix of the initially defined
size in a row by row pattern.

Step 2: To obtain the cipher text read the text written in a rectangular matrix
column by column. But you have to permute the order of column before reading
it column by column. The obtained message is the cipher text message.

To understand the columnar transposition let us take an example:

Plain text: meet Tomorrow

Now, put the plain text in the rectangle of a predefined size. For our example,
the predefined size of the rectangle would be 3×4. As you can see in the image
below the plain text is placed in the rectangle of 3×4. And we have also
permuted the order of the column

Now, to obtain the cipher text we have to read the plain text column by column
as the sequence of permuted column order. So, the cipher text obtained by the
columnar transposition technique in this example is:

Cipher Text: MTREOREMOTOW.

Similar to the rail fence cipher, the columnar cipher can be easily broken. The
cryptanalyst only has to try few permutation and combination over the order of
column to obtain the permuted order of column and the get the original
message. So, a more sophisticated technique was required to strengthen the
encryption.
Book Cipher or Running Key Cipher

The book cipher or the running key cipher works on the basic principle of one-
time pad cipher. In onetime pad cipher the key is taken as long as the plain text
and is discarded after the use. Every time a new key is taken for a new
message.

The improvement to the onetime pad in Book cipher is that the key or the
onetime pad is taken from the book. Let us discuss the steps:

Step 1: Convert the plain text in numeric form consider A=0, B=1, C=3 …,
Z=25.
Step 2: Take an onetime pad or key from any of the books and convert it in the
numeric form also. But the key must be as long as the length of plain text.

Step 3: Now add the numeric form of both plain text and key, each plain text
letter with corresponding key text letter. If the addition of any plain text letter
with corresponding key text letter is >26, then subtract it with 26.

Let us understand with the example:

Plain text: Meet Tomorrow

Key taken from the book: ANENCRYPTION.

Now we have to convert this plain text and key text in numeric form and add
them to get cipher text as shown in the image below:

The cipher text obtained is MRIGVFKDKZDJ.

You might also like