· 6 years ago · Oct 04, 2019, 12:00 PM
1Practical 1
2
3Aim:-Write programs to implement the following Substitution Cipher Techniques:
4- Caesar Cipher
5- Monoalphabetic Cipher
6
7
8 - Caesar Cipher
9
10CODE:-
11
12import java.util.Scanner;
13public class CaesarCipher2
14 {
15public static void main(String[] args)
16{
17System.out.println("Enter 1 for encryption or 2 for decryption:");
18Scanner input=new Scanner(System.in);
19int operation=input.nextInt();
20System.out.println("Enter the key value in integer:");
21int key=input.nextInt();
22input.nextLine();
23System.out.println("Enter the string:");
24String inputString=input.nextLine();
25if(operation==1){
26System.out.println(encrypt(key,inputString));
27}else if(operation==2){
28System.out.println(decrypt(key, inputString));
29}else{
30System.out.println("Invalid input!!");
31}
32}
33
34public static String encrypt(int key, String input){
35StringBuilder sb=new StringBuilder();
36int charCode=0;
37for(int i=0;i<input.length();i++){
38charCode=input.charAt(i)+key;
39sb=sb.append(Character.toString((char)charCode));
40charCode=0;
41}
42return sb.toString();
43}
44
45public static String decrypt(int key, String input){
46StringBuilder sb=new StringBuilder();
47int charCode=0;
48for(int i=0;i<input.length();i++){
49charCode=input.charAt(i)-key;
50sb=sb.append(Character.toString((char)charCode));
51charCode=0;
52}
53return sb.toString();
54}
55}
56
57
58- Monoalphabetic Cipher
59Code:-
60
61import java.util.Scanner;
62public class MonoalphabeticCipher
63{
64 public static char p[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
65 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
66 'w', 'x', 'y', 'z' };
67 public static char ch[] = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
68 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c',
69 'v', 'b', 'n', 'M' };
70 public static String doEncryption(String s)
71 {
72 char c[] = new char[(s.length())];
73 for (int i = 0; i < s.length(); i++)
74 {
75 for (int j = 0; j < 26; j++)
76 {
77 if (p[j] == s.charAt(i))
78 {
79 c[i] = ch[j];
80 break;
81 }
82 }
83 }
84 return (new String(c));
85 }
86 public static String doDecryption(String s)
87 {
88 char c[] = new char[(s.length())];
89 for (int i = 0; i < s.length(); i++)
90 {
91 for (int j = 0; j < 26; j++)
92 {
93 if (ch[j] == s.charAt(i))
94 {
95 c[i] = p[j];
96 break;
97 } } }
98 return (new String(c));
99 }
100 public static void main(String args[])
101 {
102 String en;
103 Scanner sc = new Scanner(System.in);
104 System.out.println("Enter 1 for encryption or 2 for decryption:");
105 int operation=sc.nextInt();
106 System.out.println("Enter the message: ");
107 en = sc.next();
108 if(operation==1)
109 {
110 System.out.println("Encrypted message: " + doEncryption(en));
111 }
112 else if(operation==2)
113 {
114 System.out.println("Decrypted message: " + doDecryption(en));
115 }
116 else
117 {
118 System.out.println("Invalid input");
119 }
120 sc.close(); }}
121
122
123Practical 2
124
125Aim:-Write programs to implement the following Substitution Cipher Techniques:
126- Vernam Cipher
127- Playfair Cipher
128
129Code for Vernam Cipher-
130import java.lang.Math;
131public class xor {
132 public static void main(String args[]) {
133 // This would be the text we encrypt (in this case "hello")
134 // We convert it to a character array
135 String text = new String("hello");
136 char[] arText = text.toCharArray();
137 // This would be our vernam cipher (should be same length as our text)
138 // Here we use the same letters, but theoretically should be random
139 // characters generated on the fly. USE RANDOM LETTERS!
140 String cipher = new String("XYZHG");
141 char[] arCipher = cipher.toCharArray();
142 // Array to hold our encryption (again same length)
143 char[] encoded = new char[5];
144 // Encrypt the text by using XOR (exclusive OR) each character
145 // of our text against cipher.
146 System.out.println("Encoded " + text + " to be... ");
147 for (int i = 0; i < arText.length; i++) {
148 encoded[i] = (char) (arText[i] ^ arCipher[i]);
149 System.out.print(encoded[i]);
150 }
151 System.out.println("\nDecoded to be... ");
152 // Run through the encrypted text and against the cipher again
153 // This decrypts the text.
154 for (int i = 0; i < encoded.length; i++) {
155 char temp = (char) (encoded[i] ^ arCipher[i]);
156 System.out.print(temp);
157 }
158 }
159}
160
161
162
163Play fair cipher
164
165
166import java.util.Scanner;
167
168public class PlayfairCipherEncryption
169{
170 private String KeyWord = new String();
171 private String Key = new String();
172 private char matrix_arr[][] = new char[5][5];
173
174 public void setKey(String k)
175 {
176 String K_adjust = new String();
177 boolean flag = false;
178 K_adjust = K_adjust + k.charAt(0);
179 for (int i = 1; i < k.length(); i++)
180 {
181 for (int j = 0; j < K_adjust.length(); j++)
182 {
183 if (k.charAt(i) == K_adjust.charAt(j))
184 {
185 flag = true;
186 }
187 }
188 if (flag == false)
189 K_adjust = K_adjust + k.charAt(i);
190 flag = false;
191 }
192 KeyWord = K_adjust;
193 }
194
195 public void KeyGen()
196 {
197 boolean flag = true;
198 char current;
199 Key = KeyWord;
200 for (int i = 0; i < 26; i++)
201 {
202 current = (char) (i + 97);
203 if (current == 'j')
204 continue;
205 for (int j = 0; j < KeyWord.length(); j++)
206 {
207 if (current == KeyWord.charAt(j))
208 {
209 flag = false;
210 break;
211 }
212 }
213 if (flag)
214 Key = Key + current;
215 flag = true;
216 }
217 System.out.println(Key);
218 matrix();
219 }
220
221 private void matrix()
222 {
223 int counter = 0;
224 for (int i = 0; i < 5; i++)
225 {
226 for (int j = 0; j < 5; j++)
227 {
228 matrix_arr[i][j] = Key.charAt(counter);
229 System.out.print(matrix_arr[i][j] + " ");
230 counter++;
231 }
232 System.out.println();
233 }
234 }
235
236 private String format(String old_text)
237 {
238 int i = 0;
239 int len = 0;
240 String text = new String();
241 len = old_text.length();
242 for (int tmp = 0; tmp < len; tmp++)
243 {
244 if (old_text.charAt(tmp) == 'j')
245 {
246 text = text + 'i';
247 }
248 else
249 text = text + old_text.charAt(tmp);
250 }
251 len = text.length();
252 for (i = 0; i < len; i = i + 2)
253 {
254 if (text.charAt(i + 1) == text.charAt(i))
255 {
256 text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
257 }
258 }
259 return text;
260 }
261
262 private String[] Divid2Pairs(String new_string)
263 {
264 String Original = format(new_string);
265 int size = Original.length();
266 if (size % 2 != 0)
267 {
268 size++;
269 Original = Original + 'x';
270 }
271 String x[] = new String[size / 2];
272 int counter = 0;
273 for (int i = 0; i < size / 2; i++)
274 {
275 x[i] = Original.substring(counter, counter + 2);
276 counter = counter + 2;
277 }
278 return x;
279 }
280
281 public int[] GetDiminsions(char letter)
282 {
283 int[] key = new int[2];
284 if (letter == 'j')
285 letter = 'i';
286 for (int i = 0; i < 5; i++)
287 {
288 for (int j = 0; j < 5; j++)
289 {
290 if (matrix_arr[i][j] == letter)
291 {
292 key[0] = i;
293 key[1] = j;
294 break;
295 }
296 }
297 }
298 return key;
299 }
300
301 public String encryptMessage(String Source)
302 {
303 String src_arr[] = Divid2Pairs(Source);
304 String Code = new String();
305 char one;
306 char two;
307 int part1[] = new int[2];
308 int part2[] = new int[2];
309 for (int i = 0; i < src_arr.length; i++)
310 {
311 one = src_arr[i].charAt(0);
312 two = src_arr[i].charAt(1);
313 part1 = GetDiminsions(one);
314 part2 = GetDiminsions(two);
315 if (part1[0] == part2[0])
316 {
317 if (part1[1] < 4)
318 part1[1]++;
319 else
320 part1[1] = 0;
321 if (part2[1] < 4)
322 part2[1]++;
323 else
324 part2[1] = 0;
325 }
326 else if (part1[1] == part2[1])
327 {
328 if (part1[0] < 4)
329 part1[0]++;
330 else
331 part1[0] = 0;
332 if (part2[0] < 4)
333 part2[0]++;
334 else
335 part2[0] = 0;
336 }
337 else
338 {
339 int temp = part1[1];
340 part1[1] = part2[1];
341 part2[1] = temp;
342 }
343 Code = Code + matrix_arr[part1[0]][part1[1]]
344 + matrix_arr[part2[0]][part2[1]];
345 }
346 return Code;
347 }
348
349 public static void main(String[] args)
350 {
351 PlayfairCipherEncryption x = new PlayfairCipherEncryption();
352 Scanner sc = new Scanner(System.in);
353 System.out.println("Enter a keyword:");
354 String keyword = sc.next();
355 x.setKey(keyword);
356 x.KeyGen();
357 System.out
358 .println("Enter word to encrypt: (Make sure length of message is even)");
359 String key_input = sc.next();
360 if (key_input.length() % 2 == 0)
361 {
362 System.out.println("Encryption: " + x.encryptMessage(key_input));
363 }
364 else
365 {
366 System.out.println("Message length should be even");
367 }
368 sc.close();
369 }
370}
371
372
373Practical 3
374
375Aim:-Write programs to implement the following Transposition Cipher Techniques:
376- Rail Fence Cipher
377- Simple Columnar Technique
378
379
380CODE for Rail Fence Cipher:
381
382
383import java.io.*;
384class RailFence2
385{
386 public static void main(String[] args) throws IOException
387 {
388 String plaintxt,ciphertxt;
389 int i,j,k;
390 System.out.println("Enter the message to be encrypted\n");
391 BufferedReader br=new BufferedReader(new
392 InputStreamReader(System.in));
393 plaintxt=br.readLine();
394 int len=plaintxt.length();
395 String s1="",s2="",temp="";
396 for(i=0;i<len;i++)
397 {
398 if(plaintxt.charAt(i)!=' ')
399 temp=temp+plaintxt.charAt(i);
400 }
401
402 for(i=0;i<temp.length();i++)
403 {
404 if(i%2==0)
405 s1=s1+temp.charAt(i);
406 else
407 s2=s2+temp.charAt(i);
408 }
409 ciphertxt=s1.concat(s2);
410 System.out.println("Ciphertext : "+ciphertxt);
411 plaintxt="";
412 if(ciphertxt.length()%2==0)
413 j=ciphertxt.length()/2;
414 else
415 j=ciphertxt.length()/2+1;
416 k=j;
417
418 for(i=0;i<k;i++)
419 {
420 plaintxt+=ciphertxt.charAt(i);
421 if(j<ciphertxt.length())
422 {plaintxt+=ciphertxt.charAt(j)
423 j++;}
424 }
425 System.out.println("Plaintext: "+plaintxt);
426 }
427}
428
429
430CODE for Simple Columnar Technique:
431
432import java.io.*;
433
434class SCT
435{
436 public static void main(String[] args)throws Exception
437 {
438 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
439 System.out.println("Enter your plain text:");
440 String accept = br.readLine();
441
442 System.out.println("Enter the number of rows:");
443 int r = Integer.parseInt(br.readLine());
444
445 System.out.println("Enter the number of columns:");
446 int c = Integer.parseInt(br.readLine());
447
448 int count = 0;
449
450 char cont[][] = new char[r][c];
451
452 for(int i = 0; i < r; i++)
453 {
454 for(int j = 0; j < c; j++)
455 {
456 if(count >= accept.length())
457 {
458 cont[i][j] = ' ';
459 count++;
460 }
461 else
462 {
463 cont[i][j] = accept.charAt(count);
464 count++;
465 }
466 }
467 }
468 System.out.println("\n Enter the order of columns you want to view them in:");
469
470 int choice[] = new int[c];
471
472 for(int k = 0; k < c; k++)
473 {
474 System.out.println("Choice "+k+"--> ");
475 choice[k] = Integer.parseInt(br.readLine());
476 }
477 System.out.println("\n Cipher text in matrix is -->");
478 String cipher = "";
479
480 for(int j = 0; j < c; j++)
481 {
482 int k = choice[j];
483 for(int i = 0; i < r; i++)
484 {
485 cipher += cont[i][k];
486 }
487 }
488 cipher = cipher.trim();
489 System.out.println(cipher);
490 }
491}
492
493
494Practical 4
495
496Aim:-Write program to encrypt and decrypt strings using
497- DES Algorithm
498- AES Algorithm
499
500CODE for DES:
501
502
503import java.util.Scanner;
504import java.security.InvalidKeyException;
505import java.security.NoSuchAlgorithmException;
506
507import javax.crypto.BadPaddingException;
508import javax.crypto.Cipher;
509import javax.crypto.IllegalBlockSizeException;
510import javax.crypto.KeyGenerator;
511import javax.crypto.NoSuchPaddingException;
512import javax.crypto.SecretKey;
513
514
515public class DESEncryption
516{
517 public static void main(String[] args)
518 {
519 try
520 {
521 Scanner input = new Scanner(System.in);
522 System.out.println("Enter the String: ");
523 String inputString = input.nextLine();
524
525 KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
526 SecretKey myDesKey = keygenerator.generateKey();
527 Cipher desCipher;
528
529 desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
530
531 desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
532 byte[] text=inputString.getBytes();
533 System.out.println("Text [Byte Format] : "+ text);
534 System.out.println("Text : "+new String(text));
535 byte[] textEncrypted=desCipher.doFinal(text);
536
537 System.out.println("Text Encrypted : " + new String(textEncrypted));
538 desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
539 byte[] textDecrypted=desCipher.doFinal(textEncrypted);
540
541 System.out.println("Text Decrypted : " + new String(textDecrypted));
542
543 }
544 catch(NoSuchAlgorithmException e){
545 e.printStackTrace();
546 }
547 catch(NoSuchPaddingException e){
548 e.printStackTrace();
549 }
550 catch(InvalidKeyException e){
551 e.printStackTrace();
552 }
553 catch(IllegalBlockSizeException e){
554 e.printStackTrace();
555 }
556 catch(BadPaddingException e){
557 e.printStackTrace();
558 }
559 }
560}
561
562
563CODE for AES:
564
565
566import java.util.Scanner;
567import javax.crypto.Cipher;
568import javax.crypto.KeyGenerator;
569import javax.crypto.SecretKey;
570import javax.xml.bind.DatatypeConverter;
571
572public class AESEncryption
573{
574 public static void main(String[] args)throws Exception
575 {
576 Scanner input = new Scanner(System.in);
577 System.out.println("Enter theString : ");
578 String plainText = input.nextLine();
579
580 SecretKey secKey = getSecretEncryptionKey();
581 byte[] cipherText = encryptText(plainText, secKey);
582 String decryptedText = decryptText(cipherText, secKey);
583
584 System.out.println("Original Text :" +plainText);
585 System.out.println("AES Key(Hex Form) :"+bytesToHex(secKey.getEncoded()));
586 System.out.println("Encrypted Text(Hex Form) :"+bytesToHex(cipherText));
587 System.out.println("DEcrypted Text : "+decryptedText);
588 }
589
590 public static SecretKey getSecretEncryptionKey() throws Exception{
591 KeyGenerator generator = KeyGenerator.getInstance("AES");
592 generator.init(128);
593 SecretKey secKey = generator.generateKey();
594 return secKey;
595 }
596
597 public static byte[] encryptText(String plainText, SecretKey secKey)
598 throws Exception{
599 Cipher aesCipher = Cipher.getInstance("AES");
600 aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
601 byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
602 return byteCipherText;
603 }
604
605 public static String decryptText(byte[] byteCipherText, SecretKey secKey)
606 throws Exception{
607 Cipher aesCipher=Cipher.getInstance("AES");
608 aesCipher.init(Cipher.DECRYPT_MODE, secKey);
609 byte[] bytePlainText=aesCipher.doFinal(byteCipherText);
610 return new String(bytePlainText);
611 }
612
613 public static String bytesToHex(byte[] hash){
614 return DatatypeConverter.printHexBinary(hash);
615 }
616}
617
618
619Practical 5
620
621Aim:-Write a program to implement RSA algorithm to perform encryption / decryption of a given string.
622
623 Code:
624
625import java.util.Scanner;
626import java.security.KeyPair;
627import java.security.KeyPairGenerator;
628import java.security.NoSuchAlgorithmException;
629import java.security.PrivateKey;
630import java.security.PublicKey;
631
632import javax.crypto.Cipher;
633
634public class Sample {
635
636 public static void main(String [] args) throws Exception {
637 // generate public and private keys
638 KeyPair keyPair = buildKeyPair();
639 PublicKey pubKey = keyPair.getPublic();
640 PrivateKey privateKey = keyPair.getPrivate();
641
642 Scanner sc = new Scanner(System.in);
643 System.out.println("Enter the plain text:");
644 String plaintext = sc.next();
645
646 // encrypt the message
647 byte [] encrypted = encrypt(privateKey, plaintext);
648 System.out.println(new String(encrypted)); // <<encrypted message>>
649
650 // decrypt the message
651 byte[] secret = decrypt(pubKey, encrypted);
652 System.out.println(new String(secret)); // This is a secret message
653 }
654
655 public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {
656 final int keySize = 2048;
657 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
658 keyPairGenerator.initialize(keySize);
659 return keyPairGenerator.genKeyPair();
660 }
661
662 public static byte[] encrypt(PrivateKey privateKey, String message) throws Exception {
663 Cipher cipher = Cipher.getInstance("RSA");
664 cipher.init(Cipher.ENCRYPT_MODE, privateKey);
665
666 return cipher.doFinal(message.getBytes());
667 }
668
669 public static byte[] decrypt(PublicKey publicKey, byte [] encrypted) throws Exception {
670 Cipher cipher = Cipher.getInstance("RSA");
671 cipher.init(Cipher.DECRYPT_MODE, publicKey);
672
673 return cipher.doFinal(encrypted);
674 }
675}
676
677
678Practical 6
679
680Aim:-Write a program to implement the Diffie-Hellman Key Agreement algorithm to generate symmetric keys.
681
682CODE:-
683import java.util.*;
684class Diffie_Hellman
685{
686 public static void main(String args[])
687 {
688 Scanner sc=new Scanner(System.in);
689 System.out.println("Enter modulo(p)");
690 int p=sc.nextInt();
691 System.out.println("Enter primitive root of "+p);
692 int g=sc.nextInt();
693 System.out.println("Choose 1st secret no(Alice)");
694 int a=sc.nextInt();
695 System.out.println("Choose 2nd secret no(BOB)");
696 int b=sc.nextInt();
697
698 int A = (int)Math.pow(g,a)%p;
699 int B = (int)Math.pow(g,b)%p;
700
701 int S_A = (int)Math.pow(B,a)%p;
702 int S_B =(int)Math.pow(A,b)%p;
703
704 if(S_A==S_B)
705 {
706 System.out.println("ALice and Bob can communicate with each other!!!");
707 System.out.println("They share a secret no = "+S_A);
708 }
709
710 else
711 {
712 System.out.println("ALice and Bob cannot communicate with each other!!!");
713 }
714 }
715}
716
717
718Practical 7
719
720Aim:-Write a program to implement the MD5 algorithm compute the message digest.
721
722CODE:-
723import java.math.BigInteger;
724import java.security.MessageDigest;
725import java.security.NoSuchAlgorithmException;
726public class JavaMD5Hash {
727 public static void main(String[] args) {
728 System.out.println("For null " + md5(""));
729 System.out.println("For simple text "+ md5("This is my text"));
730 System.out.println("For simple numbers " + md5("12345"));
731 }
732 public static String md5(String input) {
733 String md5 = null;
734 if(null == input) return null;
735 try {
736 //Create MessageDigest object for MD5
737 MessageDigest digest = MessageDigest.getInstance("MD5");
738 //Update input string in message digest
739 digest.update(input.getBytes(), 0, input.length());
740 //Converts message digest value in base 16 (hex)
741 md5 = new BigInteger(1, digest.digest()).toString(16);
742 }
743 catch (NoSuchAlgorithmException e) {
744 e.printStackTrace();
745 }
746 return md5;
747 }
748}
749
750
751Practical 8
752
753Aim:-Write a program to calculate HMAC-SHA1 Signature
754
755CODE:- HmacSha1Signature.java
756
757import java.security.InvalidKeyException;
758import java.security.NoSuchAlgorithmException;
759import java.security.SignatureException;
760import java.util.Formatter;
761
762import javax.crypto.Mac;
763import javax.crypto.spec.SecretKeySpec;
764
765
766public class HmacSha1Signature {
767 private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
768
769 private static String toHexString(byte[] bytes) {
770 Formatter formatter = new Formatter();
771
772 for (byte b : bytes) {
773 formatter.format("%02x", b);
774 }
775
776 return formatter.toString();
777 }
778
779 public static String calculateRFC2104HMAC(String data, String key)
780 throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
781 {
782 SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
783 Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
784 mac.init(signingKey);
785 return toHexString(mac.doFinal(data.getBytes()));
786 }
787
788 public static void main(String[] args) throws Exception {
789 String hmac = calculateRFC2104HMAC("data", "key");
790
791 System.out.println(hmac);
792 assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
793 }
794}
795
796
797
798Practical 9
799
800Aim:-Write a program to implement SSL.
801
802CODE 7.1 (Using SSL connection)
803import java.util.Properties;
804import javax.mail.Message;
805import javax.mail.MessagingException;
806import javax.mail.PasswordAuthentication;
807import javax.mail.Session;
808import javax.mail.Transport;
809import javax.mail.internet.InternetAddress;
810import javax.mail.internet.MimeMessage;
811public class SendMailSSL
812 {
813public static void main(String[] args) {
814Properties props = new Properties();
815props.put("mail.smtp.host", "smtp.gmail.com");
816props.put("mail.smtp.socketFactory.port", "465");
817props.put("mail.smtp.socketFactory.class",
818"javax.net.ssl.SSLSocketFactory");
819props.put("mail.smtp.auth", "true");
820props.put("mail.smtp.port", "465");
821Session session = Session.getDefaultInstance(props,
822new javax.mail.Authenticator() {
823protected PasswordAuthentication
824getPasswordAuthentication() {
825return new
826PasswordAuthentication("sender@gmail.com","password");
827}
828});
829try {
830Message message = new MimeMessage(session);
831message.setFrom(new InternetAddress("sender@gmail.com"));
832message.setRecipients(Message.RecipientType.TO,
833InternetAddress.parse("receiver@gmail.com"));
834message.setSubject("Testing Subject");
835message.setText("Hi Athu…");
836Transport.send(message);
837System.out.println("Done");
838} catch (MessagingException e) {
839throw new RuntimeException(e);
840}
841}}