Wednesday, 12 April 2017

HILL CIPHER

  HILL CIPHER

AIM
To write a program to encrypt and decrypt using  Hill cipher substitution technique

ALGORITHM DESCRIPTION

· The Hill cipher is a substitution cipher invented by Lester S. Hill in 1929.

· Each letter is represented by a number modulo 26. To encrypt a message, each block of n letters is multiplied by an invertible n × n matrix, again modulus 26.

· To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption. The matrix used for encryption is the cipher key, and it should be chosen randomly from the set of invertible n × n matrices (modulo 26).

· The cipher can, be adapted to an alphabet with any number of letters.

· All arithmetic just needs to be done modulo the number of letters instead of modulo 26.








PROGRAM
import java.util.*;
class hill
{
/* 3x3 key matrix for 3 characters at once */
public static int[][] keymat = new int[][]
{ { 1, 2, 1 }, { 2, 3, 2 }, { 2, 2, 1 } };
/* key inverse matrix */
public static int[][] invkeymat = new int[][]
{ { -1, 0, 1 }, { 2, -1, 0 }, { -2, 2, -1 } };
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static String encode(char a, char b, char c)
{
String ret = "";
int x,y, z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(x%26);
b = key.charAt(y%26);
c = key.charAt(z%26);
ret = "" + a + b + c;
return ret;
}
private static String decode(char a, char b, char c)
{
String ret = "";
int x,y,z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * invkeymat[0][0]+ posb * invkeymat[1][0] + posc * invkeymat[2][0];
y = posa * invkeymat[0][1]+ posb * invkeymat[1][1] + posc * invkeymat[2][1];
z = posa * invkeymat[0][2]+ posb * invkeymat[1][2] + posc * invkeymat[2][2];
a = key.charAt((x%26<0) ? (26+x%26) : (x%26));
b = key.charAt((y%26<0) ? (26+y%26) : (y%26));
c = key.charAt((z%26<0) ? (26+z%26) : (z%26));
ret = "" + a + b + c;
return ret;
}
public static void main (String[] args) throws java.lang.Exception
{
String msg;
String enc = "";
String dec = "";
int n;
msg = ("SecurityLaboratory");
System.out.println("simulation of Hill Cipher");
System.out.println("input message : " + msg);
msg = msg.toUpperCase();
msg = msg.replaceAll("\\s", ""); /* remove spaces */
n = msg.length() % 3;
/* append padding text X */
if (n != 0)
{
for(int i = 1; i<= (3-n);i++)
{
msg+= 'X';
}
}
System.out.println("padded message : " + msg);
char[] pdchars = msg.toCharArray();
for (int i=0; i < msg.length(); i+=3)
{
enc += encode(pdchars[i], pdchars[i+1], pdchars[i+2]);
}
System.out.println("encoded message : " + enc);
char[] dechars = enc.toCharArray();
for (int i=0; i< enc.length(); i+=3)
{
dec += decode(dechars[i], dechars[i+1], dechars[i+2]);
}
System.out.println("decoded message : " + dec);
}
}







OUTPUT

simulation of hill cipher
input message: SecurityLaboratory
padded message:SECURITYLABORATORY
encoded message:EACSDKLCAEFQDUKSXU
decoded message:SECURITYLABORATORY

Sunday, 9 April 2017

PLAYFAIR CIPHER

  PLAYFAIR CIPHER

AIM
To write a program to encrypt a plain text and decrypt a cipher text using Playfair Cipher substitution technique.

ALGORITHM DESCRIPTION

· The playfair cipher uses a 5 by 5 table containing a key word or phrase.

· To generate the key table, first fill the spaces in the table with the letters of the keyword, then fill the remaining spaces with the rest of the letters of the alphabet in order (usually omitting "Q" to reduce the alphabet to fit; other versions put both "I" and "J" in the same space).

· The key can be written in the top rows of the table, from left to right, or in some other pattern, such as a spiral beginning in the upper-left-hand corner and ending in the centre.

· The keyword together with the conventions for filling in the 5 by 5 table constitutes the cipher key. To encrypt a message, one would break the message into diagrams (groups of 2 letters) such that, for example, "HelloWorld" becomes "HE LL OW OR LD", and map them out on the key table. Then apply the following 4 rules, to each pair of letters in the plaintext:

· If both letters are the same (or only one letter is left), add an "X" after the first letter. Encrypt the new pair and continue. Some variants of Playfair use "Q" instead of "X", but any letter, itself uncommon as a repeated pair, will do.

· If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively (wrapping around to the left side of the row if a letter in the original pair was on the right side of the row).

· If the letters appear on the same column of your table, replace them with the letters immediately below respectively (wrapping around to the top side of the column if a letter in the original pair was on the bottom side of the column).

· If the letters are not on the same row or column, replace them with the letters on the same row respectively but at the other pair of corners of the rectangle defined by the original pair. The order is important – the first letter of the encrypted pair is the one that lies on the same row as the first letter of the plaintext pair.

· To decrypt, use the INVERSE (opposite) of the last 3 rules, and the 1st as-is (dropping any extra "X"s, or "Q"s that do not make sense in the final message when finished).

PROGRAM
import java.awt.Point;
import java.util.*;
class Play
{
private static char[][] charTable;
private static Point[] positions;
private static String prepareText(String s, boolean chgJtoI)
{
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTbl(String key, boolean chgJtoI)
{
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", chgJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++)
{
char c = s.charAt(i);
if (positions[c - 'A'] == null)
{
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String codec(StringBuilder txt, int dir)
{
int len = txt.length();
for (int i = 0; i < len; i += 2)
{
char a = txt.charAt(i);
char b = txt.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2)
{
col1 = (col1 + dir) % 5;
col2 = (col2 + dir) % 5;
}
else if (col1 == col2)
{
row1 = (row1 + dir) % 5;
row2 = (row2 + dir) % 5;
}
else
{
int tmp = col1;
col1 = col2;
col2 = tmp;
}
txt.setCharAt(i, charTable[row1][col1]);
txt.setCharAt(i + 1, charTable[row2][col2]);
}
return txt.toString();
}
private static String encode(String s)
{
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2)
{
if (i == sb.length() - 1)
{
sb.append(sb.length() % 2 == 1 ? 'X' : "");
}
else if (sb.charAt(i) == sb.charAt(i + 1))
{
sb.insert(i + 1, 'X');
}
}
return codec(sb, 1);
}
private static String decode(String s)
{
return codec(new StringBuilder(s), 4);
}
public static void main (String[] args) throws java.lang.Exception
{
String key = "mysecretkey";
String txt = "CRYPTOLABS"; /* make sure string length is even */
/* change J to I */
boolean chgJtoI = true;
createTbl(key, chgJtoI);
String enc = encode(prepareText(txt, chgJtoI));
System.out.println("simulation of Playfair Cipher");
System.out.println("input message : " + txt);
System.out.println("encoded message : " + enc);
System.out.println("decoded message : " + decode(enc));
}
}


output:

simulation of Playfair Cipher

input message: CRYPTOLABS
encoded message:MBENKNPRKC
decoded message:CRYPTOLABS

ceaser cipher

SUBSTITUTION & TRANSPOSITION TECHNIQUES
 CAESAR CIPHER


AIM
To write a program for encrypting a plain text and decrypting a cipher text using Caesar Cipher (shift cipher) substitution technique

ALGORITHM DESCRIPTION

· It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.

· The method is named after Julius Caesar, who used it in his private correspondence.

· The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain alphabet rotated left or right by some number of positions.

· The encryption can also be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1, Z = 25.

· Encryption of a letter x by a shift n can be described mathematically as,

En(x) = (x + n) mod26

· Decryption is performed similarly,

Dn (x)=(x - n) mod26







PROGRAM
import java.io.*;
importjava.util.Scanner;
public class CaeserCipher
 {
public static void main(String[] args)
{            
Scanner s=new Scanner(System.in);
System.out.println("Input Data to encypt:");
        String str = s.nextLine();
System.out.println("Input the key");
int key =s.nextInt();
         String encrypted = encrypt(str, key);
System.out.println("Encrypted Data :" + encrypted);
        String decrypted = decrypt(encrypted, key);
System.out.println("Decrypted Data:" + decrypted);
    }
public static String encrypt(String str, int key)
    {
       String encrypted = "";
for(int i = 0; i <str.length(); i++)
        {
int c = str.charAt(i);
if (Character.isUpperCase(c))
            {                
                c = c + (key % 26);
if (c > 'Z')
                c = c - 26;
            }
else if (Character.isLowerCase(c))
            {
                c = c + (key % 26);
if (c > 'z')
                c = c - 26;
            }
encrypted += (char) c;
        }
return encrypted;
    }
public static String decrypt(String str, int key)
    {
        String decrypted = "";
for(int i = 0; i <str.length(); i++)
        {
int c = str.charAt(i);
if (Character.isUpperCase(c))
            {
                c = c - (key % 26);
if (c < 'A')
                c = c + 26;
           }
else if (Character.isLowerCase(c))
            {
                c = c - (key % 26);
if (c < 'a')
                c = c + 26;
            }
decrypted += (char) c;
        }
return decrypted;
    }
}

OUTPUT

Input Data to encrypt:
 Hello How wre you
Input the key
3
Encrypted data: khoor krz zuh brx
Decrypted data : hello how wre you


Sunday, 26 March 2017

secure electronic transaction

SECURE ELECTRONIC TRANSACTION SET is an open encryption and security specification designed to protect credit card transactions on the Internet. The current version, SETv1, emerged from a call for security standards by MasterCard and Visa in February 1996. A wide range of companies were involved in developing the initial specification, including IBM, Microsoft, Netscape, RSA, Terisa, and Verisign. Beginning in 1996. SET is not itself a payment system. Rather it is a set of security protocols and formats that enables users to employ the existing credit card payment infrastructure on an open network, such as the Internet, in a secure fashion. In essence, SET provides three services:
 • Provides a secure communications channel among all parties involved in a transaction
 • Provides trust by the use of X.509v3 digital certificates
 • Ensures privacy because the information is only available to parties in a transaction when and
where necessary.
 SET Overview: A good way to begin our discussion of SET is to look at the business requirements for SET, its key features, and the participants in SET transactions.
Requirements: The SET specification lists the following business requirements for secure payment processing with credit cards over the Internet and other networks:
• Provide confidentiality of payment and ordering information: It is necessary to assure cardholders that this information is safe and accessible only to the intended recipient. Confidentiality also reduces the risk of fraud by either party to the transaction or by malicious third parties. SET uses encryption to provide confidentiality.
• Ensure the integrity of all transmitted data: That is, ensure that no changes in content occur during transmission of SET messages. Digital signatures are used to provide integrity.
• Provide authentication that a cardholder is a legitimate user of a credit card account: A mechanism that links a cardholder to a specific account number reduces the incidence of fraud and the overall cost of payment processing. Digital signatures and certificates are used to verify that a cardholder is a legitimate user of a valid account.
 • Provide authentication that a merchant can accept credit card transactions through its relationship with a financial institution: This is the complement to the preceding requirement. Cardholders need to be able to identify merchants with whom they can conduct secure transactions. Again, digital signatures and certificates are used.
 • Ensure the use of the best security practices and system design techniques to protect all legitimate parties in an electronic commerce transaction: SET is a well-tested specification based on highly secure cryptographic algorithms and protocols.
 • Create a protocol that neither depends on transport security mechanisms nor prevents their use: SET can securely operate over a "raw" TCP/IP stack. However, SET does not interfere with the use of other security mechanisms, such as IPSec and SSL/TLS.
 • Facilitate and encourage interoperability among software and network providers: The SET protocols and formats are independent of hardware platform, operating system, and Web software. Key Features of SET To meet the requirements just outlined, SET incorporates the following features:
 • Confidentiality of information: Cardholder account and payment information is secured as it travels across the network. An interesting and important feature of SET is that it prevents the merchant from learning the cardholder's credit card number; this is only provided to the issuing bank. Conventional encryption by DES is used to
provide confidentiality.
• Integrity of data: Payment information sent from cardholders to merchants includes order information, personal data, and payment instructions. SET guarantees that these message contents are not altered in transit. RSA digital signatures, using SHA-1 hash codes, provide message integrity. Certain messages are also protected by HMAC using SHA-1.
• Cardholder account authentication: SET enables merchants to verify that a cardholder is a legitimate user of a valid card account number. SET uses X.509v3 digital certificates with RSA signatures for this purpose.
 • Merchant authentication: SET enables cardholders to verify that a merchant has a relationship with a financial institution allowing it to accept payment cards. SET uses X.509v3 digital certificates with RSA signatures for this purpose. Note that unlike IPSec and SSL/TLS, SET provides only one choice for each cryptographic algorithm. This makes sense, because SET is a single application with a single set of requirements, whereas IPSec and SSL/TLS are intended to support a range of applications.

Wednesday, 22 March 2017

Jagged array

Jagged Array
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays.
The following is a declaration of a single-dimensional array that has three elements, each of which is a single-dimensional array of integers:
C#
int[][] jaggedArray = new int[3][];
Before you can use jaggedArray, its elements must be initialized. You can initialize the elements like this:
C#
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers.
It is also possible to use initializers to fill the array elements with values, in which case you do not need the array size. For example:
C#
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
You can also initialize the array upon declaration like this:
C#
    int[][] jaggedArray2 = new int[][]
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};
You can use the following shorthand form. Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:
C#
    int[][] jaggedArray3 =
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
You can access individual array elements like these examples:
C#
// Assign 77 to the second element ([1]) of the first array ([0]):
jaggedArray3[0][1] = 77;

// Assign 88 to the second element ([1]) of the third array ([2]):
jaggedArray3[2][1] = 88;
It is possible to mix jagged and multidimensional arrays. The following is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes. For more information about two-dimensional arrays, see Multidimensional Arrays (C# Programming Guide).
C#
int[][,] jaggedArray4 = new int[3][,]
{
    new int[,] { {1,3}, {5,7} },
    new int[,] { {0,2}, {4,6}, {8,10} },
    new int[,] { {11,22}, {99,88}, {0,9} }
};