· 6 years ago · Oct 01, 2019, 11:00 AM
1
2 ITNS
3Title:Write programs to implement the following Substitution Cipher Techniques: -
4a)Caesar Cipher
5 b)Monoalphabetic Cipher.
6
7a) Caesar Cipher
8
9Program:[Encryption]
10
11import java.util.*;
12class caeser
13{
14 public static void main(String args[])
15 {
16 Scanner sc=new Scanner(System.in);
17 String msg,enc=" ";
18 int key;
19 char ch;
20 System.out.println("Enter msg");
21 msg=sc.next();
22 System.out.println("Enter key");
23 key=sc.nextInt();
24 for(int i=0;i<msg.length();i++)
25 {
26 ch=msg.charAt(i);
27 if(ch>='a' && ch<='z')
28 {
29 ch=(char)(ch+key);
30 if(ch>'z')
31 {
32 ch=(char)(ch-'z'+'a'-1);
33 }
34 enc+=ch;
35 }
36 else if(ch>='A' && ch<='Z')
37 {
38 ch=(char)(ch+key);
39 if(ch>'Z')
40 {
41 ch=(char)(ch-'Z'+'A'-1);
42 }
43 enc+=ch;
44 }
45 else
46 {
47 enc+=ch;
48 }
49 }
50 System.out.println(enc);
51 }
52}
53
54Output:
55
56
57
58
59Program:[Decryption]
60
61import java.util.*;
62class caeserdecrypt
63{
64 public static void main(String args[])
65 {
66 Scanner sc=new Scanner(System.in);
67 String msg,enc=" ";
68 int key;
69 char ch;
70 System.out.println("Enter msg");
71 msg=sc.next();
72 System.out.println("Enter key");
73 key=-sc.nextInt();
74 for(int i=0;i<msg.length();i++)
75 {
76 ch=msg.charAt(i);
77 if(ch>='a' && ch<='z')
78 {
79 ch=(char)(ch+key);
80 if(ch>'z')
81 {
82 ch=(char)(ch-'z'+'a'-1);
83 }
84 enc+=ch;
85 }
86 else if(ch>='A' && ch<='Z')
87 {
88 ch=(char)(ch+key);
89 if(ch>'Z')
90 {
91 ch=(char)(ch-'Z'+'A'-1);
92 }
93 enc+=ch;
94 }
95 else
96 {
97 enc+=ch;
98 }
99 }
100 System.out.println(enc);
101 }
102}
103
104
105Output:
106
107
108
109
110
111
112
113
114
115
116
117a) Monoalphabetic Cipher
118
119Program:
120
121import java.util.*;
122class monoalpha
123{
124 public static void main(String args[])
125 {
126 String msg,encrypt=" ";
127 int len;
128 int ascii,enc,fin=0;
129 char ch;
130 Scanner sc=new Scanner(System.in);
131 System.out.println("Enter msg");
132 msg=sc.next();
133 len=msg.length();
134 for(int i=0;i<msg.length();i++)
135 {
136 ch=msg.charAt(i);
137 ascii=(int)ch;
138 if(ascii>=65 && ascii<=90)
139 {
140 enc=ascii-65;
141 fin=90-enc;
142 encrypt+=(char)(fin);
143 }
144 else if(ascii>=97 && ascii<=122)
145 {
146 enc=ascii-97;
147 fin=122-enc;
148 encrypt+=(char)(fin);
149 }
150 else
151 {
152 encrypt+=(char)(fin);
153 }
154 }
155 System.out.println(encrypt);
156 }
157}
158
159
160
161
162
163
164
165
166Output:
167
168
169
170
171
172Title:Write programs to implement the following Substitution Cipher Techniques: -
173a)Vernam Cipher
174b)Playfair Cipher
175
176a) Vernam Cipher
177
178Program:
179
180import java.util.*;
181class vernam
182{
183public static void main(String args[])
184{
185 String msg,encrypt=" ",key;
186 int ascii,ascii2,en;
187 char ch,ke;
188 Scanner sc=new Scanner(System.in);
189 System.out.println("Enter msg");
190 msg=sc.next();
191 System.out.println("Enter key");
192 key=sc.next();
193 int len=msg.length();
194 for(int i=0;i<len;i++)
195 {
196 ch=msg.charAt(i);
197 ascii=(int)ch;
198 ke=key.charAt(i);
199 ascii2=(int)ke;
200 if(ascii<=90)
201 {
202 ascii=ascii-65;
203 ascii2=ascii2-65;
204 en=ascii+ascii2;
205 if(en>25)
206 {
207 en=en-26;
208 }
209 en=en+65;
210 }
211 else
212 {
213 ascii=ascii-97;
214 ascii2=ascii2-97;
215 en=ascii+ascii2;
216 if(en>25)
217 {
218 en=en-26;
219 }
220 en=en+97;
221 }
222 encrypt+=(char)(en);
223 }
224 System.out.println("Encrypt key"+encrypt);
225}
226}
227
228Output:
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256a) Playfair Cipher
257
258Program:
259
260import java.awt.Point;
261import java.util.Scanner;
262
263public class PFC {
264 private static char[][] charTable;
265 private static Point[] positions;
266
267 public static void main(String[] args) {
268 Scanner sc = new Scanner(System.in);
269
270 String key = prompt("Enter an encryption key (min length 6): ", sc, 6);
271 String txt = prompt("Enter the message: ", sc, 1);
272 String jti = prompt("Replace J with I? y/n: ", sc, 1);
273
274 boolean changeJtoI = jti.equalsIgnoreCase("y");
275
276 createTable(key, changeJtoI);
277
278 String enc = encode(prepareText(txt, changeJtoI));
279
280 System.out.printf("%nEncoded message: %n%s%n", enc);
281 System.out.printf("%nDecoded message: %n%s%n", decode(enc));
282 }
283
284 private static String prompt(String promptText, Scanner sc, int minLen) {
285 String s;
286 do {
287 System.out.print(promptText);
288 s = sc.nextLine().trim();
289 } while (s.length() < minLen);
290 return s;
291 }
292
293 private static String prepareText(String s, boolean changeJtoI) {
294 s = s.toUpperCase().replaceAll("[^A-Z]", "");
295 return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
296 }
297
298 private static void createTable(String key, boolean changeJtoI) {
299 charTable = new char[5][5];
300 positions = new Point[26];
301
302 String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", changeJtoI);
303
304 int len = s.length();
305 for (int i = 0, k = 0; i < len; i++) {
306 char c = s.charAt(i);
307 if (positions[c - 'A'] == null) {
308 charTable[k / 5][k % 5] = c;
309 positions[c - 'A'] = new Point(k % 5, k / 5);
310 k++;
311 }
312 }
313 }
314
315 private static String encode(String s) {
316 StringBuilder sb = new StringBuilder(s);
317
318 for (int i = 0; i < sb.length(); i += 2) {
319
320 if (i == sb.length() - 1)
321 sb.append(sb.length() % 2 == 1 ? 'X' : "");
322
323 else if (sb.charAt(i) == sb.charAt(i + 1))
324 sb.insert(i + 1, 'X');
325 }
326 return codec(sb, 1);
327 }
328
329 private static String decode(String s) {
330 return codec(new StringBuilder(s), 4);
331 }
332
333 private static String codec(StringBuilder text, int direction) {
334 int len = text.length();
335 for (int i = 0; i < len; i += 2) {
336 char a = text.charAt(i);
337 char b = text.charAt(i + 1);
338
339 int row1 = positions[a - 'A'].y;
340 int row2 = positions[b - 'A'].y;
341 int col1 = positions[a - 'A'].x;
342 int col2 = positions[b - 'A'].x;
343
344 if (row1 == row2) {
345 col1 = (col1 + direction) % 5;
346 col2 = (col2 + direction) % 5;
347
348 } else if (col1 == col2) {
349 row1 = (row1 + direction) % 5;
350 row2 = (row2 + direction) % 5;
351
352 } else {
353 int tmp = col1;
354 col1 = col2;
355 col2 = tmp;
356 }
357
358 text.setCharAt(i, charTable[row1][col1]);
359 text.setCharAt(i + 1, charTable[row2][col2]);
360 }
361 return text.toString();
362 }
363}
364
365
366Output:
367
368
369
370
371
372Title:Write programs to implement the following Transposition Cipher Techniques:
373a) Rail Fence Cipher .
374b) Simple Columnar Technique.
375
376a) Rail Fence Cipher.
377
378Program:
379
380import java.util.*;
381class RailFenceBasic{
382 int depth;
383 String Encryption(String plainText,int depth)throws Exception
384 {
385 int r=depth,len=plainText.length();
386 int c=len/depth;
387 char mat[][]=new char[r][c];
388 int k=0;
389
390 String cipherText="";
391
392 for(int i=0;i< c;i++)
393 {
394 for(int j=0;j< r;j++)
395 {
396 if(k!=len)
397 mat[j][i]=plainText.charAt(k++);
398 else
399 mat[j][i]='X';
400 }
401 }
402 for(int i=0;i< r;i++)
403 {
404 for(int j=0;j< c;j++)
405 {
406 cipherText+=mat[i][j];
407 }
408 }
409 return cipherText;
410 }
411
412
413 String Decryption(String cipherText,int depth)throws Exception
414 {
415 int r=depth,len=cipherText.length();
416 int c=len/depth;
417 char mat[][]=new char[r][c];
418 int k=0;
419
420 String plainText="";
421
422
423 for(int i=0;i< r;i++)
424 {
425 for(int j=0;j< c;j++)
426 {
427 mat[i][j]=cipherText.charAt(k++);
428 }
429 }
430 for(int i=0;i< c;i++)
431 {
432 for(int j=0;j< r;j++)
433 {
434 plainText+=mat[j][i];
435 }
436 }
437
438 return plainText;
439 }
440}
441
442class RailFence{
443 public static void main(String args[])throws Exception
444 {
445 RailFenceBasic rf=new RailFenceBasic();
446 Scanner scn=new Scanner(System.in);
447 int depth;
448
449 String plainText,cipherText,decryptedText;
450
451 System.out.println("Enter plain text:");
452 plainText=scn.nextLine();
453
454 System.out.println("Enter depth for Encryption:");
455 depth=scn.nextInt();
456
457 cipherText=rf.Encryption(plainText,depth);
458 System.out.println("Encrypted text is:\n"+cipherText);
459
460 decryptedText=rf.Decryption(cipherText, depth);
461
462 System.out.println("Decrypted text is:\n"+decryptedText);
463
464 }
465}
466
467
468
469Output:
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506a) Simple Columnar Technique.
507
508Program:
509
510import java.io.*;
511class SCT
512{
513 public static void main(String args[])throws Exception
514 {
515 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
516 System.out.println("Enter your plain text");
517 String accept=br.readLine();
518 System.out.println("Enter the no of rows ");
519 int r=Integer.parseInt(br.readLine());
520 System.out.println("Enter the no of cols");
521 int c=Integer.parseInt(br.readLine());
522 int count=0;
523 char cont[][]=new char[r][c];
524 for(int i=0;i<r;i++)
525 {
526 for(int j=0;j<c;j++)
527 {
528 if(count>=accept.length())
529 {
530 cont[i][j]=' ';
531 count++;
532 }
533 else
534 {
535 cont[i][j]=accept.charAt(count);
536 count++;
537 }
538 }
539 }
540 System.out.println("\nEnter the order of cols you want to view them in");
541 int choice[]=new int[c];
542 for(int k=0;k<c;k++)
543 {
544 System.out.println("Choice "+k+"-> ");
545 choice[k]=Integer.parseInt(br.readLine());
546 }
547 System.out.println("\nCipher text in matrix is ->");
548 String cipher="";
549 for(int j=0;j<c;j++)
550 {
551 int k=choice[j];
552 for(int i=0;i<r;i++)
553 {
554 cipher+=cont[i][k];
555 }
556 }
557 cipher=cipher.trim();
558 System.out.println(cipher);
559 }
560}
561
562Output:
563
564
565
566Title:Write a program to implement RSA algorithm to perform encryption / decryption of a given string.
567
568Program:
569
570import java.math.*;
571import java.util.Scanner;
572
573class RSA
574{
575 public static void main(String args[])
576 {
577 Scanner sc=new Scanner(System.in);
578 int p,q,n,z,d=0,e,i;
579 System.out.println("Enter the number to be encrypted and decrypted");
580 int msg=sc.nextInt();
581 double c;
582 BigInteger msgback;
583 System.out.println("Enter 1st prime number p");
584 p=sc.nextInt();
585 System.out.println("Enter 2nd prime number q");
586 q=sc.nextInt();
587
588 n=p*q;
589 z=(p-1)*(q-1);
590 System.out.println("the value of z = "+z);
591
592 for(e=2;e<z;e++)
593 {
594 if(gcd(e,z)==1) // e is for public key exponent
595 {
596 break;
597 }
598 }
599 System.out.println("the value of e = "+e);
600 for(i=0;i<=9;i++)
601 {
602 int x=1+(i*z);
603 if(x%e==0) //d is for private key exponent
604 {
605 d=x/e;
606 break;
607 }
608 }
609 System.out.println("the value of d = "+d);
610 c=(Math.pow(msg,e))%n;
611 System.out.println("Encrypted message is : -");
612 System.out.println(c);
613 //converting int value of n to BigInteger
614 BigInteger N = BigInteger.valueOf(n);
615 //converting float value of c to BigInteger
616 BigInteger C = BigDecimal.valueOf(c).toBigInteger();
617 msgback = (C.pow(d)).mod(N);
618 System.out.println("Derypted message is : -");
619 System.out.println(msgback);
620
621 }
622
623 static int gcd(int e, int z)
624 {
625 if(e==0)
626 return z;
627 else
628 return gcd(z%e,e);
629 }
630}
631
632Output:
633
634
635
636Title:Write a program to implement the Diffie-Hellman Key Agreement algorithm to generate symmetric keys.
637
638Program:
639
640import java.io.*;
641import java.math.BigInteger;
642class Diffie
643{
644 public static void main(String[]args)throws IOException
645 {
646 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
647 System.out.println("Enter prime number (P)':");
648 BigInteger p=new BigInteger(br.readLine());
649 System.out.print("Enter (G):");
650 BigInteger g=new BigInteger(br.readLine());
651 System.out.println("Enter value for a:");
652 BigInteger x=new BigInteger(br.readLine());
653 BigInteger R1=g.modPow(x,p);
654 System.out.println("R1="+R1);
655 System.out.print("Enter value for b:");
656 BigInteger y=new BigInteger(br.readLine());
657 BigInteger R2=g.modPow(y,p);
658 System.out.println("R2="+R2);
659 BigInteger k1=R2.modPow(x,p);
660 System.out.println("Key calculated at Alice's side:"+k1);
661 BigInteger k2=R1.modPow(y,p);
662 System.out.println("Key calculated at Bob's side:"+k2);
663 System.out.println("deffie hellman secret key Encryption has Taken");
664 }
665}
666
667Output:
668
669
670Title: Write a program to implement the MD5 algorithm compute the message digest.
671
672
673public class Md5 {
674
675 private static final int INIT_A = 0x67452301;
676 private static final int INIT_B = (int) 0xEFCDAB89L;
677 private static final int INIT_C = (int) 0x98BADCFEL;
678 private static final int INIT_D = 0x10325476;
679 private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4,
680 11, 16, 23, 6, 10, 15, 21 };
681 private static final int[] TABLE_T = new int[64];
682 static
683 {
684 for (int i = 0; i < 64; i++)
685 TABLE_T[i] = (int) (long) ((1L << 32) * Math.abs(Math.sin(i + 1)));
686 }
687
688 public static byte[] computeMD5(byte[] message)
689 {
690 int messageLenBytes = message.length;
691 int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
692 int totalLen = numBlocks << 6;
693 byte[] paddingBytes = new byte[totalLen - messageLenBytes];
694 paddingBytes[0] = (byte) 0x80;
695 long messageLenBits = (long) messageLenBytes << 3;
696 for (int i = 0; i < 8; i++)
697 {
698 paddingBytes[paddingBytes.length - 8 + i] = (byte) messageLenBits;
699 messageLenBits >>>= 8;
700 }
701 int a = INIT_A;
702 int b = INIT_B;
703 int c = INIT_C;
704 int d = INIT_D;
705 int[] buffer = new int[16];
706 for (int i = 0; i < numBlocks; i++)
707 {
708 int index = i << 6;
709 for (int j = 0; j < 64; j++, index++)
710 buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index]
711 : paddingBytes[index - messageLenBytes]) << 24)
712 | (buffer[j >>> 2] >>> 8);
713 int originalA = a;
714 int originalB = b;
715 int originalC = c;
716 int originalD = d;
717 for (int j = 0; j < 64; j++)
718 {
719 int div16 = j >>> 4;
720 int f = 0;
721 int bufferIndex = j;
722 switch (div16)
723 {
724 case 0:
725 f = (b & c) | (~b & d);
726 break;
727 case 1:
728 f = (b & d) | (c & ~d);
729 bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
730 break;
731 case 2:
732 f = b ^ c ^ d;
733 bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
734 break;
735 case 3:
736 f = c ^ (b | ~d);
737 bufferIndex = (bufferIndex * 7) & 0x0F;
738 break;
739 }
740 int temp = b
741 + Integer.rotateLeft(a + f + buffer[bufferIndex]
742 + TABLE_T[j],
743 SHIFT_AMTS[(div16 << 2) | (j & 3)]);
744 a = d;
745 d = c;
746 c = b;
747 b = temp;
748 }
749 a += originalA;
750 b += originalB;
751 c += originalC;
752 d += originalD;
753 }
754 byte[] md5 = new byte[16];
755 int count = 0;
756 for (int i = 0; i < 4; i++)
757 {
758 int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
759 for (int j = 0; j < 4; j++)
760 {
761 md5[count++] = (byte) n;
762 n >>>= 8;
763 }
764 }
765 return md5;
766 }
767
768 public static String toHexString(byte[] b)
769 {
770 StringBuilder sb = new StringBuilder();
771 for (int i = 0; i < b.length; i++)
772 {
773 sb.append(String.format("%02X", b[i] & 0xFF));
774 }
775 return sb.toString();
776 }
777
778 public static void main(String[] args)
779 {
780 String[] testStrings = { "", "Sanfoundry", "Message Digest",
781 "abcdefghijklmnopqrstuvwxyz" };
782 for (String s : testStrings)
783 System.out.println("0x" + toHexString(computeMD5(s.getBytes()))
784 + " <== \"" + s + "\"");
785 return;
786 }
787
788
789}
790
791
792Output:-
793
794Title: Write a program to calculate HMAC-SHA1 Signature
795
796import java.io.ByteArrayOutputStream;
797import java.io.IOException;
798import java.security.InvalidKeyException;
799import java.security.MessageDigest;
800import java.security.NoSuchAlgorithmException;
801import java.util.Arrays;
802import java.util.Scanner;
803
804public class HMAC {
805
806 public final int BlockSize = 64; // In Bytes { Number of bytes in each block}
807 public final String MessageDigestAlgorithm = "SHA-1";
808
809 public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
810 final Scanner read = new Scanner(System.in);
811 HMAC hmacInstance = new HMAC();
812
813 System.out.println("Enter Message :- ");
814 String message = read.nextLine();
815
816 System.out.println("Enter Key :- ");
817 String key = read.next();
818
819 byte[] MAC = hmacInstance.getHMAC_SHA1(message, key);
820
821 // Print the output
822 for (byte b : MAC) {
823 System.out.print(String.format("%x", b)); // %x is format Specifier for hex
824 }
825 }
826
827 private byte[] getHMAC_SHA1(String message,String secretKey ) {
828
829 //--------------Variables used for HMAC Algorithms---------------//
830
831 // Arrays.copyOf : - Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
832 byte[] msg = Arrays.copyOf(message.getBytes(),512);
833 byte[] ipad = getIpad();
834 byte[] opad = getOpad();
835 //---------------------------------------------------------------//
836
837 //==============Step 1============//
838
839 /* If the key is less then BlockSize, it would be preceded by 0.
840 If the key is greater then BlockSize it would be truncated to the size of BlockSize
841 */
842 byte[] key = Arrays.copyOf(secretKey.getBytes(),BlockSize);
843
844 //=============Step 2============//
845 byte[] s1 = XOR(key, ipad); //
846
847 //=============Step 3============//
848 byte[] appendedS1AndMessage = AppendByteArray(s1,msg);
849
850 //=============Step 4============//
851 byte[] h = Hash(appendedS1AndMessage);
852
853
854 //=============Step 5============//
855 byte[] s2 = XOR(key,opad);
856
857 //=============Step 5============//
858 byte[] appenedS2AndMessage = AppendByteArray(s2,msg);
859
860 //=============Step 7============//
861 byte[] MAC = Hash(appenedS2AndMessage);
862
863 return MAC;
864 }
865
866 private byte[] Hash(byte[] appendedS1AndMessage) {
867 MessageDigest md = null;
868 try {
869 // Uses SHA-1 MD algorithm provided by Java Security APIs.
870 md = MessageDigest.getInstance(MessageDigestAlgorithm);
871 byte[] digest = md.digest(appendedS1AndMessage);
872 return digest;
873 }
874 catch(NoSuchAlgorithmException e) {
875 e.printStackTrace();
876 }
877 return null;
878 }
879
880 private byte[] AppendByteArray(byte[] s1, byte[] message) {
881
882 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
883 try {
884 outputStream.write(s1);
885 outputStream.write(message);
886 } catch (IOException e) {
887 e.printStackTrace();
888 }
889
890 byte c[] = outputStream.toByteArray();
891 return c;
892 }
893
894 private byte[] XOR(byte[] key, byte[] ipad) {
895 byte[] output = new byte[BlockSize];
896 for (int i = 0; i < output.length; i++) {
897 output[i] = (byte) (key[i] ^ ipad[i]);
898 }
899 return output;
900 }
901
902 private byte[] getOpad() {
903 byte[] opad = new byte[BlockSize];
904 for (int i = 0; i < opad.length; i++) {
905 opad[i] = 0x5C;
906 }
907 return opad;
908 }
909
910 private byte[] getIpad() {
911 byte[] ipad = new byte[BlockSize];
912 for (int i = 0; i < ipad.length; i++) {
913 ipad[i] = 0x36;
914 }
915 return ipad;
916 }
917
918}
919Output:-
920
921Title: Configure Windows Firewall to block:
922 - A port
923 - An Program
924 - A website
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953Website:
954
955
956
957
958
959
960
961
962Port: