· 7 years ago · Oct 25, 2018, 09:52 PM
1
2//A Java Program to illustrate Caesar Cipher Technique
3class CaesarCipher
4{
5 // Encrypts text using a shift od s
6 public static StringBuffer encrypt(String text, int s)
7 {
8 StringBuffer result= new StringBuffer();
9
10 for (int i=0; i<text.length(); i++)
11 {
12 if (Character.isUpperCase(text.charAt(i)))
13 {
14 char ch = (char)(((int)text.charAt(i) +
15 s - 65) % 26 + 65);
16 result.append(ch);
17 }
18 else
19 {
20 char ch = (char)(((int)text.charAt(i) +
21 s - 97) % 26 + 97);
22 result.append(ch);
23 }
24 }
25 return result;
26 }
27
28 // Driver code
29 public static void main(String[] args)
30 {
31 String text = "ATTACKATONCE";
32 int s = 4;
33 System.out.println("Text : " + text);
34 System.out.println("Shift : " + s);
35 System.out.println("Cipher: " + encrypt(text, s));
36 }
37}
38
39
40//play fair
41import java.awt.Point;
42import java.util.Scanner;
43
44public class PlayfairCipher {
45 private static char[][] charTable;
46 private static Point[] positions;
47
48 public static void main(String[] args) {
49 Scanner sc = new Scanner(System.in);
50
51 String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
52 String txt = prompt("Enter the message: ", sc, 1);
53 String jti = prompt("Replace J with I? y/n: ", sc, 1);
54
55 boolean changeJtoI = jti.equalsIgnoreCase("y");
56
57 createTable(key, changeJtoI);
58
59 String enc = encode(prepareText(txt, changeJtoI));
60
61 System.out.printf("%nEncoded message: %n%s%n", enc);
62 System.out.printf("%nDecoded message: %n%s%n", decode(enc));
63 }
64
65 private static String prompt(String promptText, Scanner sc, int minLen) {
66 String s;
67 do {
68 System.out.print(promptText);
69 s = sc.nextLine().trim();
70 } while (s.length() < minLen);
71 return s;
72 }
73
74 private static String prepareText(String s, boolean changeJtoI) {
75 s = s.toUpperCase().replaceAll("[^A-Z]", "");
76 return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
77 }
78
79 private static void createTable(String key, boolean changeJtoI) {
80 charTable = new char[5][5];
81 positions = new Point[26];
82
83 String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
84
85 int len = s.length();
86 for (int i = 0, k = 0; i < len; i++) {
87 char c = s.charAt(i);
88 if (positions[c - 'A'] == null) {
89 charTable[k / 5][k % 5] = c;
90 positions[c - 'A'] = new Point(k % 5, k / 5);
91 k++;
92 }
93 }
94 }
95
96 private static String encode(String s) {
97 StringBuilder sb = new StringBuilder(s);
98
99 for (int i = 0; i < sb.length(); i += 2) {
100
101 if (i == sb.length() - 1)
102 sb.append(sb.length() % 2 == 1 ? 'X' : "");
103
104 else if (sb.charAt(i) == sb.charAt(i + 1))
105 sb.insert(i + 1, 'X');
106 }
107 return codec(sb, 1);
108 }
109
110 private static String decode(String s) {
111 return codec(new StringBuilder(s), 4);
112 }
113
114 private static String codec(StringBuilder text, int direction) {
115 int len = text.length();
116 for (int i = 0; i < len; i += 2) {
117 char a = text.charAt(i);
118 char b = text.charAt(i + 1);
119
120 int row1 = positions[a - 'A'].y;
121 int row2 = positions[b - 'A'].y;
122 int col1 = positions[a - 'A'].x;
123 int col2 = positions[b - 'A'].x;
124
125 if (row1 == row2) {
126 col1 = (col1 + direction) % 5;
127 col2 = (col2 + direction) % 5;
128
129 } else if (col1 == col2) {
130 row1 = (row1 + direction) % 5;
131 row2 = (row2 + direction) % 5;
132
133 } else {
134 int tmp = col1;
135 col1 = col2;
136 col2 = tmp;
137 }
138
139 text.setCharAt(i, charTable[row1][col1]);
140 text.setCharAt(i + 1, charTable[row2][col2]);
141 }
142 return text.toString();
143 }
144}
145
146
147
148//hill cipher
149
150import java.util.*;
151class hillCipher
152{
153/* 3x3 key matrix for 3 characters at once */ public static int[][] keymat = new int[][]
154{ { 1, 2, 1 }, { 2, 3, 2 }, { 2, 2, 1 } }; /* key inverse matrix */
155public static int[][] invkeymat = new int[][] { {-1, 0, 1 }, { 2, -1, 0 }, { -2, 2, -1 } };
156public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static String encode(char a, char b, char c)
157{
158String ret = ""; int x,y, z;
159int posa = (int)a - 65; int posb = (int)b - 65; int posc = (int)c - 65;
160x = 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);
161b = key.charAt(y%26); c = key.charAt(z%26);
162ret = "" + a + b + c; return ret;
163}
164private static String decode(char a, char b, char c)
165{
166String ret = ""; int x,y,z;
167int posa = (int)a - 65; int posb = (int)b - 65; int posc = (int)c - 65;
168x = posa * invkeymat[0][0]+ posb * invkeymat[1][0] + posc * invkeymat[2][0];
169y = posa * invkeymat[0][1]+ posb * invkeymat[1][1] + posc * invkeymat[2][1];
170z = posa * invkeymat[0][2]+ posb * invkeymat[1][2] + posc * invkeymat[2][2];
171a = key.charAt((x%26<0) ? (26+x%26) : (x%26));
172b = key.charAt((y%26<0) ? (26+y%26) : (y%26)); c = key.charAt((z%26<0) ? (26+z%26) : (z%26));
173ret = "" + a + b + c;
174return ret;
175}
176public static void main (String[] args) throws java.lang.Exception
177{
178String msg; String enc = ""; String dec = "";
179 int n;
180msg = ("SecurityLaboratory"); System.out.println("simulation of Hill Cipher");
181System.out.println("input message : " + msg);
182msg = msg.toUpperCase();
183msg = msg.replaceAll("\\s", ""); /* remove spaces */ n = msg.length() % 3;
184/* append padding text X */ if (n != 0)
185{
186for(int i = 1; i<= (3-n);i++)
187{
188msg+= 'X';
189}
190}
191System.out.println("padded message : " + msg);
192char[] pdchars = msg.toCharArray(); for (int i=0; i < msg.length(); i+=3)
193{
194enc += encode(pdchars[i], pdchars[i+1], pdchars[i+2]);
195}
196System.out.println("encoded message : " + enc); char[] dechars = enc.toCharArray();
197for (int i=0; i< enc.length(); i+=3)
198{
199dec += decode(dechars[i], dechars[i+1], dechars[i+2]);
200}
201System.out.println("decoded message : " + dec);
202}
203}
204
205
206
207//vignere cipher
208
209public class VigenereCipherJava {
210 public static void main(String...s){
211 char msg[] = {'T','H','E','J','A','V','A','P','R','O','G','R','A','M','M','E','R'};
212 char key[] = {'N','E','E','R','A','J'};
213 int msgLen = msg.length, i, j;
214
215 char newKey[] = new char[msgLen];
216 char encryptedMsg[] = new char[msgLen];
217 char decryptedMsg[] = new char[msgLen];
218
219 //generate new key in cyclic manner equal to the length of original message
220 for(i = 0, j = 0; i < msgLen; ++i, ++j){
221 if(j == key.length)
222 j = 0;
223
224 newKey[i] = key[j];
225 }
226
227 //encryption
228 for(i = 0; i < msgLen; ++i)
229 encryptedMsg[i] = (char)(((msg[i] + newKey[i]) % 26) + 'A');
230
231 //decryption
232 for(i = 0; i < msgLen; ++i)
233 decryptedMsg[i] = (char)((((encryptedMsg[i] - newKey[i]) + 26) % 26) + 'A');
234
235 System.out.println("Original Message: " + String.valueOf(msg)); //String.valueOf() converts character array to String
236 System.out.println("Key: " + String.valueOf(key));
237 System.out.println("Generated Key: " + String.valueOf(newKey));
238 System.out.println("\nEncrypted Message: " + String.valueOf(encryptedMsg));
239 System.out.println("\nDecrypted Message: " + String.valueOf(decryptedMsg));
240 }
241}
242
243
244//Railfence
245import java.util.Scanner;
246public class railfence {
247 public static void main(String[] args) {
248 // TODO code application logic here
249 Scanner sc=new Scanner(System.in);
250 String s1="";
251 String s2="";
252 System.out.println("Enter the PlainText");
253 String pt=sc.nextLine();
254 char[] ch=pt.toCharArray();
255 for(int i=0;i<pt.length();i++){
256 if(i%2==0)
257 s1+=Character.toString(ch[i]);
258 else
259 s2+=Character.toString(ch[i]); }
260 System.out.println("Encrypted Text:" +s1+s2);
261 System.out.print("Decrypted Text:");
262 if(pt.length()%2==0){
263 for(int i=0;i<(pt.length()/2);i++){
264 System.out.print(s1.charAt(i));
265 System.out.print(s2.charAt(i));
266 } }
267
268
269 else
270 {
271 for(int i=0;i<(pt.length()/2)+1;i++){
272 System.out.print(s1.charAt(i));
273 if(i==(pt.length()/2))
274 break;
275 System.out.print(s2.charAt(i));
276 }
277 }
278 }
279}
280
281
282//RSA
283import java.util.Scanner;
284public class rsa {
285 public static void main(String args[])
286 {
287 Scanner sc=new Scanner(System.in);
288 int p,q,n,z,d=0,e,i;
289 System.out.println("Enter the number to be encrypted and decrypted");
290 int msg=sc.nextInt();
291
292 double c,msgback;
293 System.out.println("Enter 1st prime number p");
294 p=sc.nextInt();
295 System.out.println("Enter 2nd prime number q");
296 q=sc.nextInt();
297
298 n=p*q;
299 z=(p-1)*(q-1);
300 System.out.println("the value of z = "+z);
301 for(e=2;e<z;e++)
302 {
303 if(gcd(e,z)==1)
304 {
305 break;
306 }
307 }
308 System.out.println("the value of e = "+e);
309 for(i=1;;i++){
310 if((e*i)%z==1){
311 d=i;
312 break;
313 }
314 }
315 System.out.println("the value of d = "+d);
316 c=(Math.pow(msg,e))%n;
317 System.out.println("Encrypted message is : -");
318 System.out.println(c);
319 msgback=(Math.pow(c,d))%n;
320 System.out.println("Derypted message is : -");
321 System.out.println(msgback);
322 }
323 static int gcd(int e, int z)
324 {
325 if(e==0)
326 return z;
327 else
328
329 return gcd(z%e,e);
330 }
331
332
333//MD5
334import java.math.BigInteger;
335import java.security.MessageDigest;
336import java.security.NoSuchAlgorithmException;
337import java.util.Scanner;
338public class md55 {
339 public static String getMd5(String input)
340 {
341 try {
342 MessageDigest md = MessageDigest.getInstance("MD5");
343 byte[] messageDigest = md.digest(input.getBytes());
344 BigInteger no = new BigInteger(1, messageDigest);
345 String hashtext = no.toString(16);
346 while (hashtext.length() < 32) {
347 hashtext = "0" + hashtext;
348 }
349 return hashtext;
350 }
351 catch (NoSuchAlgorithmException e) {
352 throw new RuntimeException(e);
353 }
354 }
355 public static void main(String args[]) throws NoSuchAlgorithmException
356 {
357 String s ="";
358 System.out.println("enter your string");
359 Scanner sc=new Scanner(System.in);
360 s=sc.next();
361 System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
362 }
363}
364
365
366
367
368//sha1
369import java.security.*;
370class JceSha1Test {
371 public static void main(String[] a) {
372 try {
373 MessageDigest md = MessageDigest.getInstance("SHA1");
374 System.out.println("Message digest object info: ");
375 System.out.println(" Algorithm = "+md.getAlgorithm());
376 System.out.println(" Provider = "+md.getProvider());
377 System.out.println(" toString = "+md.toString());
378
379 String input = "";
380 md.update(input.getBytes());
381 byte[] output = md.digest();
382 System.out.println();
383 System.out.println("SHA1(\""+input+"\") =");
384 System.out.println(" "+bytesToHex(output));
385
386 input = "abc";
387 md.update(input.getBytes());
388 output = md.digest();
389 System.out.println();
390 System.out.println("SHA1(\""+input+"\") =");
391 System.out.println(" "+bytesToHex(output));
392
393 input = "abcdefghijklmnopqrstuvwxyz";
394 md.update(input.getBytes());
395 output = md.digest();
396 System.out.println();
397 System.out.println("SHA1(\""+input+"\") =");
398 System.out.println(" "+bytesToHex(output));
399
400 } catch (Exception e) {
401 System.out.println("Exception: "+e);
402 }
403 }
404 public static String bytesToHex(byte[] b) {
405 char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
406 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
407 StringBuffer buf = new StringBuffer();
408 for (int j=0; j<b.length; j++) {
409 buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
410 buf.append(hexDigit[b[j] & 0x0f]);
411 }
412 return buf.toString();
413 }
414}
415
416
417//digital key
418
419import java.util.*;
420import java.math.BigInteger; class dsaAlg
421{
422final static BigInteger one = new BigInteger("1");
423final static BigInteger zero = new BigInteger("0");
424/* incrementally tries for next prime */
425public static BigInteger getNextPrime(String ans)
426{
427BigInteger test = new BigInteger(ans); while (!test.isProbablePrime(99))
428{
429test = test.add(one);
430}
431return test;
432}
433/* finds largest prime factor of n */
434public static BigInteger findQ(BigInteger n)
435{
436BigInteger start = new BigInteger("2"); while (!n.isProbablePrime(99))
437{
438while (!((n.mod(start)).equals(zero)))
439{
440start = start.add(one);
441}
442n = n.divide(start);
443}
444return n;
445}
446/* finds a generator mod p */
447public static BigInteger getGen(BigInteger p, BigInteger q,
448Random r)
449{
450BigInteger h = new BigInteger(p.bitLength(), r); h = h.mod(p);
451return h.modPow((p.subtract(one)).divide(q), p);
452}
453public static void main (String[] args) throws java.lang.Exception
454{
455Random randObj = new Random();
456/* establish the global public key components */
457BigInteger p = getNextPrime("10600"); /* approximate prime */ BigInteger q = findQ(p.subtract(one));
458BigInteger g = getGen(p,q,randObj);
459/* public key components */
460System.out.println("simulation of Digital Signature Algorithm");
461System.out.println("global public key components are:"); System.out.println("p is: " + p);
462System.out.println("q is: " + q); System.out.println("g is: " + g);
463/* find the private key */
464BigInteger x = new BigInteger(q.bitLength(), randObj); x = x.mod(q);
465/* corresponding public key */ BigInteger y = g.modPow(x,p);
466/* random value message */
467BigInteger k = new BigInteger(q.bitLength(), randObj); k = k.mod(q);
468/* randomly generated hash value and digital signature */ BigInteger r = (g.modPow(k,p)).mod(q);
469BigInteger hashVal = new BigInteger(p.bitLength(), randObj); BigInteger kInv = k.modInverse(q);
470BigInteger s = kInv.multiply(hashVal.add(x.multiply(r))); s = s.mod(q);
471/* secret information */ System.out.println("secret information are:"); 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);
472System.out.println("generating digital signature:"); System.out.println("r is : " + r); System.out.println("s is : " + s);
473/* verify the digital signature */ BigInteger w = s.modInverse(q);
474BigInteger u1 = (hashVal.multiply(w)).mod(q); BigInteger u2 = (r.multiply(w)).mod(q);
475BigInteger v = (g.modPow(u1,p)).multiply(y.modPow(u2,p)); v = (v.mod(p)).mod(q);
476System.out.println("verifying digital signature (checkpoints):"); System.out.println("w is : " + w);
477System.out.println("u1 is : " + u1); System.out.println("u2 is : " + u2); System.out.println("v is : " + v); if (v.equals(r))
478{
479System.out.println("success: digital signature is verified! " + r);
480}
481else
482{
483System.out.println("error: incorrect digital signature");
484}
485}
486}
487
488
489
490
491//DES Cipher
492import javax.swing.*;
493import java.security.SecureRandom;
494import javax.crypto.Cipher;
495import javax.crypto.KeyGenerator;
496import javax.crypto.SecretKey;
497import javax.crypto.spec.SecretKeySpec;
498import java.util.Random ;
499import java.util.Scanner;
500public class DES1 {
501 byte[] skey = new byte[1000];
502 String skeyString;
503 static byte[] raw;
504
505 String inputMessage,encryptedData,decryptedMessage;
506 public DES1() {
507 try {
508 generateSymmetricKey();
509 Scanner sc=new Scanner(System.in);
510 System.out.println("Enter message to encrypt");
511 inputMessage=sc.next();
512 byte[] ibyte = inputMessage.getBytes();
513 byte[] ebyte=encrypt(raw, ibyte);
514 String encryptedData = new String(ebyte);
515 System.out.println("Encrypted message "+encryptedData);
516 byte[] dbyte= decrypt(raw,ebyte);
517 String decryptedMessage = new String(dbyte);
518 System.out.println("Decrypted message "+decryptedMessage);
519 }
520 catch(Exception e) {
521 System.out.println(e);
522 }
523 }
524 void generateSymmetricKey() {
525 try {
526 Random r = new Random();
527 int num = r.nextInt(10000);
528 String knum = String.valueOf(num);
529 byte[] knumb = knum.getBytes();
530 skey=getRawKey(knumb);
531 skeyString = new String(skey);
532 }
533 catch(Exception e) {
534 System.out.println(e);
535 }
536 }
537 private static byte[] getRawKey(byte[] seed) throws Exception {
538 KeyGenerator kgen = KeyGenerator.getInstance("DES");
539 SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
540 sr.setSeed(seed);
541 kgen.init(56, sr);
542 SecretKey skey = kgen.generateKey();
543 raw = skey.getEncoded();
544 return raw;
545 }
546 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
547 SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
548 Cipher cipher = Cipher.getInstance("DES");
549 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
550 byte[] encrypted = cipher.doFinal(clear);
551 return encrypted;
552 }
553 private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
554 SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
555 Cipher cipher = Cipher.getInstance("DES");
556
557 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
558 byte[] decrypted = cipher.doFinal(encrypted);
559 return decrypted;
560 }
561 public static void main(String args[]) {
562 DES1 des = new DES1();
563 }
564}