· 6 years ago · Oct 06, 2019, 12:40 PM
1Prac1:1. Write programs to implement the following Substitution Cipher Techniques:
2
31) Caesar Cipher
4
5
6import java.util.Scanner;
7public class CaesarCipher2
8 {
9public static void main(String[] args)
10{
11System.out.println("Enter 1 for encryption or 2 for decryption:");
12Scanner input=new Scanner(System.in);
13int operation=input.nextInt();
14System.out.println("Enter the key value in integer:");
15int key=input.nextInt();
16input.nextLine();
17System.out.println("Enter the string:");
18String inputString=input.nextLine();
19if(operation==1){
20System.out.println(encrypt(key,inputString));
21}else if(operation==2){
22System.out.println(decrypt(key, inputString));
23}else{
24System.out.println("Invalid input!!");
25}
26}
27
28public static String encrypt(int key, String input){
29StringBuilder sb=new StringBuilder();
30int charCode=0;
31for(int i=0;i<input.length();i++){
32charCode=input.charAt(i)+key;
33sb=sb.append(Character.toString((char)charCode));
34charCode=0;
35}
36return sb.toString();
37}
38
39public static String decrypt(int key, String input){
40StringBuilder sb=new StringBuilder();
41int charCode=0;
42for(int i=0;i<input.length();i++){
43charCode=input.charAt(i)-key;
44sb=sb.append(Character.toString((char)charCode));
45charCode=0;
46}
47return sb.toString();
48}
49}
50
51
522) Monoalphabetic Cipher
53Code:-
54
55import java.util.Scanner;
56public class MonoalphabeticCipher
57{
58 public static char p[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
59 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
60 'w', 'x', 'y', 'z' };
61 public static char ch[] = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
62 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c',
63 'v', 'b', 'n', 'M' };
64 public static String doEncryption(String s)
65 {
66 char c[] = new char[(s.length())];
67 for (int i = 0; i < s.length(); i++)
68 {
69 for (int j = 0; j < 26; j++)
70 {
71 if (p[j] == s.charAt(i))
72 {
73 c[i] = ch[j];
74 break;
75 }
76 }
77 }
78 return (new String(c));
79 }
80 public static String doDecryption(String s)
81 {
82 char c[] = new char[(s.length())];
83 for (int i = 0; i < s.length(); i++)
84 {
85 for (int j = 0; j < 26; j++)
86 {
87 if (ch[j] == s.charAt(i))
88 {
89 c[i] = p[j];
90 break;
91 } } }
92 return (new String(c));
93 }
94 public static void main(String args[])
95 {
96 String en;
97 Scanner sc = new Scanner(System.in);
98 System.out.println("Enter 1 for encryption or 2 for decryption:");
99 int operation=sc.nextInt();
100 System.out.println("Enter the message: ");
101 en = sc.next();
102 if(operation==1)
103 {
104 System.out.println("Encrypted message: " + doEncryption(en));
105 }
106 else if(operation==2)
107 {
108 System.out.println("Decrypted message: " + doDecryption(en));
109 }
110 else
111 {
112 System.out.println("Invalid input");
113 }
114 sc.close(); }}
115
116
117
118
119
120Prac2: AIM: Write programs to implement the following Substitution Cipher Techniques:
121Code for 1) Vernam Cipher-
122import java.lang.Math;
123public class xor {
124 public static void main(String args[]) {
125 // This would be the text we encrypt (in this case "hello")
126 // We convert it to a character array
127 String text = new String("hello");
128 char[] arText = text.toCharArray();
129 // This would be our vernam cipher (should be same length as our text)
130 // Here we use the same letters, but theoretically should be random
131 // characters generated on the fly. USE RANDOM LETTERS!
132 String cipher = new String("XYZHG");
133 char[] arCipher = cipher.toCharArray();
134 // Array to hold our encryption (again same length)
135 char[] encoded = new char[5];
136 // Encrypt the text by using XOR (exclusive OR) each character
137 // of our text against cipher.
138 System.out.println("Encoded " + text + " to be... ");
139 for (int i = 0; i < arText.length; i++) {
140 encoded[i] = (char) (arText[i] ^ arCipher[i]);
141 System.out.print(encoded[i]);
142 }
143 System.out.println("\nDecoded to be... ");
144 // Run through the encrypted text and against the cipher again
145 // This decrypts the text.
146 for (int i = 0; i < encoded.length; i++) {
147 char temp = (char) (encoded[i] ^ arCipher[i]);
148 System.out.print(temp);
149 }
150 }
151}
152
153
154Prac4 : AIM:- Write program to encrypt and decrypt strings using
155- DES Algorithm
156- AES Algorithm
157
1581) CODE for DES:
159import java.util.Scanner;
160import java.security.InvalidKeyException;
161import java.security.NoSuchAlgorithmException;
162
163import javax.crypto.BadPaddingException;
164import javax.crypto.Cipher;
165import javax.crypto.IllegalBlockSizeException;
166import javax.crypto.KeyGenerator;
167import javax.crypto.NoSuchPaddingException;
168import javax.crypto.SecretKey;
169
170
171public class DESEncryption
172{
173 public static void main(String[] args)
174 {
175 try
176 {
177 Scanner input = new Scanner(System.in);
178 System.out.println("Enter the String: ");
179 String inputString = input.nextLine();
180
181 KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
182 SecretKey myDesKey = keygenerator.generateKey();
183 Cipher desCipher;
184
185 desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
186
187 desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
188 byte[] text=inputString.getBytes();
189 System.out.println("Text [Byte Format] : "+ text);
190 System.out.println("Text : "+new String(text));
191 byte[] textEncrypted=desCipher.doFinal(text);
192
193 System.out.println("Text Encrypted : " + new String(textEncrypted));
194 desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
195 byte[] textDecrypted=desCipher.doFinal(textEncrypted);
196
197 System.out.println("Text Decrypted : " + new String(textDecrypted));
198
199 }
200 catch(NoSuchAlgorithmException e){
201 e.printStackTrace();
202 }
203 catch(NoSuchPaddingException e){
204 e.printStackTrace();
205 }
206 catch(InvalidKeyException e){
207 e.printStackTrace();
208 }
209 catch(IllegalBlockSizeException e){
210 e.printStackTrace();
211 }
212 catch(BadPaddingException e){
213 e.printStackTrace();
214 }
215 }
216}
217
218
2192) CODE for AES:
220import java.util.Scanner;
221import javax.crypto.Cipher;
222import javax.crypto.KeyGenerator;
223import javax.crypto.SecretKey;
224import javax.xml.bind.DatatypeConverter;
225
226public class AESEncryption
227{
228 public static void main(String[] args)throws Exception
229 {
230 Scanner input = new Scanner(System.in);
231 System.out.println("Enter theString : ");
232 String plainText = input.nextLine();
233
234 SecretKey secKey = getSecretEncryptionKey();
235 byte[] cipherText = encryptText(plainText, secKey);
236 String decryptedText = decryptText(cipherText, secKey);
237
238 System.out.println("Original Text :" +plainText);
239 System.out.println("AES Key(Hex Form) :"+bytesToHex(secKey.getEncoded()));
240 System.out.println("Encrypted Text(Hex Form) :"+bytesToHex(cipherText));
241 System.out.println("DEcrypted Text : "+decryptedText);
242 }
243
244 public static SecretKey getSecretEncryptionKey() throws Exception{
245 KeyGenerator generator = KeyGenerator.getInstance("AES");
246 generator.init(128);
247 SecretKey secKey = generator.generateKey();
248 return secKey;
249 }
250
251 public static byte[] encryptText(String plainText, SecretKey secKey)
252 throws Exception{
253 Cipher aesCipher = Cipher.getInstance("AES");
254 aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
255 byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
256 return byteCipherText;
257 }
258
259 public static String decryptText(byte[] byteCipherText, SecretKey secKey)
260 throws Exception{
261 Cipher aesCipher=Cipher.getInstance("AES");
262 aesCipher.init(Cipher.DECRYPT_MODE, secKey);
263 byte[] bytePlainText=aesCipher.doFinal(byteCipherText);
264 return new String(bytePlainText);
265 }
266
267 public static String bytesToHex(byte[] hash){
268 return DatatypeConverter.printHexBinary(hash);
269 }
270}
271
272Prac 6 : Aim:-
273Write a program to implement the Diffie-Hellman Key Agreement algorithm to generate symmetric keys.
274
275Algorithm:-
276Step 1 : Choose two prime numbers g(primitive root of p) and p.
277Step 2 : Alice selects a secret no(a) and computes ga mod p , let’s call it A. Alice sends A to Bob.
278Step 3 : Bob selects a secret no(b) and computes gb mod p, let’s call it B. Bob sends B to Alice.
279Step 4 : Alice computes S_A = Ba mod p
280Step 5 : Bob computes S_B = Ab mod p
281Step 6 : If S_A=S_B then Alice and Bob can agree for future communication.
282
283CODE:-
284import java.util.*;
285class Diffie_Hellman
286{
287 public static void main(String args[])
288 {
289 Scanner sc=new Scanner(System.in);
290 System.out.println("Enter modulo(p)");
291 int p=sc.nextInt();
292 System.out.println("Enter primitive root of "+p);
293 int g=sc.nextInt();
294 System.out.println("Choose 1st secret no(Alice)");
295 int a=sc.nextInt();
296 System.out.println("Choose 2nd secret no(BOB)");
297 int b=sc.nextInt();
298
299 int A = (int)Math.pow(g,a)%p;
300 int B = (int)Math.pow(g,b)%p;
301
302 int S_A = (int)Math.pow(B,a)%p;
303 int S_B =(int)Math.pow(A,b)%p;
304
305 if(S_A==S_B)
306 {
307 System.out.println("ALice and Bob can communicate with each other!!!");
308 System.out.println("They share a secret no = "+S_A);
309 }
310
311 else
312 {
313 System.out.println("ALice and Bob cannot communicate with each other!!!");
314 }
315 }
316}
317
318
319Prac7 : AIM:- Write a program to implement the MD5 algorithm compute the message digest.
320
321CODE:-
322import java.math.BigInteger;
323import java.security.MessageDigest;
324import java.security.NoSuchAlgorithmException;
325public class JavaMD5Hash {
326 public static void main(String[] args) {
327 System.out.println("For null " + md5(""));
328 System.out.println("For simple text "+ md5("This is my text"));
329 System.out.println("For simple numbers " + md5("12345"));
330 }
331 public static String md5(String input) {
332 String md5 = null;
333 if(null == input) return null;
334 try {
335 //Create MessageDigest object for MD5
336 MessageDigest digest = MessageDigest.getInstance("MD5");
337 //Update input string in message digest
338 digest.update(input.getBytes(), 0, input.length());
339 //Converts message digest value in base 16 (hex)
340 md5 = new BigInteger(1, digest.digest()).toString(16);
341 }
342 catch (NoSuchAlgorithmException e) {
343 e.printStackTrace();
344 }
345 return md5;
346 }
347}
348
349
350Prac8 : AIM:-
351Write a program to calculate HMAC-SHA1 Signature
352
353CODE:- HmacSha1Signature.java
354
355import java.security.InvalidKeyException;
356import java.security.NoSuchAlgorithmException;
357import java.security.SignatureException;
358import java.util.Formatter;
359
360import javax.crypto.Mac;
361import javax.crypto.spec.SecretKeySpec;
362
363
364public class HmacSha1Signature {
365 private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
366
367 private static String toHexString(byte[] bytes) {
368 Formatter formatter = new Formatter();
369
370 for (byte b : bytes) {
371 formatter.format("%02x", b);
372 }
373
374 return formatter.toString();
375 }
376
377 public static String calculateRFC2104HMAC(String data, String key)
378 throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
379 {
380 SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
381 Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
382 mac.init(signingKey);
383 return toHexString(mac.doFinal(data.getBytes()));
384 }
385
386 public static void main(String[] args) throws Exception {
387 String hmac = calculateRFC2104HMAC("data", "key");
388
389 System.out.println(hmac);
390 assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
391 }
392}