Question

Exercise 3.2 (Symmetric and Asymmetric Encryption) t In this exercise, you will send an encrypted message from a socket clien

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Language Used: Python 2.7

Download PyCrypto module from PyCryptoPlus .

I have shown both the server side and the client side implementations. Please find the code below:

Server Side:

import os
import time
import itertools
import socket
import hashlib
import threading
import sys
import Crypto.Cipher.AES as AES
from Crypto.PublicKey import RSA
from CryptoPlus.Cipher import IDEA

#get server address and port number
hosts = raw_input("Server Addr - > ")
ports = int(input("Port no - > "))
#check server port
checkflag = False
doneflag = False

def anim():
for char in itertools.cycle(['.....','.......','..........','............']):
if doneflag:
break
sys.stdout.write('\rCHECKING NOT USED PORT AND IP ADDRESS '+char)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\r -----SERVER HAS STARTED. WAITING FOR CLIENT-----\n')
try:
#set up socket
serv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serv.bind((hosts,ports))
serv.listen(5)
checkflag = True
except BaseException:
print "-----Check Port or Server Address -----"
checkflag = False

if checkflag is True:
# Quit
shut_down = False
# printing "Server Started"
threadload = threading.Thread(target=anim)
threadload.start()

time.sleep(4)
doneflag = True
# client and address binding
cl,adrs = serv.accept()
print ("CLIENT CONNECTED. ADDRESS ->",adrs)
print ("\n-----WAITING FOR PUBLIC KEY & HASH -----\n")

# Public Key
getpbkey = cl.recv(2048)

#convert string to KEY
servpublic_key = RSA.importKey(getpbkey)

# public key hashing in server side for validation
hashobj = hashlib.sha1(getpbkey)
hexdigest = hashobj.hexdigest()

if getpbkey != "":
print (getpbkey)
cl.send("YES")
get_hash = cl.recv(1024)
print ("\n----- PUBLIC KEY HASH ----- \n"+get_hash)
if hexdigest == get_hash:
# create session key
key128 = os.urandom(16)
#encrypt CTR MODE session key
enc = AES.new(key128,AES.MODE_CTR,counter = lambda:key128)
encryptor = enc.encrypt(key128)
#hash sha1
enc_object = hashlib.sha1(encryptor)
enc_digest = enc_object.hexdigest()

print ("\n----- SESSION KEY -----\n"+enc_digest)

# session key and public key encryption
En = servpublic_key.encrypt(encryptor,16)
print ("\n-----ENCRYPTED PUBLIC AND SESSION KEY-----\n"+str(En))
print ("\n-----HANDSHAKE DONE-----")
cl.send(str(En))
while True:
#message from client
newmsg = cl.recv(1024)
#decoding the message from HEX to decrypt the ecrypted version of the message only
Decoded = newmsg.decode("hex")
#making enc_digest(session_key) as the key
k = enc_digest[:16]
print ("\nENCRYPTED MESSAGE FROM CLIENT -> "+newmsg)
#decrypt message from the client
idea_Decrypt = IDEA.new(k, IDEA.MODE_CTR, counter=lambda: k)
d_Msg = idea_Decrypt.decrypt(Decoded)
print ("\n**New Message** "+time.ctime(time.time()) +" > "+d_Msg+"\n")
msg = raw_input("\nMessage To Client -> ")
if msg != "":
idea_Encrypt = IDEA.new(k, IDEA.MODE_CTR, counter=lambda : k)
e_Msg = ideaEncrypt.encrypt(msg)
e_Msg = e_Msg.encode("hex").upper()
if e_Msg != "":
print ("ENCRYPTED MESSAGE TO CLIENT-> " + e_Msg)
cl.send(e_Msg)
cl.close()
else:
print ("\n-----PUBLIC KEY HASH DOESNOT MATCH-----\n")

Client Side

import time
import hashlib
import itertools
import socket
import threading
import sys
from Crypto import Random
from Crypto.PublicKey import RSA
from CryptoPlus.Cipher import IDEA

#animate loading
flag = False
def anim():
for char in itertools.cycle(['.....','.......','..........','............']):
if flag:
break
sys.stdout.write('\rCONFIRMING CONNECTION TO SERVER '+char)
sys.stdout.flush()
time.sleep(0.1)

# private and public key
rand_generator = Random.new().read
K = RSA.generate(1024,rand_generator)
pub = K.publickey().exportKey()
priv = K.exportKey()

#hash the public key
hash_obj = hashlib.sha1(pub)
hex_digest = hash_obj.hexdigest()

#Set up socket
serv = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#host and port
hosts = raw_input("Server Address To Be Connected -> ")
ports = int(input("Port of The Server -> "))
#bind port and the address
serv.connect((hosts, ports))
# Server Started Message
threadload = threading.Thread(target=anim)
threadload.start()

time.sleep(4)
flag = True

def send(t,name,K):
mess = raw_input(name + " : ")
K = K[:16]
#merg the message and name
whole = name+" : "+mess
idea_Encrypt = IDEA.new(K, IDEA.MODE_CTR, counter=lambda : K)
e_Msg = idea_Encrypt.encrypt(whole)
#convert encrypted message to HEX to readable
e_Msg = e_Msg.encode("hex").upper()
if e_Msg != "":
print ("ENCRYPTED MESSAGE TO SERVER-> "+e_Msg)
serv.send(e_Msg)
def recv(t,K):
newmsg = serv.recv(1024)
print ("\nENCRYPTED MESSAGE FROM SERVER-> " + newmsg)
K = K[:16]
decoded = newmsg.decode("hex")
idea_Decrypt = IDEA.new(K, IDEA.MODE_CTR, counter=lambda: K)
d_Msg = idea_Decrypt.decrypt(decoded)
print ("\n**New Message From Server** " + time.ctime(time.time()) + " : " + d_Msg + "\n")

while True:
serv.send(pub)
confirm = serv.recv(1024)
if confirm == "YES":
serv.send(hex_digest)

#connected message
msg = serv.recv(1024)
enc = eval(msg)
decrypt = K.decrypt(enc)
# hash sha1
enc_object = hashlib.sha1(decrypt)
enc_digest = enc_object.hexdigest()

print ("\n-----ENCRYPTED PUBLIC KEY AND SESSION KEY FROM SERVER-----")
print (msg)
print ("\n-----DECRYPTED SESSION KEY-----")
print (enc_digest)
print ("\n-----HANDSHAKE COMPLETE-----\n")
alais = raw_input("\nYour Name -> ")

while True:
threadsend = threading.Thread(target=send,args=("------Sending Message------",alais,enc_digest))
threadrecv = threading.Thread(target=recv,args=("------Recieving Message------",enc_digest))
threadsend.start()
threadrecv.start()

threadsend.join()
threadrecv.join()
time.sleep(0.5)
time.sleep(60)
serv.close()

Add a comment
Know the answer?
Add Answer to:
Exercise 3.2 (Symmetric and Asymmetric Encryption) t In this exercise, you will send an encrypted...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Question 4 (5 points) Consider the following scenario: Alice wants to send Bill a message. Alice...

    Question 4 (5 points) Consider the following scenario: Alice wants to send Bill a message. Alice encrypts some information using Bill's public key; Bill decrypts the ciphertext using his private key. This is an example of: Question 4 options: 1) symmetric encryption 2) digital certificate 3) asymmetric encryption 4) digital signature

  • The Diffie-Hellman public-key encryption algorithm is an alternative key exchange algorithm that is used by protocols...

    The Diffie-Hellman public-key encryption algorithm is an alternative key exchange algorithm that is used by protocols such as IPSec for communicating parties to agree on a shared key. The DH algorithm makes use of a large prime number p and another large number, g that is less than p. Both p and g are made public (so that an attacker would know them). In DH, Alice and Bob each independently choose secret keys, ?? and ??, respectively. Alice then computes...

  • (7) (2 pts) The simplified version of the handshaking procedure between a client and a bank...

    (7) (2 pts) The simplified version of the handshaking procedure between a client and a bank server for establishing a secure connection is described below (just consider it identical to the SSL/TLS described in class): 1. A client connects to the TLS-enabled bank server requesting a secure connection, and presents a list of supported ciphers (RC4, DES, AES, etc) and hash functions (MD5, SHA-1, etc). 2. The server picks the strongest cipher and hash. It then server sends back its...

  • 1.Which of the following statements about asymmetric-key encryption is correct? a When using asym...

    1.Which of the following statements about asymmetric-key encryption is correct? a When using asymmetric-key encryption method, a total of two keys are necessary in electronic communication between two parties. b Employees in the same company share the same public key. c Most companies would like to manage the private keys for their employees. d Most companies would like to use a Certificate Authority to manage the public keys of their employees. e Two of the above are correct. 2 Which...

  • Use C++ forehand e receiver creates a public key and a secret key as follows. Generate...

    Use C++ forehand e receiver creates a public key and a secret key as follows. Generate two distinct primes, p andq. Since they can be used to generate the secret key, they must be kept hidden. Let n-pg, phi(n) ((p-1)*(q-1) Select an integer e such that gcd(e, (p-100g-1))-1. The public key is the pair (e,n). This should be distributed widely. Compute d such that d-l(mod (p-1)(q-1). This can be done using the pulverizer. The secret key is the pair (d.n)....

  • Implement in Go language AES encryption mode CBC with providing the packages name for Go language....

    Implement in Go language AES encryption mode CBC with providing the packages name for Go language. You can implement AES-ECB Mode (the basic AES) from crypto/aes package and crypto/cipher.Block. You can also get the SHA-256 hash function from crypto/sha256. You can get the secure random numbers generator from crypto/rand package. However, the you will implement both CBC mode and HMAC from scratch. You are NOT allowed to use any libraries or packages to implement these two things for you. You...

  • For this hands-on project, you will use the SQL Server named instance SQLSERVERHOA, and the HandsOnOne...

    For this hands-on project, you will use the SQL Server named instance SQLSERVERHOA, and the HandsOnOne database and tables you created in previous chapters. The objective of this activity is to practice generating keys and encrypting/decrypting data. Document each step by taking a screen shot of the Query Editor window after successfully executing each SQL query. 1.In SQL Server Management Studio, open a new Query Editor window, which you will use for completing all steps in this activity. 2.Create a...

  • Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA...

    Write code for RSA encryption package rsa; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class RSA {    private BigInteger phi; private BigInteger e; private BigInteger d; private BigInteger num; public static void main(String[] args) {    Scanner keyboard = new Scanner(System.in); System.out.println("Enter the message you would like to encode, using any ASCII characters: "); String input = keyboard.nextLine(); int[] ASCIIvalues = new int[input.length()]; for (int i = 0; i < input.length(); i++) { ASCIIvalues[i] = input.charAt(i); } String ASCIInumbers...

  • Exercise: Execute the next cell to produce a message encrypted using the Hill cipher method [4]: ...

    Hill cypher Exercise: Execute the next cell to produce a message encrypted using the Hill cipher method [4]: cipher make_cipher cipher out [4]: 129, 41, 42, 75, 94, 103, 34, 43, 48, 44, 44, 64, 18, 23, 23, 80, 95, 116, 48, 48, 63, 46, 46, 66, 78, 87, 108, 61, 77, 85, 54, 66, 81, 70, 75·94, 58, 72, 87, 34, 50, 51, 86, 106, 120, 79,97, 116 58, 67, 83 The message starts with the word "CLASSIFIED use...

  • C++ Code

    "For two thousand years, codemakers have fought to preserve secrets while codebreakers have tried their best to reveal them." - taken from Code Book, The Evolution of Secrecy from Mary, Queen of Scots to Quantum Cryptography by Simon Singh.The idea for this machine problem came from this book.You will encrypt and decrypt some messages using a simplified version of a code in the book. The convention in cryptography is to write the plain text in lower case letters and the encrypted text in upper case...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT