Network security

B

ns notes

A. Caesar Cipher:
Code:
import java.io.*;
importjava.math.*;
classCaesarCipher {
private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public String encrypt(String plainText, intshiftKey) {
plainText = plainText.toLowerCase();
String cipherText="";
for(inti=0;i<plainText.length();i++)
{
intcharPosition = ALPHABET.indexOf(plainText.charAt(i));
intkeyVal = (shiftKey+charPosition)%26;
charreplaceVal = this.ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
returncipherText;
}
public String decrypt(String cipherText, intshiftKey) {
cipherText = cipherText.toLowerCase();
String plainText="";
for(inti=0;i<cipherText.length();i++)
{
intcharPosition = this.ALPHABET.indexOf(cipherText.charAt(i));
intkeyVal = (charPosition-shiftKey)%26;
if(keyVal<0) {
keyVal = this.ALPHABET.length()+ keyVal;
}
charreplaceVal = this.ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
returnplainText;
}
}
classCaesarDemo {
public static void main(String args[]){
String plainText = "ankitayyer";
intshiftKey=3;
CaesarCipher cc = new CaesarCipher();
String cipherText = cc.encrypt(plainText,shiftKey);
System.out.println("Your Plain Text :" + plainText);
System.out.println("Your Cipher Text :" + cipherText);
String cPlainText = cc.decrypt (cipherText,shiftKey);
System.out.println("Your Plain Text :" + cPlainText);
}
}
Output:
B. Modified Caesar Cipher:
Code:
import java.io.*;
classcaesarcipher
{
public String encrypt(int shift, String line)
{
String result=" ";
int offset;
for(inti=0;i<line.length();i++)
{
offset=((int)line.charAt(i)+shift)%256;
result+=(char)(offset);
}
return result;
}
public String decrypt(int shift, String line)
{ String result=" ";
int offset;
for(inti=0;i<line.length();i++)
{
offset=((int)line.charAt(i)-shift)%256;
if(offset<0)
offset+=256;
result+=(char)(offset);
}
return result;
}
public static void main(String args[])throws IOException
{
caesarcipherobj=new caesarcipher();
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
int choice;
System.out.println("Menu:n1: Encryptionn2: Decryption");
choice=Integer.parseInt(in.readLine());
System.out.println("Enter the shift: ");
int shift=Integer.parseInt(in.readLine());
System.out.println("Enter the line: ");
String line=in.readLine();
System.out.println("Result:");
switch(choice){
case 1:System.out.println(obj.encrypt(shift,line));
break;
case 2:System.out.println(obj.decrypt(shift,line));
break;
default:
System.out.println("Invalid input!");
break;
} } }
Output:
C. Mono Alphabetic Cipher:
Code:
Import java.util.*;
public class Monoalpha {
public void Stringencode() {
System.out.println("t"+"MonoAlphabatic ENCODING");
String inp,code=" ";
char c = 0;
System.out.println("Enter a string: ");
Scanner sc=new Scanner(System.in);
inp=sc.next();
System.out.println("Ener the key:");
int k=sc.nextInt();
intlen=inp.length();
for(inti=0;i<len;i++) {
int x=inp.charAt(i);
if(x>=97 && x<=122) {
x=x+k;
k++;
if(x>122) {
int temp=x-122;
x=97+temp-1; }
c=(char)x; }
code=code+c; }
System.out.println("Cipher is :"+code); }
public static void main(String[] args) {
Monoalphaobj=new Monoalpha ();
obj.Stringencode(); } }
Output:
A. Rail Fence Techniques:
Code:
import java.io.*;
public class railfence
{
public static void main(String args[])
{
String input="MohitAmichand";
String output=" ";
intlen=input.length();
System.out.println("Input Text : "+input);
for(inti=0;i<len;i+=2)
{
output+=input.charAt(i);
}
for (inti=1;i<len;i+=2)
{
output+=input.charAt(i);
}
System.out.println("Ciphered Text :"+output);
}
}
Output:
B. Vernam Cipher:
Code:
Import java.lang.Math;
public class VernamCipher
{
public static void main(String args[])
{
String text = new String("Mohit");
char[] arText = text.toCharArray();
String cipher = new String("XYZHG");
char[] arCipher = cipher.toCharArray();
char[] encoded = new char[5];
System.out.println("Encoded " + text + " to be... ");
for (inti = 0; i<arText.length; i++)
{
encoded[i] = (char) (arText[i] ^ arCipher[i]);
System.out.print(encoded[i]);
}
System.out.println("nDecoded to be... ");
for (inti = 0; i<encoded.length; i++)
{
char temp = (char) (encoded[i] ^ arCipher[i]);
System.out.print(temp);
}
} }
Output:
Code:
Import java.util.*;
Import java.math.BigInteger;
public class DiffieHellmanBigInt {
final static BigInteger one = new BigInteger("1");
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
BigInteger p;
System.out.println("Enter the approximate value of p you want.");
String ans = stdin.next();
p = getNextPrime(ans);
System.out.println("Your prime is "+p+".");
System.out.println("Now, enter a number in between 2 and p-1");
BigInteger g = new BigInteger(stdin.next());
System.out.println("Person A: enter your secret number now.");
BigInteger a = new BigInteger(stdin.next());
BigIntegerresulta = g.modPow(a,p);
System.out.println("Person A sends to person B "+resulta+".");
System.out.println("Person B: enter your secret number now.");
BigInteger b = new BigInteger(stdin.next());
BigIntegerresultb = g.modPow(b,p);
System.out.println("Person B sends to person A "+resultb+".");
BigIntegerKeyACalculates = resultb.modPow(a,p);
BigIntegerKeyBCalculates = resulta.modPow(b,p);
System.out.println("A takes "+resultb+" raises it to the power "+a+" mod "+p);
System.out.println("The Key A calculates is "+KeyACalculates+".");
System.out.println("B takes "+resulta+" raises it to the power "+b+" mod "+p);
System.out.println("The Key B calculates is "+KeyBCalculates+".");
}
public static BigIntegergetNextPrime(String ans) {
BigInteger test = new BigInteger(ans);
while (!test.isProbablePrime(99))
test = test.add(one);
return test;
} }
Output:
Code:
Import java.security.*;
Import javax.crypto.*;
Import java.security.spec.*;
Import javax.crypto.spec.*;
public class StringEncrypter_SecretKey_DES {
Cipher ecipher;
Cipher dcipher;
String Encrypter_SecretKey_DES(SecretKey key, String algorithm) {
try {
ecipher = Cipher.getInstance(algorithm);
dcipher = Cipher.getInstance(algorithm);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (Exception e) {
e.printStackTrace();
}
return null; }
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (Exception e) {
e.printStackTrace();
}
return null; }
public static void testUsingSecretKey(){
try {
System.out.println();
System.out.println("+----------------------------------------+");
System.out.println("| -- Test Using Secret Key Method -- |");
System.out.println("+----------------------------------------+");
System.out.println();
String secretString = "MohitAmichand";
SecretKeydesKey = KeyGenerator.getInstance("DES").generateKey();
StringEncrypter_SecretKey_DESdesEncrypter = new StringEncrypter_SecretKey_DES(desKey,
desKey.getAlgorithm());
String desEncrypted = desEncrypter.encrypt(secretString);
String desDecrypted = desEncrypter.decrypt(desEncrypted);
System.out.println(desKey.getAlgorithm() + " Encryption algorithm");
System.out.println(" Original String : " + secretString);
System.out.println(" Encrypted String : " + desEncrypted);
System.out.println(" Decrypted String : " + desDecrypted);
System.out.println();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
testUsingSecretKey(); }
}
Output:
Code:
Import java.security.*;
Import javax.crypto.*;
import java.io.*;
public class AES_StringEncrypter{
Cipher ecipher;
Cipher dcipher;
publicAES_StringEncrypter(SecretKey key) {
try {
ecipher = Cipher.getInstance("AES");
dcipher = Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e) {}
}
public String encrypt(String str) {
try { byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch(Exception e) {}
return null;
}
public String decrypt(String str) {
try { byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch(Exception e) {}
return null;
}
public static void main(String args[]){
SecretKey key=null;
try {
KeyGeneratorkeyGen = KeyGenerator.getInstance("AES");
key = keyGen.generateKey();
}
catch (Exception e)
{
e.printStackTrace();}
AES_StringEncrypter dese = new AES_StringEncrypter(key);
String o = "MohitAmichand";
String en = dese.encrypt(o);
String de = dese.decrypt(en);
System.out.println("Original Text:"+o);
System.out.println("Encrypted Text:"+en);
System.out.println("Decrypted Text:"+de);
}
}
Output:
Code:
Import java.math.*;
classRSADemo {
RSADemo() {
BigInteger one = new BigInteger("1");
BigInteger zero = new BigInteger("0");
BigInteger p = new BigInteger("7");
BigInteger q = new BigInteger("19");
BigInteger N = p.multiply(q);
BigInteger temp1 = p.subtract(new BigInteger("1")); //(p-1)
BigInteger temp2 = q.subtract(new BigInteger("1")); //(q-1)
BigInteger m = temp1.multiply(temp2);
BigInteger e;
e = new BigInteger("2");
while (true) {
BigInteger res = m.gcd(e);
if (res.toString().equals("1")) {
break;
}
e = e.add(one);
}
BigInteger d=null;
BigInteger n1 = new BigInteger("0");
while (true) {
if
((one.add(n1.multiply(m))).remainder(e).toString().equals(zero.toString())) {
d = (one.add(n1.multiply(m))).divide(e);
break;
}
n1 = n1.add(one);
}
System.out.println("p = "+p+",q = "+q+"n");
System.out.println("N = p * q = "+N+"n");
System.out.println("m = (p-1) * (q-1) = "+m+"n");
System.out.println("e = "+e+"n");
System.out.println("d = (1 + (n1 * m))/e = "+d+"n");
System.out.println("Public Key --> ("+N+","+e+")"+"n");
System.out.println("Secret Key --> ("+N+","+d+")"+"n");
BigInteger P = new BigInteger("116");
BigInteger C = P.modPow(e,N);
System.out.println("Given plain text is 116");
System.out.println("Encryption:"+C+"n");
P = C.modPow(d,N);
System.out.println("Decryption:"+P+"n");
}
public static void main(String args[]) {
newRSADemo();
}}
Output:
Code:
Import java.security.*;
Import javax.crypto.*;
Import java.security.spec.*;
Import javax.crypto.spec.*;
public class RC4Algo {
Cipher ecipher;
Cipher dcipher;
RC4Algo(SecretKey key, String algorithm) {
try {
ecipher = Cipher.getInstance(algorithm);
dcipher = Cipher.getInstance(algorithm);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e) {
e.printStackTrace();
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String decrypt(String str) {
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void testUsingSecretKey() {
try {
System.out.println();
System.out.println("+----------------------------------------+");
System.out.println("| -- Test Using Secret Key Method -- |");
System.out.println("+----------------------------------------+");
System.out.println();
String secretString = "MohitAmichand";
SecretKeydesedeKey =KeyGenerator.getInstance("RC4").generateKey();
RC4Algo desedeEncrypter = new
RC4Algo(desedeKey, desedeKey.getAlgorithm());
String desedeEncrypted = desedeEncrypter.encrypt(secretString);
String desedeDecrypted = desedeEncrypter.decrypt(desedeEncrypted);
System.out.println(desedeKey.getAlgorithm() + " Encryption algorithm");
System.out.println(" Original String : " + secretString);
System.out.println(" Encrypted String : " + desedeEncrypted);
System.out.println(" Decrypted String : " + desedeDecrypted);
System.out.println();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
testUsingSecretKey();
}
}
Output:
Program:
importjava.security.*;
importjavax.crypto.*;
importjava.security.spec.*;
importjavax.crypto.spec.*;
public class StringEncrypter_SecretKey_BlowFish{
Cipher ecipher;
Cipher dcipher;
StringEncrypter_SecretKey_BlowFish(SecretKey key, String algorithm) {
try{
ecipher = Cipher.getInstance(algorithm);
dcipher = Cipher.getInstance(algorithm);
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e){
e.printStackTrace();}
}
public String encrypt(String str) {
try{
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (Exception e) {
e.printStackTrace();}
return null; }
public String decrypt(String str) {
try{
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (Exception e) {
e.printStackTrace();}
return null;
}
public static void testUsingSecretKey() {
try {
System.out.println();
System.out.println("+----------------------------------------+");
System.out.println("| -- Test Using Secret Key Method -- |");
System.out.println("+----------------------------------------+");
System.out.println();
String secretString = "MohitAmichand";
SecretKeyblowfishKey = KeyGenerator.getInstance("Blowfish").generateKey();
StringEncrypter_SecretKey_BlowFishblowfishEncrypter = new
StringEncrypter_SecretKey_BlowFish(blowfishKey, blowfishKey.getAlgorithm());
String blowfishEncrypted =blowfishEncrypter.encrypt(secretString);
String blowfishDecrypted =blowfishEncrypter.decrypt(blowfishEncrypted);
System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm");
System.out.println(" Original String : " + secretString);
System.out.println(" Encrypted String : " + blowfishEncrypted);
System.out.println(" Decrypted String : " + blowfishDecrypted);
System.out.println();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();}
}
public static void main(String[] args) {
testUsingSecretKey();
}
}
Output:

Recomendados

java sockets por
 java sockets java sockets
java socketsEnam Ahmed Shahaz
2.8K vistas15 diapositivas
Why Learn Python? por
Why Learn Python?Why Learn Python?
Why Learn Python?Christine Cheung
12.8K vistas84 diapositivas
Java VS Python por
Java VS PythonJava VS Python
Java VS PythonSimone Federici
3K vistas59 diapositivas
Programs por
ProgramsPrograms
Programskulwinderbawa007
9 vistas20 diapositivas
The Ring programming language version 1.10 book - Part 39 of 212 por
The Ring programming language version 1.10 book - Part 39 of 212The Ring programming language version 1.10 book - Part 39 of 212
The Ring programming language version 1.10 book - Part 39 of 212Mahmoud Samir Fayed
10 vistas10 diapositivas
Lo Mejor Del Pdc2008 El Futrode C# por
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
412 vistas41 diapositivas

Más contenido relacionado

La actualidad más candente

Cpds lab por
Cpds labCpds lab
Cpds labpraveennallavelly08
342 vistas23 diapositivas
C programs por
C programsC programs
C programsVikram Nandini
952 vistas49 diapositivas
Networking Core Concept por
Networking Core ConceptNetworking Core Concept
Networking Core ConceptRays Technologies
24 vistas15 diapositivas
Java Performance Puzzlers por
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
617 vistas68 diapositivas
CBSE Class XII Comp sc practical file por
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical filePranav Ghildiyal
2.8K vistas48 diapositivas
Introduzione a C# por
Introduzione a C#Introduzione a C#
Introduzione a C#Lorenz Cuno Klopfenstein
674 vistas54 diapositivas

La actualidad más candente(20)

Java Performance Puzzlers por Doug Hawkins
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
Doug Hawkins617 vistas
CBSE Class XII Comp sc practical file por Pranav Ghildiyal
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
Pranav Ghildiyal2.8K vistas
Collection v3 por Sunil OS
Collection v3Collection v3
Collection v3
Sunil OS105.5K vistas
The Ring programming language version 1.6 book - Part 32 of 189 por Mahmoud Samir Fayed
The Ring programming language version 1.6 book - Part 32 of 189The Ring programming language version 1.6 book - Part 32 of 189
The Ring programming language version 1.6 book - Part 32 of 189
The Ring programming language version 1.5.4 book - Part 10 of 185 por Mahmoud Samir Fayed
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185
Data structures cs301 power point slides lecture 03 por Nasir Mehmood
Data structures   cs301 power point slides lecture 03Data structures   cs301 power point slides lecture 03
Data structures cs301 power point slides lecture 03
Nasir Mehmood808 vistas
Lisp and prolog in artificial intelligence por ArtiSolanki5
Lisp and prolog in artificial intelligenceLisp and prolog in artificial intelligence
Lisp and prolog in artificial intelligence
ArtiSolanki5198 vistas
The Ring programming language version 1.5.3 book - Part 10 of 184 por Mahmoud Samir Fayed
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184
Developer Experience i TypeScript. Najbardziej ikoniczne duo por The Software House
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House105 vistas
Groovy grails types, operators, objects por Husain Dalal
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
Husain Dalal458 vistas
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB por tdc-globalcode
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
tdc-globalcode439 vistas
Alexey Tsoy Meta Programming in C++ 16.11.17 por LogeekNightUkraine
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
LogeekNightUkraine149 vistas
Dynamic C++ ACCU 2013 por aleks-f
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f4.4K vistas

Destacado

Teaching F# por
Teaching F#Teaching F#
Teaching F#Tomas Petricek
753 vistas22 diapositivas
Practical Encryption Tips and Tools por
Practical Encryption Tips and ToolsPractical Encryption Tips and Tools
Practical Encryption Tips and ToolsHeidi Alexander
224 vistas48 diapositivas
Watermarking & Encryption por
Watermarking & EncryptionWatermarking & Encryption
Watermarking & EncryptionHossam Halapi
1.8K vistas30 diapositivas
Teaching With Thinking Graphics por
Teaching With Thinking GraphicsTeaching With Thinking Graphics
Teaching With Thinking Graphicsjgentile
2K vistas34 diapositivas
A Brief History of Cryptography por
A Brief History of CryptographyA Brief History of Cryptography
A Brief History of Cryptographyguest9006ab
11.4K vistas20 diapositivas
Cryptography - A Brief History por
Cryptography - A Brief HistoryCryptography - A Brief History
Cryptography - A Brief Historyprasenjeetd
6.2K vistas39 diapositivas

Destacado(11)

Practical Encryption Tips and Tools por Heidi Alexander
Practical Encryption Tips and ToolsPractical Encryption Tips and Tools
Practical Encryption Tips and Tools
Heidi Alexander224 vistas
Watermarking & Encryption por Hossam Halapi
Watermarking & EncryptionWatermarking & Encryption
Watermarking & Encryption
Hossam Halapi1.8K vistas
Teaching With Thinking Graphics por jgentile
Teaching With Thinking GraphicsTeaching With Thinking Graphics
Teaching With Thinking Graphics
jgentile2K vistas
A Brief History of Cryptography por guest9006ab
A Brief History of CryptographyA Brief History of Cryptography
A Brief History of Cryptography
guest9006ab11.4K vistas
Cryptography - A Brief History por prasenjeetd
Cryptography - A Brief HistoryCryptography - A Brief History
Cryptography - A Brief History
prasenjeetd6.2K vistas
Project Method of Teaching por Mandeep Gill
 Project Method of Teaching Project Method of Teaching
Project Method of Teaching
Mandeep Gill401.8K vistas
LinkedIn SlideShare: Knowledge, Well-Presented por SlideShare
LinkedIn SlideShare: Knowledge, Well-PresentedLinkedIn SlideShare: Knowledge, Well-Presented
LinkedIn SlideShare: Knowledge, Well-Presented
SlideShare579.8K vistas
State of the Word 2011 por photomatt
State of the Word 2011State of the Word 2011
State of the Word 2011
photomatt636.2K vistas
The Great State of Design with CSS Grid Layout and Friends por Stacy Kvernmo
The Great State of Design with CSS Grid Layout and FriendsThe Great State of Design with CSS Grid Layout and Friends
The Great State of Design with CSS Grid Layout and Friends
Stacy Kvernmo2.1M vistas

Similar a Network security

Java binary subtraction por
Java binary subtractionJava binary subtraction
Java binary subtractionCharm Sasi
525 vistas2 diapositivas
Network security por
Network securityNetwork security
Network securityRakesh chaudhary
144 vistas7 diapositivas
Java Simple Programs por
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
6.2K vistas49 diapositivas
Cifrado cesar por
Cifrado cesarCifrado cesar
Cifrado cesarEIYSC
166 vistas1 diapositiva
Java programs por
Java programsJava programs
Java programsjojeph
1K vistas25 diapositivas
Ac2 por
Ac2Ac2
Ac2Muhammad Islahuddin
128 vistas13 diapositivas

Similar a Network security(20)

Java binary subtraction por Charm Sasi
Java binary subtractionJava binary subtraction
Java binary subtraction
Charm Sasi525 vistas
Java Simple Programs por Upender Upr
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr6.2K vistas
Cifrado cesar por EIYSC
Cifrado cesarCifrado cesar
Cifrado cesar
EIYSC166 vistas
Java programs por jojeph
Java programsJava programs
Java programs
jojeph1K vistas
Codeimport java.util.Scanner; import java.io.; class Test {.pdf por anujmkt
Codeimport java.util.Scanner; import java.io.; class Test {.pdfCodeimport java.util.Scanner; import java.io.; class Test {.pdf
Codeimport java.util.Scanner; import java.io.; class Test {.pdf
anujmkt5 vistas
Please help! Using Java Write the program that will do the following t.docx por rtodd19
Please help! Using Java Write the program that will do the following t.docxPlease help! Using Java Write the program that will do the following t.docx
Please help! Using Java Write the program that will do the following t.docx
rtodd192 vistas
java-comment both codes out for everyline- explain the code- will give.pdf por anjutandon12309
java-comment both codes out for everyline- explain the code- will give.pdfjava-comment both codes out for everyline- explain the code- will give.pdf
java-comment both codes out for everyline- explain the code- will give.pdf
anjutandon123093 vistas
I need help getting the following code to compile- import java-io-File.docx por patriciab30
I need help getting the following code to compile- import java-io-File.docxI need help getting the following code to compile- import java-io-File.docx
I need help getting the following code to compile- import java-io-File.docx
patriciab303 vistas
Go vs C++ - CppRussia 2019 Piter BoF por Timur Safin
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
Timur Safin150 vistas
IT8761-SECURITY LABORATORY-590519304-IT8761 security labmanual.pdf por DhanuskarSankar1
IT8761-SECURITY LABORATORY-590519304-IT8761 security labmanual.pdfIT8761-SECURITY LABORATORY-590519304-IT8761 security labmanual.pdf
IT8761-SECURITY LABORATORY-590519304-IT8761 security labmanual.pdf
DhanuskarSankar12 vistas

Último

Interaction of microorganisms with vascular plants.pptx por
Interaction of microorganisms with vascular plants.pptxInteraction of microorganisms with vascular plants.pptx
Interaction of microorganisms with vascular plants.pptxMicrobiologyMicro
58 vistas33 diapositivas
What is Digital Transformation? por
What is Digital Transformation?What is Digital Transformation?
What is Digital Transformation?Mark Brown
41 vistas11 diapositivas
Thanksgiving!.pdf por
Thanksgiving!.pdfThanksgiving!.pdf
Thanksgiving!.pdfEnglishCEIPdeSigeiro
568 vistas17 diapositivas
Pharmaceutical Analysis PPT (BP 102T) por
Pharmaceutical Analysis PPT (BP 102T) Pharmaceutical Analysis PPT (BP 102T)
Pharmaceutical Analysis PPT (BP 102T) yakshpharmacy009
116 vistas29 diapositivas
Retail Store Scavenger Hunt.pptx por
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptxjmurphy154
53 vistas10 diapositivas
Papal.pdf por
Papal.pdfPapal.pdf
Papal.pdfMariaKenney3
73 vistas24 diapositivas

Último(20)

Interaction of microorganisms with vascular plants.pptx por MicrobiologyMicro
Interaction of microorganisms with vascular plants.pptxInteraction of microorganisms with vascular plants.pptx
Interaction of microorganisms with vascular plants.pptx
MicrobiologyMicro58 vistas
What is Digital Transformation? por Mark Brown
What is Digital Transformation?What is Digital Transformation?
What is Digital Transformation?
Mark Brown41 vistas
Pharmaceutical Analysis PPT (BP 102T) por yakshpharmacy009
Pharmaceutical Analysis PPT (BP 102T) Pharmaceutical Analysis PPT (BP 102T)
Pharmaceutical Analysis PPT (BP 102T)
yakshpharmacy009116 vistas
Retail Store Scavenger Hunt.pptx por jmurphy154
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptx
jmurphy15453 vistas
Six Sigma Concept by Sahil Srivastava.pptx por Sahil Srivastava
Six Sigma Concept by Sahil Srivastava.pptxSix Sigma Concept by Sahil Srivastava.pptx
Six Sigma Concept by Sahil Srivastava.pptx
Sahil Srivastava51 vistas
Guess Papers ADC 1, Karachi University por Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz105 vistas
INT-244 Topic 6b Confucianism por S Meyer
INT-244 Topic 6b ConfucianismINT-244 Topic 6b Confucianism
INT-244 Topic 6b Confucianism
S Meyer49 vistas
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx por Niranjan Chavan
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptxGuidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Guidelines & Identification of Early Sepsis DR. NN CHAVAN 02122023.pptx
Niranjan Chavan42 vistas
12.5.23 Poverty and Precarity.pptx por mary850239
12.5.23 Poverty and Precarity.pptx12.5.23 Poverty and Precarity.pptx
12.5.23 Poverty and Precarity.pptx
mary850239514 vistas
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 por MysoreMuleSoftMeetup
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37

Network security

  • 1. A. Caesar Cipher: Code: import java.io.*; importjava.math.*; classCaesarCipher { private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz"; public String encrypt(String plainText, intshiftKey) { plainText = plainText.toLowerCase(); String cipherText=""; for(inti=0;i<plainText.length();i++) { intcharPosition = ALPHABET.indexOf(plainText.charAt(i)); intkeyVal = (shiftKey+charPosition)%26; charreplaceVal = this.ALPHABET.charAt(keyVal); cipherText += replaceVal; } returncipherText; } public String decrypt(String cipherText, intshiftKey) { cipherText = cipherText.toLowerCase(); String plainText=""; for(inti=0;i<cipherText.length();i++) { intcharPosition = this.ALPHABET.indexOf(cipherText.charAt(i)); intkeyVal = (charPosition-shiftKey)%26; if(keyVal<0) {
  • 2. keyVal = this.ALPHABET.length()+ keyVal; } charreplaceVal = this.ALPHABET.charAt(keyVal); plainText += replaceVal; } returnplainText; } } classCaesarDemo { public static void main(String args[]){ String plainText = "ankitayyer"; intshiftKey=3; CaesarCipher cc = new CaesarCipher(); String cipherText = cc.encrypt(plainText,shiftKey); System.out.println("Your Plain Text :" + plainText); System.out.println("Your Cipher Text :" + cipherText); String cPlainText = cc.decrypt (cipherText,shiftKey); System.out.println("Your Plain Text :" + cPlainText); } }
  • 4. B. Modified Caesar Cipher: Code: import java.io.*; classcaesarcipher { public String encrypt(int shift, String line) { String result=" "; int offset; for(inti=0;i<line.length();i++) { offset=((int)line.charAt(i)+shift)%256; result+=(char)(offset); } return result; } public String decrypt(int shift, String line) { String result=" "; int offset; for(inti=0;i<line.length();i++) { offset=((int)line.charAt(i)-shift)%256; if(offset<0) offset+=256; result+=(char)(offset);
  • 5. } return result; } public static void main(String args[])throws IOException { caesarcipherobj=new caesarcipher(); BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int choice; System.out.println("Menu:n1: Encryptionn2: Decryption"); choice=Integer.parseInt(in.readLine()); System.out.println("Enter the shift: "); int shift=Integer.parseInt(in.readLine()); System.out.println("Enter the line: "); String line=in.readLine(); System.out.println("Result:"); switch(choice){ case 1:System.out.println(obj.encrypt(shift,line)); break; case 2:System.out.println(obj.decrypt(shift,line)); break; default: System.out.println("Invalid input!"); break; } } }
  • 7. C. Mono Alphabetic Cipher: Code: Import java.util.*; public class Monoalpha { public void Stringencode() { System.out.println("t"+"MonoAlphabatic ENCODING"); String inp,code=" "; char c = 0; System.out.println("Enter a string: "); Scanner sc=new Scanner(System.in); inp=sc.next(); System.out.println("Ener the key:"); int k=sc.nextInt(); intlen=inp.length(); for(inti=0;i<len;i++) { int x=inp.charAt(i); if(x>=97 && x<=122) { x=x+k; k++; if(x>122) { int temp=x-122; x=97+temp-1; } c=(char)x; } code=code+c; } System.out.println("Cipher is :"+code); }
  • 8. public static void main(String[] args) { Monoalphaobj=new Monoalpha (); obj.Stringencode(); } } Output: A. Rail Fence Techniques:
  • 9. Code: import java.io.*; public class railfence { public static void main(String args[]) { String input="MohitAmichand"; String output=" "; intlen=input.length(); System.out.println("Input Text : "+input); for(inti=0;i<len;i+=2) { output+=input.charAt(i); } for (inti=1;i<len;i+=2) { output+=input.charAt(i); } System.out.println("Ciphered Text :"+output); } }
  • 11. Code: Import java.lang.Math; public class VernamCipher { public static void main(String args[]) { String text = new String("Mohit"); char[] arText = text.toCharArray(); String cipher = new String("XYZHG"); char[] arCipher = cipher.toCharArray(); char[] encoded = new char[5]; System.out.println("Encoded " + text + " to be... "); for (inti = 0; i<arText.length; i++) { encoded[i] = (char) (arText[i] ^ arCipher[i]); System.out.print(encoded[i]); } System.out.println("nDecoded to be... "); for (inti = 0; i<encoded.length; i++) { char temp = (char) (encoded[i] ^ arCipher[i]); System.out.print(temp); } } }
  • 13. Import java.util.*; Import java.math.BigInteger; public class DiffieHellmanBigInt { final static BigInteger one = new BigInteger("1"); public static void main(String args[]) { Scanner stdin = new Scanner(System.in); BigInteger p; System.out.println("Enter the approximate value of p you want."); String ans = stdin.next(); p = getNextPrime(ans); System.out.println("Your prime is "+p+"."); System.out.println("Now, enter a number in between 2 and p-1"); BigInteger g = new BigInteger(stdin.next()); System.out.println("Person A: enter your secret number now."); BigInteger a = new BigInteger(stdin.next()); BigIntegerresulta = g.modPow(a,p); System.out.println("Person A sends to person B "+resulta+"."); System.out.println("Person B: enter your secret number now."); BigInteger b = new BigInteger(stdin.next()); BigIntegerresultb = g.modPow(b,p); System.out.println("Person B sends to person A "+resultb+"."); BigIntegerKeyACalculates = resultb.modPow(a,p); BigIntegerKeyBCalculates = resulta.modPow(b,p); System.out.println("A takes "+resultb+" raises it to the power "+a+" mod "+p);
  • 14. System.out.println("The Key A calculates is "+KeyACalculates+"."); System.out.println("B takes "+resulta+" raises it to the power "+b+" mod "+p); System.out.println("The Key B calculates is "+KeyBCalculates+"."); } public static BigIntegergetNextPrime(String ans) { BigInteger test = new BigInteger(ans); while (!test.isProbablePrime(99)) test = test.add(one); return test; } } Output: Code:
  • 15. Import java.security.*; Import javax.crypto.*; Import java.security.spec.*; Import javax.crypto.spec.*; public class StringEncrypter_SecretKey_DES { Cipher ecipher; Cipher dcipher; String Encrypter_SecretKey_DES(SecretKey key, String algorithm) { try { ecipher = Cipher.getInstance(algorithm); dcipher = Cipher.getInstance(algorithm); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { e.printStackTrace(); } } public String encrypt(String str) { try { byte[] utf8 = str.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc); } catch (Exception e) {
  • 16. e.printStackTrace(); } return null; } public String decrypt(String str) { try { byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] utf8 = dcipher.doFinal(dec); return new String(utf8, "UTF8"); } catch (Exception e) { e.printStackTrace(); } return null; } public static void testUsingSecretKey(){ try { System.out.println(); System.out.println("+----------------------------------------+"); System.out.println("| -- Test Using Secret Key Method -- |"); System.out.println("+----------------------------------------+"); System.out.println(); String secretString = "MohitAmichand"; SecretKeydesKey = KeyGenerator.getInstance("DES").generateKey(); StringEncrypter_SecretKey_DESdesEncrypter = new StringEncrypter_SecretKey_DES(desKey, desKey.getAlgorithm());
  • 17. String desEncrypted = desEncrypter.encrypt(secretString); String desDecrypted = desEncrypter.decrypt(desEncrypted); System.out.println(desKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + desEncrypted); System.out.println(" Decrypted String : " + desDecrypted); System.out.println(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static void main(String[] args) { testUsingSecretKey(); } }
  • 19. Import java.security.*; Import javax.crypto.*; import java.io.*; public class AES_StringEncrypter{ Cipher ecipher; Cipher dcipher; publicAES_StringEncrypter(SecretKey key) { try { ecipher = Cipher.getInstance("AES"); dcipher = Cipher.getInstance("AES"); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) {} } public String encrypt(String str) { try { byte[] utf8 = str.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc); } catch(Exception e) {} return null; } public String decrypt(String str) { try { byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
  • 20. byte[] utf8 = dcipher.doFinal(dec); return new String(utf8, "UTF8"); } catch(Exception e) {} return null; } public static void main(String args[]){ SecretKey key=null; try { KeyGeneratorkeyGen = KeyGenerator.getInstance("AES"); key = keyGen.generateKey(); } catch (Exception e) { e.printStackTrace();} AES_StringEncrypter dese = new AES_StringEncrypter(key); String o = "MohitAmichand"; String en = dese.encrypt(o); String de = dese.decrypt(en); System.out.println("Original Text:"+o); System.out.println("Encrypted Text:"+en); System.out.println("Decrypted Text:"+de); } }
  • 22. Import java.math.*; classRSADemo { RSADemo() { BigInteger one = new BigInteger("1"); BigInteger zero = new BigInteger("0"); BigInteger p = new BigInteger("7"); BigInteger q = new BigInteger("19"); BigInteger N = p.multiply(q); BigInteger temp1 = p.subtract(new BigInteger("1")); //(p-1) BigInteger temp2 = q.subtract(new BigInteger("1")); //(q-1) BigInteger m = temp1.multiply(temp2); BigInteger e; e = new BigInteger("2"); while (true) { BigInteger res = m.gcd(e); if (res.toString().equals("1")) { break; } e = e.add(one); } BigInteger d=null; BigInteger n1 = new BigInteger("0"); while (true) { if ((one.add(n1.multiply(m))).remainder(e).toString().equals(zero.toString())) {
  • 23. d = (one.add(n1.multiply(m))).divide(e); break; } n1 = n1.add(one); } System.out.println("p = "+p+",q = "+q+"n"); System.out.println("N = p * q = "+N+"n"); System.out.println("m = (p-1) * (q-1) = "+m+"n"); System.out.println("e = "+e+"n"); System.out.println("d = (1 + (n1 * m))/e = "+d+"n"); System.out.println("Public Key --> ("+N+","+e+")"+"n"); System.out.println("Secret Key --> ("+N+","+d+")"+"n"); BigInteger P = new BigInteger("116"); BigInteger C = P.modPow(e,N); System.out.println("Given plain text is 116"); System.out.println("Encryption:"+C+"n"); P = C.modPow(d,N); System.out.println("Decryption:"+P+"n"); } public static void main(String args[]) { newRSADemo(); }}
  • 25. Import java.security.*; Import javax.crypto.*; Import java.security.spec.*; Import javax.crypto.spec.*; public class RC4Algo { Cipher ecipher; Cipher dcipher; RC4Algo(SecretKey key, String algorithm) { try { ecipher = Cipher.getInstance(algorithm); dcipher = Cipher.getInstance(algorithm); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { e.printStackTrace(); } } public String encrypt(String str) { try { byte[] utf8 = str.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc);
  • 26. } catch (Exception e) { e.printStackTrace(); } return null; } public String decrypt(String str) { try { byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] utf8 = dcipher.doFinal(dec); return new String(utf8, "UTF8"); } catch (Exception e) { e.printStackTrace(); } return null; } public static void testUsingSecretKey() { try { System.out.println(); System.out.println("+----------------------------------------+"); System.out.println("| -- Test Using Secret Key Method -- |"); System.out.println("+----------------------------------------+"); System.out.println();
  • 27. String secretString = "MohitAmichand"; SecretKeydesedeKey =KeyGenerator.getInstance("RC4").generateKey(); RC4Algo desedeEncrypter = new RC4Algo(desedeKey, desedeKey.getAlgorithm()); String desedeEncrypted = desedeEncrypter.encrypt(secretString); String desedeDecrypted = desedeEncrypter.decrypt(desedeEncrypted); System.out.println(desedeKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + desedeEncrypted); System.out.println(" Decrypted String : " + desedeDecrypted); System.out.println(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } public static void main(String[] args) { testUsingSecretKey(); } }
  • 29. importjava.security.*; importjavax.crypto.*; importjava.security.spec.*; importjavax.crypto.spec.*; public class StringEncrypter_SecretKey_BlowFish{ Cipher ecipher; Cipher dcipher; StringEncrypter_SecretKey_BlowFish(SecretKey key, String algorithm) { try{ ecipher = Cipher.getInstance(algorithm); dcipher = Cipher.getInstance(algorithm); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e){ e.printStackTrace();} } public String encrypt(String str) { try{ byte[] utf8 = str.getBytes("UTF8"); byte[] enc = ecipher.doFinal(utf8); return new sun.misc.BASE64Encoder().encode(enc); } catch (Exception e) { e.printStackTrace();}
  • 30. return null; } public String decrypt(String str) { try{ byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] utf8 = dcipher.doFinal(dec); return new String(utf8, "UTF8"); } catch (Exception e) { e.printStackTrace();} return null; } public static void testUsingSecretKey() { try { System.out.println(); System.out.println("+----------------------------------------+"); System.out.println("| -- Test Using Secret Key Method -- |"); System.out.println("+----------------------------------------+"); System.out.println(); String secretString = "MohitAmichand"; SecretKeyblowfishKey = KeyGenerator.getInstance("Blowfish").generateKey(); StringEncrypter_SecretKey_BlowFishblowfishEncrypter = new StringEncrypter_SecretKey_BlowFish(blowfishKey, blowfishKey.getAlgorithm()); String blowfishEncrypted =blowfishEncrypter.encrypt(secretString);
  • 31. String blowfishDecrypted =blowfishEncrypter.decrypt(blowfishEncrypted); System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm"); System.out.println(" Original String : " + secretString); System.out.println(" Encrypted String : " + blowfishEncrypted); System.out.println(" Decrypted String : " + blowfishDecrypted); System.out.println(); } catch (NoSuchAlgorithmException e) { e.printStackTrace();} } public static void main(String[] args) { testUsingSecretKey(); } }