Advertisement
Guest User

reycss

a guest
May 1st, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.75 KB | None | 0 0
  1. https://pastebin.com/yxpdbQwP
  2.  
  3. Ifconfig
  4.  
  5. ************************************************************************
  6. whois 192.168.39.187
  7.  
  8. A 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. ***************************************************************************
  11. dig www.google.com OR dig google.com +short
  12.  
  13. domain information groper
  14. It performs DNS lookups
  15. dig 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.  
  17. dig 192.168.39.187
  18.  
  19. ****************************************************************************
  20. traceroute www.google.com
  21.  
  22. traceroute prints the route that packets take to a network host.
  23.  
  24. https://www.computerhope.com/unix/utracero.htm
  25. **************************************************************************
  26. nslookup google.com
  27.  
  28. The nslookup command is used to query Internet name servers interactively for information.
  29. By default, nslookup will translate a domain name to an IP address and vice versa
  30.  
  31. https://www.computerhope.com/unix/unslooku.htm
  32. **************************************************************************
  33. sudo netstat -plnt
  34. netstat -r
  35. netstat -i
  36.  
  37. netstat -a | grep -e unix -e ESTABLISHED
  38. netstat -a | grep -e udp -e ESTABLISHED
  39. netstat -a | grep -c -e tcp -e ESTABLISHED
  40. sudo netstat -plnt | grep 80
  41.  
  42.  
  43.  
  44. network 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.  
  46. netstat ("network statistics") is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface
  47. **************************************************************************
  48. Find ves public ip address? -
  49. dig ves.ac.in
  50.  
  51.  
  52. **************************************************************************
  53. sudo nmap -v -Pn -O 192.168.45.151
  54.  
  55. nmap ("Network Mapper") is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks,
  56.  
  57. https://www.unixmen.com/10-practical-examples-linux-nmap-command/
  58.  
  59. nmap google.com
  60. sudo nmap -O google.com
  61. sudo nmap -sX google.com
  62.  
  63.  
  64.  
  65. #######################################
  66.  
  67. hping
  68. sudo hping3 192.168.37.56
  69. sudo hping3 -c 10000 --flood --rand-source 192.168.37.56
  70. sudo hping3 -c 10 192.168.36.193
  71. sudo hping3 -c 10 -d 120 192.168.36.193
  72. sudo hping3 -1 -c 10 -a 192.168.36.193 192.168.37.56
  73. The -V is for a verbose output
  74. The -c command is essentially the number of packets you want to send to the particular target. In this case, 1000 packets
  75. The -d command allows you to choose the size of a packet. For this example, 100
  76. To specify the type of packet, we need to add -S which is a syn packet
  77. After this, the -p command specifies the port, so the port 21 in this case, the FTP port.
  78. You then type in the command –flood
  79. -a Spoofs the source address
  80. Then add the ip which you need to spoof
  81. You then add the address which you need to send it to.
  82. https://hsploit.com/hping3-syn-flooding-icmp-flooding-land-attacks/
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91. #######################################
  92. firewall using Iptables
  93.  
  94. *************list rules
  95. iptables -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
  103. iptables -A OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
  104. ***********unblock websites
  105. iptables -D OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
  106.  
  107. *******Filtering packets based on source
  108. sudo iptables -A INPUT -s 192.168.1.3 -j DROP
  109. sudo iptables -A INPUT -s 192.168.1.3 -j ACCEPT
  110.  
  111. https://www.hostinger.in/tutorials/iptables-tutorial
  112.  
  113.  
  114. Block Access To Outgoing IP Address
  115.  
  116. The following rule will block ip address 202.54.1.22 from making any outgoing connection:
  117. iptables -A OUTPUT -d 202.54.1.22 -j DROP
  118.  
  119. ****************************************************************************
  120. Wireshark
  121.  
  122. Install
  123. sudo add-apt-repository ppa:wireshark-dev/stable
  124. sudo apt-get update
  125. sudo 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.  
  133. remove
  134. sudo apt-get remove --autoremove wireshark
  135. sudo apt-get remove --autoremove wireshark wireshark-*
  136.  
  137. ***************************************************************************
  138.  
  139. GPG
  140. {https://www.digitalocean.com/community/tutorials/how-to-use-gpg-to-encrypt-and-sign-messages}
  141.  
  142. sudo apt-get update
  143. sudo apt-get install gnupg
  144. gpg --gen-key
  145. gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
  146. chmod 600 ~/revocation.crt
  147. Listing all generated keys:
  148. gpg --list-secret-keys
  149. Send your public key as a file to the recipient:
  150. gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
  151. {gpg --output ~/mygpg.key --armor --export your_email@address.com}
  152.  
  153. gpg mypubkey.gpg
  154. Friend sends his/her public key to you:
  155. gpg --import mypubkey.gpg
  156. {gpg --import name_of_pub_key_file}
  157.  
  158. encryption:
  159. gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
  160.  
  161. Decryption:
  162. gpg abc.txt.asc
  163.  
  164.  
  165.  
  166.  
  167.  
  168.  
  169. Installing GPG
  170. lab308-3@Shubham:~$ sudo apt-get update
  171. [sudo] password for lab308-3:
  172. Hit: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
  173. Hit:4 http://ppa.launchpad.net/danielrichter2007/grub-customizer/ubuntu xenial InRelease Hit:5 http://in.archive.ubuntu.com/ubuntu xenial-updates InRelease
  174. Hit:6 http://in.archive.ubuntu.com/ubuntu xenial-backports InRelease Hit:7 http://ppa.launchpad.net/gns3/ppa/ubuntu xenial InRelease
  175. Hit:8 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease Reading package lists... Done
  176.  
  177. lab308-3@Shubham:~$ sudo apt-get install gnupg
  178. Reading package lists... Done
  179. Building dependency tree
  180. Reading state information... Done
  181. gnupg is already the newest version (1.4.20-1ubuntu3.3).
  182. 0 upgraded, 0 newly installed, 0 to remove and 141 not upgraded.
  183.  
  184. lab308-3@Shubham:~$ gpg --gen-key
  185. gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
  186. This is free software: you are free to change and redistribute it.
  187. There is NO WARRANTY, to the extent permitted by law.
  188. Key Generation
  189.  
  190.  
  191. lab308-3@Shubham:~$ gpg --gen-key
  192.  
  193. gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
  194. This is free software: you are free to change and redistribute it.
  195. There is NO WARRANTY, to the extent permitted by law.
  196. Please 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)
  201. Your selection? 1
  202.  
  203. RSA keys may be between 1024 and 4096 bits long.
  204. What keysize do you want? (2048) 4096
  205. Requested keysize is 4096 bits
  206.  
  207. Please specify how long the key should be valid.
  208. 0 = 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
  213. Key is valid for? (0) 1y
  214.  
  215. Key expires at Tuesday 17 March 2020 08:41:50 AM IST
  216. Is this correct? (y/N) y
  217.  
  218. You 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.  
  221. Real name: Stephen Grinder
  222. Email address: 2016.stephen.grinder@ves.ac.in
  223. Comment: Stephen
  224. You selected this USER-ID:
  225. "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  226. Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
  227.  
  228. You need a Passphrase to protect your secret key.
  229. We 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.
  230. Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 203 more bytes)
  231. .........+++++
  232. Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 11 more bytes)
  233. .........+++++
  234. We 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.
  235. Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 178 more bytes) .+++++
  236. Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 243 more bytes)
  237. .......+++++
  238. gpg: /home/lab308-3/.gnupg/trustdb.gpg: trustdb created
  239. gpg: key 7EDF0433 marked as ultimately trusted
  240. public and secret key created and signed.
  241. gpg: checking the trustdb
  242. gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
  243. gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
  244. gpg: next trustdb check due at 2020-03-17
  245. pub 4096R/7EDF0433 2019-03-18 [expires: 2020-03-17]
  246. Key fingerprint = 8A72 FEAC 9855 2574 4ED5 0A91 D06F 2B3F 7EDF 0433
  247. uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
  248. sub 4096R/8D3D2327 2019-03-18 [expires: 2020-03-17]
  249.  
  250.  
  251. Create a Revocation Certificate
  252. lab308-3@Shubham:~$ gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
  253.  
  254. sec 4096R/7EDF0433 2019-03-18 Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
  255. Create a revocation certificate for this key? (y/N) y
  256.  
  257. Please select the reason for the revocation:
  258. 0 = No reason specified
  259. 1 = Key has been compromised
  260. 2 = Key is superseded
  261. 3 = Key is no longer used
  262. Q = Cancel
  263. (Probably you want to select 1 here)
  264. Your decision? 0
  265.  
  266. Enter an optional description; end it with an empty line:
  267. >
  268. Reason for revocation: No reason specified
  269. (No description given)
  270. Is this okay? (y/N) y
  271.  
  272. You need a passphrase to unlock the secret key for
  273. user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  274. 4096-bit RSA key, ID 7EDF0433, created 2019-03-18
  275. ASCII armored output forced.
  276. Revocation certificate created.
  277. Please 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
  278. your media become unreadable. But have some caution: The print system of your machine might store the data and make it available to others!
  279.  
  280. lab308-3@Shubham:~$ chmod 600 ~/revocation.crt
  281.  
  282. Listing all generated keys
  283. stephen@stephen:~$ gpg --list-secret-keys
  284. /home/stephen/.gnupg/secring.gpg
  285. -----------------------------
  286. sec 2048R/84C7D581 2019-03-31 [expires: 2020-03-30]
  287. uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
  288. ssb 2048R/46ECE634 2019-03-31
  289.  
  290. Send your public key as a file to the recipient
  291. stephen@stephen:~$ gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
  292. stephen@stephen:~$ gpg mypubkey.gpg
  293. pub 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.  
  295. Friend sends his/her public key to you
  296. stephen@stephen:~$ gpg --import mypubkey.gpg
  297. gpg: key 84C7D581: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>" not changed
  298. gpg: Total number processed: 1
  299. gpg: unchanged: 1
  300.  
  301.  
  302. Encryption
  303.  
  304. stephen@stephen:~$ gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
  305. You need a passphrase to unlock the secret key for
  306. user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  307. 2048-bit RSA key, ID 84C7D581, created 2019-03-31
  308.  
  309. Decryption
  310. stephen@stephen:~$ gpg abc.txt.asc
  311. You need a passphrase to unlock the secret key for
  312. user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  313. 2048-bit RSA key, ID 46ECE634, created 2019-03-31 (main key ID 84C7D581)
  314. gpg: encrypted with 2048-bit RSA key, ID 46ECE634, created 2019-03-31 "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  315. File `abc.txt' exists. Overwrite? (y/N) y
  316. gpg: Signature made Sunday 31 March 2019 07:52:23 PM IST using RSA key ID 84C7D581
  317. gpg: Good signature from "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
  318.  
  319.  
  320.  
  321.  
  322.  
  323.  
  324. ****************************************************************************
  325. SQL INJECTION
  326.  
  327. sudo apt-get install sqlmap
  328.  
  329. Step 1: List information about the existing databases
  330. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs
  331.  
  332. Step 2: List information about Tables present in a particular Database
  333. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart --tables
  334.  
  335. Step 3: List information about the columns of a particular table
  336. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists --columns
  337.  
  338. Step 4: Dump the data from the columns
  339. sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists -C aname --dump
  340.  
  341.  
  342. *******************************************************************
  343. XSS
  344.  
  345. https://xss-game.appspot.com/
  346.  
  347.  
  348.  
  349.  
  350.  
  351. ****************************************************************
  352. Ettercap
  353.  
  354. https://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
  365. import random
  366. import time
  367. import socket
  368. def select_private_keys(p):
  369. a = random.randrange(1,p)
  370. return a
  371. def 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
  385. if _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
  426. import random
  427. import time
  428. import socket
  429. def select_private_keys(p):
  430. a = random.randrange(1,p)
  431. return a
  432. if _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
  469. import random
  470. import socket
  471.  
  472. def 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.  
  488. def 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.  
  497. if __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
  513. import random
  514. import socket
  515.  
  516. def 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.  
  532. def 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.  
  542. if __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
  560. import random
  561. def gcd(a, b):
  562. while b != 0:
  563. a, b = b, a % b
  564. return a
  565. def 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
  574. def 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
  588. def 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))
  600. def encrypt(public_key, plain_text):
  601. key, n = public_key
  602. cipher = pow(int(plain_text),int(key),int(n))
  603. return cipher
  604. def decrypt(private_key, encrypted_text):
  605. key, n = private_key
  606. mssg = pow(encrypted_text,key,n)
  607. return mssg
  608. if _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.  
  627. import math
  628. from sympy import factorint #pip install sympy
  629.  
  630. factors=[]
  631. power=[]
  632. '''
  633. def isPrime(p):
  634. for i in range(2,p//2+1):
  635. if p%i==0:
  636. return False
  637. return True
  638.  
  639. def 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. '''
  655. def 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.  
  664. def 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.  
  686. def encrypt(s,e,n):
  687. c=pow(s,e,n)
  688. return c
  689.  
  690. def decrypt(c,e,n):
  691. p=pow(c,d,n)
  692. return p
  693.  
  694. print("RSA key generation:")
  695. print("1. Encryption with public key")
  696. print("2. Encryption with private key(Digital Signature)")
  697. ch=int(input("Enter your choice:"))
  698.  
  699. n=int(input("Enter n:"))
  700. print("n:",n)
  701.  
  702. #factorize(n)
  703. fact=factorint(n)
  704. factors=list(fact.keys())
  705. power=list(fact.values())
  706. print(factors)
  707. print(power)
  708. phi=calc_phi()
  709.  
  710. d=-1
  711. while 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.")
  717. print("d:",d)
  718. if ch==1:
  719. print("Public Key: (", n, ",", e, ")")
  720. print("Private Key: (", n, ",", d, ")")
  721. else:
  722. print("Private Key: (", n, ",", e, ")")
  723. print("Public Key: (", n, ",", d, ")")
  724. s=int(input("Enter the plain text:"))
  725. c=encrypt(s,e,n)
  726. print("encrypted text : ",c)
  727. p=decrypt(c,e,n)
  728. print("decrypted text : ",p)
  729.  
  730.  
  731.  
  732. ####################################
  733.  
  734. /////////////////////MD5 Number 5
  735. import hashlib
  736. import time
  737. import os
  738. import math
  739. md=open("hii.txt","r")
  740. data=md.read()
  741. print('Length of input data is :',len(data))
  742. start = time.clock()
  743. result = hashlib.md5(data.encode())
  744. print(result.hexdigest())
  745. a=len(result.hexdigest())
  746. end = time.clock()
  747. print('length of encoded data using md5',a)
  748. print("time required :",end-start)
  749.  
  750. ///////////////////SHA
  751. import hashlib
  752. import time
  753. # initializing string
  754. str1 = "Hi"
  755. input_length=len(str1)
  756. start_time=time.time()
  757. # then sending to SHA1()
  758. result = hashlib.sha1(str1.encode())
  759. print("The hexadecimal equivalent of SHA1 is : ")
  760. print(result.hexdigest())
  761. end_time=time.time()
  762. print('length of input string',input_length)
  763. print('length of output string',result.digest_size)
  764. print('Start time =',start_time)
  765. print('End_time=',end_time)
  766. print('Total time required =',(end_time-start_time))
  767.  
  768.  
  769.  
  770.  
  771.  
  772.  
  773.  
  774.  
  775. *************************************************************
  776. Product cipher
  777.  
  778.  
  779.  
  780. k = [3,1,4,5,2]
  781. ki = [2,5,1,3,4]
  782. kc = 3
  783. alpha = 'abcdefghijklmnopqrstuvwxyz'
  784. msg = input("Enter the message: ")
  785. msg = "".join(msg.split())
  786. enc = ""
  787. dec = ""
  788.  
  789. ##while len(msg)%5 != 0 :
  790. ## msg = msg + "x"
  791.  
  792. for i in msg :
  793. enc = enc + alpha[(alpha.find(i)+kc)%26]
  794.  
  795. print("After encryption with Caesar Cipher:",enc)
  796. msg = enc
  797. enc = ""
  798.  
  799. mat = [["x" for i in range(5)] for j in range(int(len(msg)/5))]
  800. print("Transposition Matrix: ")
  801. for i in range(int(len(msg)/5)) :
  802. for j in range(5):
  803. print(msg[i*5+j], end=" ")
  804. print()
  805.  
  806. l = 0
  807. for 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.  
  812. enc = ""
  813. for i in range(5) :
  814. for j in range(int(len(msg)/5)) :
  815. enc = enc + mat[j][i]
  816.  
  817. print("Final Encrypted Message:",enc.upper())
  818.  
  819. for 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.  
  823. enc= ""
  824.  
  825. for i in range(int(len(msg)/5)) :
  826. for j in range(5) :
  827. enc = enc + mat[i][ki[j]-1]
  828.  
  829. for i in enc :
  830. dec = dec + alpha[(alpha.find(i)-kc)%26]
  831.  
  832. print("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.  
  840. key = 'abcdefghijklmnopqrstuvwxyz'
  841.  
  842. def 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.  
  855. def 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.  
  868. text = "I am coding Python on SoloLearn!"
  869. offset = 5
  870.  
  871. encrypted = encrypt(offset, text)
  872. print('Encrypted:', encrypted)
  873.  
  874. decrypted = decrypt(offset, encrypted)
  875. print('Decrypted:', decrypted)
  876.  
  877.  
  878.  
  879.  
  880.  
  881.  
  882. //////////////////////////////Autokey substitution cipher
  883.  
  884. import math
  885. import random
  886.  
  887. def 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.  
  900. def 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.  
  910. if __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 '''
  928. import math
  929.  
  930. #WORKING
  931. ''' e.g. message is 'Python' to be transposed
  932. In keyless trans.n message is split into 2 rows having alternate characters of message
  933. 1st row --> | P | | T | | O | |
  934. 2nd row --> | | Y | | H | | N |
  935. The transposed message will be all characters of 1st row then of the 2nd row
  936. i.e. --> 'PTOYHN'
  937. '''
  938.  
  939. def 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.  
  953. def 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.  
  966. if __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))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement