· 6 years ago · Sep 17, 2019, 02:50 AM
1# Caesar Cipher
2
3def ceasarCipher(string, key):
4 lower = [chr(i) for i in range(97, 123)]
5 upper = [chr(i) for i in range(65, 91)]
6
7 code = ""
8 for i in string:
9 if i.islower():
10 code += lower[(ord(i) - 97 + key) % len(lower)]
11 elif i.isupper():
12 code += upper[(ord(i) - 65 + key) % len(upper)]
13 else:
14 code += i
15 return code
16x = "middle-Outz"
17print(ceasarCipher(x, 2))
18----------------------------
19# Monoalphabetic cipher
20
21def encrypt(text, a):
22 res = ""
23 for i in range(len(text)):
24 char = text[i]
25 if char.isUpper():
26 res += chr((ord(char)+s-65)%26 + 65)
27 else:
28 res += chr((ord(char)+s-97)%26 + 97)
29 return res
30text = "SUPERVISOR"
31S = 6
32print("Cipher Text :",encrypt(text,s))
33----------------------------
34#playFairCipher
35
36#This cipher is only intended to work with lowercase letters
37def playFairCipher(msg, key):
38 keyset = []
39 key = key.replace(" ","") #Removing the blank spaces
40
41 for i in key : #Makes the table according to the message
42 if i not in keyset:
43 if i != "j":
44 keyset.append(i)
45 for i in range(97, 123): #Takes remaining character which were not there in the cipherKey
46 if chr(i) not in keyset:
47 if chr(i) != "j" : #rejecting j, treating j as i (Rule)
48 keyset.append(chr(i))
49
50 keyMatrix = [keyset[i:i+5] for i in range(0,25,5)] #Makes a 5x5 table of where j is not used
51 print("Encryption table :")
52 for row in keyMatrix: #Prints the 5x5 cipherKey table
53 for e in row:
54 print(e, end = "\t")
55 print()
56
57 msg = msg.replace(" ", "") #Removing blankspaces
58 msg = msg.replace("j", "i") #replacing j's with i's because j is treated as i and j is not present in the table
59
60 count = 0
61 code = ""
62 noOfX = 0
63 while count <= (len(msg) - 1): #Loops until the msg ends;
64 if count == len(msg) - 1: #Prevents index out of range
65 break
66 first = msg[count] #Taking 1st character at a time
67 second = msg[count+1] #Taking 2nd Character at a time
68 code, count, noOfX = encrypt(first, second, code, keyMatrix, count, noOfX) #Returns the tuple and multiple assignment happens
69
70 if (len(msg) + noOfX) % 2 != 0: #checks no of X's used in cipher text, which increases the length of cipherText; If incase last character is left to be Decrypted
71 elements = [msg[len(msg) - 1], "x"]
72 code = encrypt(msg[len(msg) - 1], "x", code, keyMatrix) #Returns only cipher text, count and noOfX is not needed in contrary to previous use of Encrypt
73 return code
74
75#encrypt function helps in reducing the redundancy of the code
76def encrypt(first, second, code, keyMatrix, count = None, noOfX = None):
77 if first == second:
78 code += first + "x"
79 if count != None:
80 count += 1
81 if noOfX != None:
82 noOfX += 1
83 else:
84 elements = [first, second]
85 indexes = []
86 for i in elements:
87 for j in range(5):
88 for k in range(5):
89 if i == keyMatrix[j][k]:
90 indexes.append([j, k])
91## print(indexes)
92 if indexes[0][0] == indexes[1][0]: #Checks wheather they are is same row
93 indexes[0][1] = (indexes[0][1] + 1) % 5 #increases the colomn index
94 indexes[1][1] = (indexes[1][1] + 1) % 5 #increases the colomn index
95## print("New",indexes)
96 print()
97 code += keyMatrix[indexes[0][0]][indexes[0][1]] #Adding the produced cipherText
98 code += keyMatrix[indexes[1][0]][indexes[1][1]]
99
100 elif indexes[0][1] == indexes[1][1]: #Checks wheather they are is same colomns
101 indexes[0][0] = (indexes[0][0] + 1) % 5 #increases the row index
102 indexes[1][0] = (indexes[1][0] + 1) % 5 #increases the row index
103## print("New",indexes)
104 code += keyMatrix[indexes[0][0]][indexes[0][1]] #Adding the produced cipherText
105 code += keyMatrix[indexes[1][0]][indexes[1][1]]
106
107 else:
108## print(indexes)
109 code += keyMatrix[indexes[0][0]][indexes[1][1]] #Adding the intersection of the first and second letter w.r.t to first's row
110 code += keyMatrix[indexes[1][0]][indexes[0][1]] #Adding the intersection of the first and second letter w.r.t to second's row
111 if count != None:
112 count += 2
113 if count != None and noOfX != None:
114 return (code, count, noOfX)
115 else:
116 return code
117
118msg = "balloon"
119key = "monarchy"
120print("Message : ", msg)
121print("Key : ", key)
122print("Encryption : ",playFairCipher(msg, key))
123-----------------------------------------------
124#Railfence Cipher
125
126def RailfenceCipher(msg):
127 code1 = ""
128 code2 = ""
129 for i in range(len(msg)):
130 if i%2 == 0:
131 code1 += msg[i]
132 else:
133 code2 += msg[i]
134 return code1+code2
135msg = "Shubham"
136print("Encrypt", RailfenceCipher(msg))
137-----------------------------------------------
138#vernam Cipher
139
140import random
141def vernumCipher(msg):
142 code = ""
143 for i in range(len(msg)//26):
144 code += encrypt(msg[26*i:26*(i+1)])
145 code += encrypt(msg[26*(len(msg)//26):])
146 return code
147
148def encrypt(msg):
149 code = ""
150 key = [i for i in range(26)]
151
152 random.shuffle(key)
153## print("key",key)
154
155 msgVal = [ord(letter)-97 for letter in msg]
156## print("mv",msgVal)
157
158 total = [(msgVal[i] + key[i])%26 for i in range(len(msg))]
159## print("Total",total)
160
161 for i in range(len(msg)):
162 code += chr(total[i] + 97)
163 return code
164
165print(vernumCipher("hiiiii"))
166-----------------------------------------------
167#RSA
168
169import random
170import math
171def RSA(msg):
172 p = generatePrime()
173 q = generatePrime()
174
175 n = p*q
176 phi = (p-1) * (q-1)
177
178 while True:
179 e = random.randint(2, phi)
180 gcd, d = GCD(phi, e)
181 if gcd == 1:
182 break
183 d = d%phi
184
185 msgVal = [ord(i) - 97 for i in msg]
186 code = []
187
188
189 for i in range(len(msg)):
190 code.append(msgVal[i]**e % n)
191 print(code)
192
193 m = ""
194 for i in code:
195 m += chr((i**d) % n + 97)
196 print(m)
197
198def GCD(a, b):
199 t1 = 0
200 t2 = 1
201 while b > 0:
202 q = a // b
203 r = a - q*b
204 a = b
205 b = r
206 t = t1 - t2*q
207 t1 = t2
208 t2 = t
209 return (a, t1)
210
211
212def isPrime(n): # PrimeChecker
213 if n == 1: return False
214 elif n == 2 : return True
215 elif n % 2 == 0 : return False
216 else:
217 for i in range(3, math.floor(n**0.5) + 1, 2):
218 if n % i == 0:
219 return False
220 return True
221
222def generatePrime(lb = 1, ub = 100): # PrimeGenerator
223 while True:
224 num = random.randint(lb, ub)
225 if isPrime(num) : return num
226
227msg = "prakhar"
228print("Message :", msg)
229RSA(msg)
230
231----------------------------------------------
232#Diffie Hellman
233
234import random
235import math
236
237def diffieHellman():
238 n = generatePrime(10,100)
239 g = generatePrime(10,100)
240 x = random.randInt(1,20)
241 y = random.randInt(1,20)
242 A = g**x%n
243 print("Bob sends Alice ", A)
244 B = g**y%n
245 print("Alice sends Bob ", B)
246 k1 = B**x%n
247 print("Alice key", k1)
248 k2 = A**y%n
249 print("Bob's Key", k2)
250def generatePrime(lB,uB):
251 while True:
252 num = random.randInt(lB,uB)
253 if checkPrime(num):
254 return num
255def checkPrime(num):
256 if num ==1 : return False
257 elif num == 2 : return True
258 elif num%2 == 0 : return False
259 else:
260 for i in range(3,math.ceil(num**0.5),2):
261 if num%i == : return False
262 return True
263diffieHellman()
264----------------------------------------------
265#DES
266
267package des;
268
269import java.security.NoSuchAlgorithmException;
270import javax.crypto.*;
271
272/**
273 *
274 * @author Dell
275 */
276public class Des {
277
278 Cipher ecipher;
279 Cipher dcipher;
280
281 Des(SecretKey key, String algorithm){
282 try{
283 ecipher = Cipher.getInstance(algorithm);
284 dcipher = Cipher.getInstance(algorithm);
285 ecipher.init(Cipher.ENCRYPT_MODE, key);
286 dcipher.init(Cipher.DECRYPT_MODE, key);
287 }
288 catch(Exception e){
289 e.printStackTrace();
290 }
291 }
292
293 public String encrypt(String str){
294 try{
295 byte[] utf8 = str.getBytes("UTF8");
296 byte[] enc = ecipher.doFinal(utf8);
297 return new sun.misc.BASE64Encoder().encode(enc);
298 }
299 catch(Exception e){
300 e.printStackTrace();
301 }
302 return null;
303 }
304
305 public String decrypt(String str){
306 try{
307 byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
308 byte[] utf8 = dcipher.doFinal(dec);
309 return new String(utf8,"UTF8");
310 }
311 catch(Exception e){
312 e.printStackTrace();
313 }
314 return null;
315 }
316
317 public static void testUsingSecretKey()
318 {
319 try{
320 String secretString="Welcome to the world of cryptography";
321 SecretKey deskey=KeyGenerator.getInstance("DES").generateKey();
322
323 Des desEncrypter=new Des(deskey,deskey.getAlgorithm());
324
325 //Encrypt the string
326 String desEncrypted=desEncrypter.encrypt(secretString);
327
328 //Decrypt the string
329 String desDecrypted=desEncrypter.decrypt(desEncrypted);
330
331 System.out.println(deskey.getAlgorithm()+"Encryption algorithm");
332 System.out.println("Original String: "+secretString);
333 System.out.println("Encrypted String: "+desEncrypted);
334 System.out.println("Decrypted String: "+desDecrypted);
335 System.out.println();
336
337 }
338 catch(NoSuchAlgorithmException e){
339 e.printStackTrace();
340 }
341 }
342
343 /**
344 * @param args the command line arguments
345 */
346 public static void main(String[] args) {
347 // TODO code application logic here
348 testUsingSecretKey();
349 }
350
351}
352--------------------------------------------------------
353#AES
354
355import java.io.UnsupportedEncodingException;
356import java.security.MessageDigest;
357import java.security.NoSuchAlgorithmException;
358import java.util.Arrays;
359import java.util.Base64;
360
361import javax.crypto.Cipher;
362import javax.crypto.spec.SecretKeySpec;
363
364public class AES {
365
366 private static SecretKeySpec secretKey;
367 private static byte[] key;
368
369 public static void setKey(String myKey)
370 {
371 MessageDigest sha = null;
372 try {
373 key = myKey.getBytes("UTF-8");
374 sha = MessageDigest.getInstance("SHA-1");
375 key = sha.digest(key);
376 key = Arrays.copyOf(key, 16);
377 secretKey = new SecretKeySpec(key, "AES");
378 }
379 catch (NoSuchAlgorithmException e) {
380 e.printStackTrace();
381 }
382 catch (UnsupportedEncodingException e) {
383 e.printStackTrace();
384 }
385 }
386
387 public static String encrypt(String strToEncrypt, String secret)
388 {
389 try
390 {
391 setKey(secret);
392 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
393 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
394 return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
395 }
396 catch (Exception e)
397 {
398 System.out.println("Error while encrypting: " + e.toString());
399 }
400 return null;
401 }
402
403 public static String decrypt(String strToDecrypt, String secret)
404 {
405 try
406 {
407 setKey(secret);
408 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
409 cipher.init(Cipher.DECRYPT_MODE, secretKey);
410 return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
411 }
412 catch (Exception e)
413 {
414 System.out.println("Error while decrypting: " + e.toString());
415 }
416 return null;
417 }
418
419 public static void main(String[] args)
420 {
421 final String secretKey = "abcdef";
422
423 String originalString = "todayisnsexam";
424 String encryptedString = AES.encrypt(originalString, secretKey) ;
425 String decryptedString = AES.decrypt(encryptedString, secretKey) ;
426
427 System.out.println(originalString);
428 System.out.println(encryptedString);
429 System.out.println(decryptedString);
430 }
431}
432--------------------------------------------------------
433#Port Scanner
434
435public static void main(String[] args) {
436 Socket skt;
437 String host = "localhost";
438
439 if(args.length>0){
440 host = args[0]
441 }
442
443 try{
444 System.out.println("IP Address: 192.168.109.119");
445 for(int i = 0;i <=200;i++){
446 try{
447 Socket s =new Socket(host,i);
448 s.connect(new InetSocketAddress("192.168.109.119",i),10);
449 System.out.println("Open port found: "+i);
450 s.close();
451 }
452 catch(Exception e){
453
454 }
455 }
456 }
457 catch(Exception e){
458 e.printStackTrace();
459 }
460 }
461--------------------------------------------------------
462#MD5
463
464package md5;
465
466import java.nio.charset.StandardCharsets;
467import java.security.MessageDigest;
468import java.security.NoSuchAlgorithmException;
469
470public class Md5 {
471
472 public static void main(String[] args) throws NoSuchAlgorithmException {
473
474 String password = "123456";
475
476 MessageDigest md = MessageDigest.getInstance("MD5");
477 byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));
478
479 StringBuilder sb = new StringBuilder();
480 for (byte b : hashInBytes) {
481 sb.append(String.format("%02x", b));
482 }
483 System.out.println(sb.toString());
484
485 }
486
487}
488--------------------------------------------------------
489--------------------------------------------------------
490#graphical LPP
491
492print("LLP by graphical method by 2 constraints")
493maxmin = input("Enter max for maximum and min for Minimum")
494if(maxmin == "max" or maxmin == "min"):
495 print("Enter value of Z:")
496 zx1 = int(input("Enter x1 value for Z:"))
497 zx2 = int(input("Enter x2 value of Z:"))
498 print("Enter value of constraint 1:")
499 c1x1 = int(input("Enter x1 value:"))
500 c1x2 = int(input("Enter x2 value"))
501 c1c1 = int(input("Enter less than value:"))
502 print("Enter value of constraint 2:")
503 c2x1 = int(input("Enter x1 value:"))
504 c2x2 = int(input("Enter x2 value:"))
505 c2c2 = int(input("Enter less than value"))
506 if(maxmin == "max"):
507 print("\n maximize Z")
508 if(zx2 > 0):
509 print("Z = " + str(zx1)+ "x1"+ " + " + str(zx2)+" x2")
510 else:
511 print("Z = " + str(zx1) + "x1" + "-" + str(abs(zx2)) + "x2")
512 else:
513 print("\n minimize Z")
514 if(zx2 > 0):
515 print("Z = "+ str(zx1)+ "x1" + "+"+ str(zx2)+ "x2")
516 else:
517 print("Z = " + str(zx1) + "x1" + "-" + str(zx2) + "x2")
518 print("sub to:")
519 if(c1x2 > 0):
520 print(" " + str(c1x1) + "x1" + " + " +str(c1x2)+ "x2 <=" + str(c1c1))
521 else:
522 print(" "+ str(c1x1) + "x1" + " + " + str(abs(c1x2))+"x2 <=" + str(c1c1))
523 if(c2x2 > 0):
524 print(" "+ str(c2x1)+ "x1" + " + " +str(c2x2)+ "x2 <=" + str(c2c2))
525 else:
526 print(" " + str(c2x1) + "x1" + " + "+ str(abs(c2x2)) + "x2 <=" + str(c2c2))
527 print("x1 and x2 >=0")
528 z = [0,0,0]
529 x1 = 0
530 x2 = 0
531 x1 = (((c1c1 * c2x2) - (c2c2 * c1x2)) / ((c1x1 * c2x2)-(c2x1 * c1x2)))
532 x2 = (((c1c1 * c2x1) - (c2c2 * c1x1)) / ((c1x2 * c2x1)-(c2x2 * c1x1)))
533 p1 = (0, c1c1 / c1x2)
534 p2 = (c1c1/ c1x1, 0)
535 p3 = (0, c2c2 / c2x2)
536 p4 = (c2c2 / c2x1, 0)
537 poi = (x1, x2)
538 z[0] = ((zx1 * x1) + (zx2 * x2))
539 if(p1[1]<p3[1]):
540 z[1] = ((zx1 * 0)+ (zx2 * p1[1]))
541 else:
542 z[1] = ((zx1 * 0)+ (zx2 * p3[1]))
543 if(p2[0] < p4[0]):
544 z[2] = ((zx1 * p2[0])+ (zx2 * 0))
545 else:
546 z[2] = ((zx1 * p4[0]) + (zx2 * 0))
547 if(maxmin == "max"):
548 print("\n Maximum solution for Z is:", max(z))
549 elif(maxmin == "min"):
550 print("\n Minimum solution for Z is:", min(z))
551 else:
552 print("\n Invalid input")
553else:
554 print("Invalid input")
555--------------------------------------------------------------------
556#LCM
557
558import math
559
560def dis():
561 for i in range(3):
562 print(mat[i])
563
564def lcm():
565 print('LCM:')
566 l = []
567 for i in range(3):
568 for j in range(4):
569 l.append(cost[i][j])
570
571 while max(sup)!=0:
572 r = l.index(min(l))
573 l[r] = infinity
574 c = r%4
575 r = r//4
576
577 if sup[r] == 0 or dem[c] == 0:
578 continue
579 elif sup[r] < dem[c]:
580 dem[c] -= sup[r]
581 mat[r][c] = sup[r]
582 sup[r] = 0
583 else:
584 sup[r] -= dem[c]
585 mat[r][c] = dem[c]
586 dem[c] = 0
587 dis()
588
589infinity = math.inf
590mat = [[0 for i in range(4)]for i in range(3)]
591
592cost = [
593 [6,4,1,5],
594 [8,9,2,7],
595 [4,3,6,2]
596 ]
597
598sup = [14,16,5]
599dem = [6,10,15,4]
600lcm()
601--------------------------------------------------------------
602#NWCR
603
604def dis(rows):
605 for i in range(rows):
606 print(mat[i])
607
608def nwcr(rows, cols):
609 print("NWCR:")
610 r = 0
611 c = 0
612 while r < rows and c < cols:
613 if sup[r] < dem [c]:
614 dem[c] -= sup[r]
615 mat[r][c] = sup[r]
616 sup[r] = 0
617 r += 1
618 elif dem[c] < sup[r]:
619 sup[r] -= dem[c]
620 mat[r][c] = dem[c]
621 dem[c] = 0
622 c += 1
623 else:
624 mat[r][c] = sup[r]
625 sup[r] = 0
626 dem[c] = 0
627 r += 1
628 c += 1
629 dis(rows)
630r,c =list(map(int,input("Enter rows and cols").split()))
631mat = [[0 for i in range(c)] for i in range(r)]
632cost = []
633print("Enter matrix")
634for i in range(r):
635 cost.append(list(map(int,input().split())))
636sup = list(map(int,input("Enter supply").split()))
637dem = list(map(int,input("Enter demand").split()))
638nwcr(r, c)
639---------------------------------------------------------------