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

Security Lab Print

The document describes several cipher techniques including the Caesar cipher, Playfair cipher, Hill cipher, Vigenere cipher, and Rail fence cipher. The Caesar cipher encrypts text by shifting each letter by a fixed number of positions in the alphabet. The Playfair cipher encrypts pairs of letters and arranges them in a 5x5 grid. The Hill cipher encrypts blocks of letters using a matrix-based approach. The Vigenere cipher uses a keyword to shift letters by varying amounts. The Rail fence cipher writes out the letters of a message zigzag along the rails of a fence.

Uploaded by

Ani Anbu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Security Lab Print

The document describes several cipher techniques including the Caesar cipher, Playfair cipher, Hill cipher, Vigenere cipher, and Rail fence cipher. The Caesar cipher encrypts text by shifting each letter by a fixed number of positions in the alphabet. The Playfair cipher encrypts pairs of letters and arranges them in a 5x5 grid. The Hill cipher encrypts blocks of letters using a matrix-based approach. The Vigenere cipher uses a keyword to shift letters by varying amounts. The Rail fence cipher writes out the letters of a message zigzag along the rails of a fence.

Uploaded by

Ani Anbu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

CAESAR CIPHER

import java.util.Scanner;
public class ceasercipher
{
public static final String ALPHABET="abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText,int shiftKey)
{
plainText=plainText.toLowerCase();
String cipherText="";
for (int i=0; i<plainText.length();i++)
{
int charPosition=ALPHABET.indexOf(plainText.charAt(i));
int keyVal=(shiftKey+charPosition)%26;
char replaceVal=ALPHABET.charAt(keyVal);
cipherText+=replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText,int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for(int i=0;i<cipherText.length();i++)
{
int charPosition= ALPHABET. indexOf(cipherText. charAt(i));
int keyVal=(charPosition-shiftKey)%26;
if (keyVal< 0)
{
keyVal=ALPHABET.length()+keyVal;
}
char replaceVal=ALPHABET.charAt(keyVal);
plainText+=replaceVal;}
return plainText;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
String message=new String();
message=sc.next();
System.out.println("Encrypted message:Cipher Text="+encrypt(message,3));
System.out.println("Decrypted message:Plain Text="+decrypt (encrypt(
message,3),3));
sc.close();
}
}

OUTPUT:
F:\bin>javac ceasercipher.java
F:\bin>java ceasercipher
Enter the Plain text for Encryption:
covid
Encrypted message:Cipher Text=frylg
Decrypted message:Plain Text=covid
PLAYFAIR CIPHER

import java.util.Scanner;
public class Playfair1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter keyword: ");
String key=in.nextLine();
System.out.print("Enter message to encrypt: ");
String msg=in.nextLine();
PFEncryption pfEncryption=new PFEncryption();
pfEncryption.makeArray(key);
msg=pfEncryption.manageMessage(msg);
pfEncryption.doPlayFair(msg, "Encrypt");
String en=pfEncryption.getEncrypted();
System.out.println("Encrypting. ..\n\nThe encrypted text is: " + en);
System.out.println("=============================");
pfEncryption.doPlayFair(en, "Decrypt");
System.out.print("\nDecrypting... \n\nThe encrypted text is: " +
pfEncryption.getDecrypted());
}
}
class PFEncryption
{
private char [][] alphabets= new char[5][5];
private char[] uniqueChar= new char[26];
private String ch="ABCDEFGHIKLMNOPQRSTUVWXYZ";
private String encrypted="";
private String decrypted="";
void makeArray(String keyword){
keyword=keyword.toUpperCase().replace("J","I");
boolean present, terminate=false;
int val=0;
int uniqueLen;
for (int i=0; i<keyword.length(); i++)
{
present=false;
uniqueLen=0;
if (keyword.charAt(i)!= ' ')
{
for (int k=0; k<uniqueChar.length; k++)
{
if (Character.toString(uniqueChar[k])==null)
{
break;
}
uniqueLen++;
}
for (int j=0; j<uniqueChar.length; j++)
{
if (keyword.charAt(i)==uniqueChar[j])
{
present=true;
}
}
if (!present)
{
uniqueChar[val]=keyword.charAt(i);
val++;
}
}
ch=ch.replaceAll(Character.toString(keyword.charAt(i)), "");
}
for (int i=0; i<ch.length(); i++)
{
}
val=0;
uniqueChar[val]=ch.charAt(i);
val++;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
alphabets[i][j]=uniqueChar[val];
val++;
System.out.print(alphabets[i][j] + "\t");
}
System.out.println();
}}
String manageMessage(String msg)
{
int val=0;
int len=msg.length()-2;
String newTxt="";
String intermediate="";
while (len>=0)
{
intermediate=msg.substring(val, val+2);
if (intermediate.charAt(0)==intermediate.charAt(1))
{
newTxt=intermediate.charAt(0) + "x" + intermediate.charAt(1);
msg=msg.replaceFirst(intermediate, newTxt);
len++;
}
len-=2;
val+=2;
}
if (msg.length()%2!=0)
{
msg=msg+'x';
}
return msg.toUpperCase().replaceAll("J","I").replaceAll(" ","");
}
void doPlayFair(String msg, String tag)
{
int val=0;
while (val<msg.length())
{
searchAndEncryptOrDecrypt(msg.substring(val,val+2),tag);
val+=2;
}}
void searchAndEncryptOrDecrypt(String doubblyCh, String tag)
{
char ch1=doubblyCh.charAt(0);
char ch2=doubblyCh.charAt(1);
int row1=0, col1=0, row2=0, col2=0;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
if (alphabets[i][j]==ch1)
{
row1=i;
col1=j;
}
else if (alphabets[i][j]==ch2)
{
row2=i;col2=j;
}
}}
if (tag=="Encrypt")
encrypt(row1, col1, row2, col2);
else if(tag=="Decrypt")
decrypt(row1, col1, row2, col2);
}
void encrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1+1;
col2=col2+1;
if (col1>4)
col1=0;
if (col2>4)
col2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1+1;
row2=row2+1;
if (row1>4)
row1=0;
if (row2>4)
row2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{ encrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
void decrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1-1;
col2=col2-1;
if (col1<0)
col1=4;
if (col2<0)
col2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{row1=row1-1;
row2=row2-1;
if (row1<0)
row1=4;
if (row2<0)
row2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{
decrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
String getEncrypted( )
{
return encrypted;
}
String getDecrypted( )
{
return decrypted;
}}

OUTPUT:
F:\bin>javac Playfair1.java
F:\bin>java Playfair1
Enter keyword: INFOSEC
Enter message to encrypt: cryptography
I N F O S
E C A B D
G H K L M
P Q R T U
V W X Y Z
Encrypting....
The encrypted text is: AQVTYBKPERLW
=======================================
Decrypting....
The encrypted text is: CRYPTOGRAPHY
HILL CIPHER

import java.util.Scanner;
import javax.swing.JOptionPane;
public class hillcipher
{
//the 3x3 key matrix for 3 characters at once
public static int[][] keymat = new int[][]
{
{ 1, 2, 1 },
{ 2, 3, 2 },
{ 2, 2, 1 },
};
public static int[][] invkeymat = new int[][]
{
{ -1, 0, 1 },
{ 2, -1, 0 },
{ -2, 2, -1},
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args)
{
String text,outtext ="",outtext1="";
int ch, n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
//String text=new String();
text=sc.next();
text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spacesn = text.length() % 3;
if(n!=0)
{
for(int i = 1; i<= (3-n);i++)
{
text+= 'X';
}
}
System.out.println("Padded Text:" + text);
char[] ptextchars = text.toCharArray();
for(int i=0;i< text.length(); i+=3)
{
outtext += encrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
System.out.println("Encypted Message: " + outtext);
char[] ptextchars1 = outtext.toCharArray();
for(int i=0;i< outtext.length(); i+=3)
{
outtext1 += decrypt(ptextchars1[i],ptextchars1[i+1],ptextchars1[i+2]);
}
System.out.println("Decrypted Message: " + outtext1);
}
private static String encrypt(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 decrypt(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;
}
}

OUTPUT:
F:\bin>javac hillcipher.java
F:\bin>java hillcipher
Enter the Plain text for Encryption:
mothertheresa
Padded Text:MOTHERTHERESAXX
Encypted Message: AAHXIGPPLJEROLR
Decrypted Message: MOTHERTHERESAXX
F:\bin>java hillcipher
Enter the Plain text for Encryption:
hilcipher
Padded Text:HILCIPHER
Encypted Message: TIIWGHXIG
Decrypted Message: HILCIPHER
VIGENERE CIPHER

public class vigenerecipher1


{
public static String encrypt(String text,final String key)
{
String res="";
text=text.toUpperCase();
for(int i=0,j=0; i< text.length(); i++)
{
char c=text.charAt(i);
if(c<'A'||c>'z')
continue;
res+=(char)((c+key.charAt(j)-2*'A')%26+'A');
j=++j%key.length();
}
return res;
}
public static String decrypt(String text,finalString key)
{
String res="";
text=text.toUpperCase();
for(int i=0,j=0;i<text.length();i++)
{
char c=text.charAt(i);
if(c<'A'||c>'z')
continue;
res+=(char)((c-key.charAt(j)+26)%26+'A');
j=++j%key.length();
}
return res;}
public static void main(String[] args)
{
System.out.println("Enter the key: ");
String key = System.console().readLine();
System.out.println("Enter the message for encrytption: ");
String message = System.console().readLine();
String encryptedMsg=encrypt(message,key);
System.out.println("String :"+message);
System.out.println("Encrypted message:Cipher Text=" +encryptedMsg);
System.out.println("Decrypted message:Plain Text="
+decrypt(encryptedMsg,key));
}
}

OUTPUT:
F:\bin>javac vigenerecipher1.java
F:\bin>java vigenerecipher1
Enter the key:
SECURITY
Enter the message for encrytption:
CRYPTOGRAPHY
String :CRYPTOGRAPHY
Encrypted message:UVAJKWZPSTJS
Decrypted message:CRYPTOGRAPHY
RAIL FENCE CIPHER

class railfenceCipherHelper
{
int depth;
String encode(String msg, int depth) throws Exception
{
int r = depth;
int l = msg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String enc = "";
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
if (k != l)
{ mat[j][i] = msg.charAt(k++); }
else
{ mat[j][i] = 'X'; }
}}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
enc += mat[i][j];
}}
return enc;
}
String decode(String encmsg, int depth) throws Exception
{
int r = depth;
int l = encmsg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];String dec = "";
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
mat[i][j] = encmsg.charAt(k++);
}}
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
dec += mat[j][i];
}}
return dec;
}}
class railfencecipher
{
public static void main(String[] args) throws java.lang.Exception
{
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
System.out.println("Enter the Plain text: ");
msg = System.console().readLine();
int depth = 2;
enc = rf.encode(msg, depth);
dec = rf.decode(enc, depth);
System.out.println("Plain Text:"+msg);
System.out.println("Encrypted Message-Cipher Text:"+enc);
System.out.printf("Decrypted Message-:"+dec);
}
}

OUTPUT:
F:\bin>javac railfencecipher.java
F:\bin>java railfencecipher
Enter the Plain text:
paulinefreeda
Plain Text:paulinefreeda
Encrypted Message-Cipher Text:puiereaalnfed
Decrypted Message-:paulinefreeda
ROW AND COLUMN TRANSFORMATION TECHNIQUE

import java.util.*;
class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close();
String s = "";
int start = 0;
for (int i= 0; i< pl.length(); i++) {
if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);
System.out.println();
// end ofspace deletionint k = s.length();
int l = 0;
int col = 4;
int row = s.length() / col;
char ch[][] = new char[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}
char trans[][] = new char[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans[j][i] = ch[i][j];
}}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}}
System.out.println();
}
}

OUTPUT:
F:\bin>javac TransCipher.java
F:\bin>java TransCipher
Enter the plain text
altrozcarshervin
altrozcarshervin
aorrlzsvtchiraen
altr
ozca
rshe
rvIn
DATA ENCRYPTION STANDARD (DES)

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
class DES
{
byte[] skey=new byte[1000];
String skeystring;
static byte[] raw;
String inputmessage,encryptedata,decryptedmessage;
public DES()
{
try
{
generatesymmetrickey();
inputmessage=JOptionPane.showInputDialog(null,"Enter message to
encrypt:");
byte[] ibyte =inputmessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encrypteddata=new String(ebyte);
System.out.println("Encrypted message:"+encrypteddata);
JOptionPane.showMessageDialog(null,"Encrypted
Data"+"\n"+encrypteddata);
byte[] dbyte=decrypt(raw,ebyte);
String decryptedmessage=new String(dbyte);
System.out.println("Decrypted
message:"+decryptedmessage);JOptionPane.showMessageDialog(null,"Decrypted Data
"+"\n"+decryptedmessage);
}
catch(Exception e)
{
System.out.println(e);
}
}
void generatesymmetrickey()
{
try
{
}
Random r = new Random();
int num=r.nextInt(10000);
String knum=String.valueOf(num);
byte[] knumb=knum.getBytes();
skey=getRawKey(knumb);
skeystring=new String(skey);
System.out.println("DES
SymmerticKey="+skeystring);
catch(Exception e)
{
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception
{
KeyGenerator kgen=KeyGenerator.getInstance("DES");
SecureRandom sr =SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56,sr);
SecretKey skey=kgen.generateKey();
raw=skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw,byte[] clear) throws Exception
{
SecretKey seckey = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,seckey);
byte[] encrypted=cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw,byte[] encrypted) throws Exception
{
SecretKey seckey=new SecretKeySpec(raw, "DES");Cipher cipher =
Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,seckey);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[])
{
DES des=new DES();
}
}

OUTPUT:
AES ALGORITHM

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES
{
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key= Arrays.copyOf(key, 16);
secretKey= new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes
("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}return null;
}
public static String decrypt(String strToDecrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
System.out.println("Enter the secret key: ");
String secretKey= System.console().readLine();
System.out.println("Enter the original URL: ");
String originalString= System.console().readLine();
String encryptedString = AES.encrypt(originalString, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);
System.out.println("URL Encryption Using AES Algorithm\n ----------");
System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
C:\Security Lab New\programs>java AES
Enter the secret key:
annaUniversity
Enter the original URL:
www.annauniv.edu
URL Encryption Using AES Algorithm
Original URL : www.annauniv.edu
Encrypted URL : vibpFJW6Cvs5Y+L7t4N6YWWe07+JzS1d3CU2h3mEvEg=
Decrypted URL : www.annauniv.edu
RSA ALGORITHM
rsa.html
<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p> </td>
</tr>
<tr>
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td>
<td><input type="number" value="89" id="msg"></p> </td>
</tr>
<tr>
<td>Public Key:</td>
<td><p id="publickey"></p> </td>
</tr>
<tr>
<td>Exponent:</td>
<td><p id="exponent"></p> </td>
</tr><tr>
<td>Private Key:</td>
<td><p id="privatekey"></p></td>
</tr>
<tr>
<td>Cipher Text:</td>
<td><p id="ciphertext"></p> </td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td>
</tr>
</table> </center>
</body>
<script type="text/javascript">
function RSA()
{
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };
p = document.getElementById('p').value;
q = document.getElementById('q').value;
no = document.getElementById('msg').value;
n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++)
{
if (gcd(e, t) == 1)
{
break;
}
}
for (i = 0; i < 10; i++)
{
x=1+i*t
if (x % e == 0)
{
d = x / e;
break;
}
}
ctt = Math.pow(no, e).toFixed(0);
ct = ctt % n;
dtt = Math.pow(ct, d).toFixed(0);
dt = dtt % n;
document.getElementById('publickey').innerHTML = n;
document.getElementById('exponent').innerHTML = e;
document.getElementById('privatekey').innerHTML = d;
document.getElementById('ciphertext').innerHTML = ct;
}
</script></html>

OUTPUT:
DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM
import java.io.*;
import java.math.BigInteger;
class dh
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for x less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Sender's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Receiver's side:"+k2);
System.out.println("Diffie-Hellman secret key was calculated.");
}}
OUTPUT:
C:\Security Lab New\programs>javac dh.java
C:\Security Lab New\programs>java dh
Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Sender's side:9
Key calculated at Receiver'sside:9
Diffie-Hellman secret key was calculated.
SHA-1 ALGORITHM

import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha1
{
public static void main(String[] args)throws NoSuchAlgorithmException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String message = new String();
message = sc.next();
System.out.println("Mesage Digest is=");
System.out.println(sha1(message));
}
static String sha1(String input)throws NoSuchAlgorithmException
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for(int i = 0;i<result.length;i++)
{
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}

OUTPUT:
C:\Security Lab New\programs>java sha1
Enter the String:
CORONA VIRUS DISEASE
Mesage Digest is=
7690b7ccb987f4b3f32d2b9e7e8a69db2d0ded02
DIGITAL SIGNATURE SCHEME

import java.util.*;
import java.math.BigInteger;
class dsaAlg {
final static BigInteger one = new BigInteger("1");
final static BigInteger zero = new BigInteger("0");
public static BigInteger getNextPrime(String ans)
{
BigInteger test = new BigInteger(ans);
while (!test.isProbablePrime(99))
e:
{
test = test.add(one);
}
return test;
}
public static BigInteger findQ(BigInteger n)
{
BigInteger start = new BigInteger("2");
while (!n.isProbablePrime(99))
{
while (!((n.mod(start)).equals(zero)))
{
start = start.add(one);
}
n = n.divide(start);
}
return n;
}public static BigInteger getGen(BigInteger p, BigInteger q,
Random r)
{
BigInteger h = new BigInteger(p.bitLength(), r);
h = h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p);
}
public static void main (String[] args) throws
java.lang.Exception
{
Random randObj = new Random();
BigInteger p = getNextPrime("10600"); /* approximate
prime */
BigInteger q = findQ(p.subtract(one));
BigInteger g = getGen(p,q,randObj);
System.out.println(" \n simulation of Digital Signature Algorithm \n");
System.out.println(" \n global public key components are:\n");
System.out.println("\np is: " + p);
System.out.println("\nq is: " + q);
System.out.println("\ng is: " + g);
BigInteger x = new BigInteger(q.bitLength(), randObj);
x = x.mod(q);
BigInteger y= g.modPow(x,p);
BigInteger k = new BigInteger(q.bitLength(), randObj);
k = k.mod(q);
BigInteger r = (g.modPow(k,p)).mod(q);
BigInteger hashVal = new BigInteger(p.bitLength(),
randObj);
BigInteger kInv = k.modInverse(q);
BigInteger s = kInv.multiply(hashVal.add(x.multiply(r)));
s = s.mod(q);
System.out.println("\nsecret information are:\n");
System.out.println("x (private) is:" + x);
System.out.println("k (secret) is: " + k);
System.out.println("y (public) is: " + y);
System.out.println("h (rndhash) is: " + hashVal);
System.out.println("\n generating digital signature:\n");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
BigInteger w = s.modInverse(q);
BigInteger u1 = (hashVal.multiply(w)).mod(q);
BigInteger u2 = (r.multiply(w)).mod(q);
BigInteger v= (g.modPow(u1,p)).multiply(y.modPow(u2,p));
v = (v.mod(p)).mod(q);
System.out.println("\nverifying digital signature (checkpoints)\n:");
System.out.println("w is : " + w);
System.out.println("u1 is : " + u1);
System.out.println("u2 is : " + u2);
System.out.println("v is : " + v);
if (v.equals(r)){
System.out.println("\nsuccess: digital signature is verified!\n " + r);
}
else
{
System.out.println("\n error: incorrect digitalsignature\n ");
}
}
}

OUTPUT:
C:\Security Lab New\programs>javac dsaAlg.java
C:\Security Lab New\programs>java dsaAlg
simulation of Digital Signature Algorithm
global public key components are:
p is: 10601
q is: 53
g is: 6089
secret information are:
x(private) is:6
k (secret) is: 3
y (public) is: 1356
h (rndhash) is: 12619
generating digitalsignature:
r is : 2
s is :41
verifying digitalsignature (checkpoints):
w is : 22
u1 is : 4
u2 is : 44
v is : 2
success: digital signature is verified!
2
INTRUSION DETECTION SYSTEM (IDS)

To check the interface list, use following command:


snort –W

Finding an interface
You can tell which interface to use by looking at the Index number and finding Microsoft.
As you can see in the above example, the other interfaces are for VMWare. My interface is
3.
9. To run snort in IDS mode, you will need to configure the file “snort.conf” according to
your network environment.
10. To specify the network address that you want to protect in snort.conf file, look for the
following line.
var HOME_NET 192.168.1.0/24 (You will normally see any here)
11. You may also want to set the addresses of DNS_SERVERS, if you have some on your
network.
Example:
example snort
12. Change the RULE_PATH variable to the path of rules folder.
var RULE_PATH c:\snort\rules
path to rules
13. Change the path of all library files with the name and path on your system. and you must
change the path of snort_dynamicpreprocessorvariable.
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be:
“/usr/local/lib/…”. you will need to replace that path with your system path. Using
C:\Snort\lib
14. Change the path ofthe “dynamicengine” variable value in the “snort.conf” file..Example:
dynamicengine C:\Snort\lib\snort_dynamicengine\sf_engine.dll
15 Add the paths for “include classification.config” and “include reference.config” files.
include c:\snort\etc\classification.config
include c:\snort\etc\reference.config
16. Remove the comment (#) on the line to allow ICMP rules, if it is commented with a #.
include $RULE_PATH/icmp.rules
17. You can also remove the comment of ICMP-info rules comment, if it is commented.
include $RULE_PATH/icmp-info.rules
18. To add log files to store alerts generated by snort, search for the “output log” test in
snort.conf and add the following line:
output alert_fast:snort-alerts.ids
19. Comment (add a #) the whitelist $WHITE_LIST_PATH/white_list.rules and the
blacklist
Change the nested_ip inner , \ to nested_ip inner #, \

20. Comment out (#) following lines:


#preprocessor normalize_ip4
#preprocessor normalize_tcp: ips ecn stream
#preprocessor normalize_icmp4
#preprocessor normalize_ip6
#preprocessor normalize_icmp6
21. Save the “snort.conf” file.
22. To start snort in IDS mode, run the following command:
snort -c c:\snort\etc\snort.conf -l c:\snort\log -i 3
(Note: 3 is used for my interface card)
Ifa log is created, select the appropriate program to open it. You can use WordPard or
NotePad++ to read the file.
To generate Log files in ASCII mode, you can use following command while running snort in
IDS mode:
snort -A console -i3 -c c:\Snort\etc\snort.conf -l c:\Snort\log -K ascii
23. Scan the computer that is running snort from another computer by using PING or NMap
(ZenMap).
After scanning or during the scan you can check the snort-alerts.ids file in the log folder to
insure it is logging properly. You will see IP address folders appear.
Snort monitoring traffic-
EXPLORING N-STALKER

Now goto “Scan Session”, enter the target URL.


In scan policy, you can select from the four options,
 Manual test which will crawl the website and will be waiting for manual attacks.
 full xss assessment
 owasp policy
 Web server infrastructure analysis.
Once, the option has been selected, next step is “Optimize settings” which will crawl the
whole website for further analysis.
In review option, you can get all the information like host information, technologies used,
policy name, etc.
Once done, start the session and start the scan.
The scanner will crawl the whole website and will show the scripts, broken pages, hidden
fields, information leakage, web forms related information which helps to analyze further.
Once the scan is completed, the NStalker scanner will show details like severity level,
vulnerability class, why is it an issue, the fix for the issue and the URL which is vulnerable to
the particular vulnerability?
DEATING MALWARE - ROOTKIT HUNTEREF

Step 1

Visit GMER's website (see Resources) and download the GMER executable.
Click the "Download EXE" button to download the program with a random file name, as
some rootkits will close “gmer.exe” before you can open it.

Step 2

Double-click the icon for the program.


Click the "Scan" button in the lower-right corner ofthe dialog box. Allow the program to
scan your entire hard drive.
Step 3

When the program completes its scan, select any program or file listed in red. Right-click it
and select "Delete."
If the red item is a service, it may be protected. Right-click the service and select "Disable."
Reboot your computer and run the scan again, this time selecting "Delete" when that service
is detected.
When your computer is free of Rootkits, close the program and restart your PC.

You might also like