Question

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 her public key, ??, by raising g to ?? and then taking mod p. Bob similarly computes his
own public key ?? by raising g to ?? and then taking mod p. Alice and Bob then exchange their public
keys over the Internet. Alice then calculates the shared secret key ? by raising ?? to ?? and then taking
mod p, i.e., ??
?? mod ?. Similarly, Bob calculates the shared secret key S’ by raising ?? to ?? and then
taking mod p, i.e., ??
?? mod ?.
In this assignment we will simulate the existence of two parties, a client and a server, that use public key
encryption to exchange a session key that will be used to encrypt data using the simplified AES
algorithm. Your server will create a string containing its name (e.g., “Server of John A. Smith”) and then
begin accepting connections from clients. Your client should first accept two integers from the
keyboard--one a prime number, ?, between 257 and 1021, and the other, ?, called a generator that is
strictly less than the prime. Your program will ensure that these numbers satisfy the relationship that
?? mod ? can generate all integers between 1 and (? − 1) for all ? between 1 and (? − 1). Some pairs
of numbers (?, ?) for which this is true include (3, 257), (5, 743), (11, 769), (5, 907), etc. Once you have
collected these numbers and they are valid, open a TCP socket to your server and send a message
containing the string “110 Hello” and then wait for a server reply. The server should reply to your
message with the string “110 Hello”. After the server acknowledges the client’s “Hello”, the client should
send a packet with the string “110 Generator: ” concatenated with the generator integer, which in turn
2
is concatenated with the string “, Prime: ” followed by the prime. The server will acknowledge this
message with the string “111 Generator and Prime Rcvd”. The client and server will then separately
compute their private and public keys by calling the appropriate methods, which are provided for you.
The client should then send a packet with the string “120 PubKey ” concatenated with the client’s public
key. The server will acknowledge this packet with the string “120 PubKey ” followed by the server’s
public key. Next, the client will generate a random integer, a nonce, and encrypt it with the server’s
public key. The client will send a packet with the string “130 Ciphertext ” followed by the encrypted
nonce. The server will extract the encrypted nonce, decrypt it, subtract 5 from the number and then
encrypt the transformed nonce with the client’s public key. The server will send a packet with the string
“130 Ciphertext ” followed by the transformed and encrypted nonce. Once the client receives this
message, it should print out a status message of “150 OK” if the absolute value of the difference
between the decrypted nonce and the original nonce is 5. Otherwise you should print “400 OK” to the
console. At this point, both the client and the server should print out ?, ?, their respective public keys,
their respective private keys, and the other process’s public key. If the status message is “150 OK,” the
client can then request that the server rolls all five dice with a “200 Roll Dice” message.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#!/usr/bin/python3


import socket
import math
import random
import sys
import time
import simplified_AES
import hashlib


def expMod(b,n,m):
    """Computes the modular exponent of a number returns (b^n mod m)"""
    if n==0:
        return 1
    elif n%2==0:
        return expMod((b*b)%m, n/2, m)
    else:
        return(b*expMod(b,n-1,m))%m

def IsValidGenerator(g, p):
    """Validation of generator and prime"""
    """Write code to validate the generator and prime"""
    pass

def serverHello():
        """Sends server hello message"""
        status = "100 Hello"
        return status

def sendGeneratorPrime(g,p):
        """Sends server generator"""
        status = "110 Generator: " + str(g) + ", Prime: " + str(p)
        return status

def computeSecretKey(g, p):
        """Computes this node's secret key"""
        secretKey = random.randint(int(g), int(p))
        return secretKey

def computePublicKey(g, p, s):
    """Computes a node's public key"""
    """Complete this function"""
    pass

def sendPublicKey(g, p, s):
    """Sends node's public key"""
    status = "120 PubKey " + str(computePublicKey(g, p, s))
        return status

def generateNonce():
        """This method returns a 16-bit random integer derived from hashing the
                current time. This is used to test for liveness"""
        hash = hashlib.sha1()
        hash.update(str(time.time()).encode('utf-8'))
        return int.from_bytes(hash.digest()[:2], byteorder=sys.byteorder)

# M   = message, an integer
# Pub = receiver's public key, an integer
# p   = prime number, an integer
# gen = generator, an integer
def encryptMsg(M, Pub, p, gen):
        """Encrypts a message M given parameters above"""
        k = random.randint(1,p-1)
        return expMod(gen,k,p), M*expMod(Pub,k,p)

# C    = second part of ciphertext, an integer
# s    = first part of ciphertext, an integer
# priv = sender's public key, an integer
# p    = prime number, an integer
def decryptMsg(C, s, priv, p):
        """Decrypts a message C given parameters above"""
        return int(C/expMod(s,priv,p))

# M   = message, an integer
# Pub = receiver's public key, an integer
# p   = prime number, an integer
# gen = generator, an integer
def sendEncryptedMsg(M, Pub, p, gen):
        """Sends encrypted message """
        y1, y2 = encryptMsg(M, Pub, p, gen)
        status = "130 Ciphertext " + str(int(y1)) +" " + str(int(y2))
        return status

def RollDice():
    """Generates message to get server to roll some or all dice."""
    toRoll = input('Roll all the dice? (y/n): ')
    toRoll = str(toRoll)
    if toRoll == 'y' or toRoll == 'Y':
        status = "200 Roll Dice"
    else:
                print("You exited the game!")
        status = ""
    return status
    
def make_bid(state):
    """This function determines whether the bid made is valid and
       returns a status.
    """
        bid  = state['lastBid']    
    bid = list(map(int,bid)) 
        status = -1
    frequency = bid[0]
    value = bid[1]
        
        face = input('Enter face value for your bid. Enter 0 to challenge: ')
    numFaces = input('Enter number of face value in your bid. Enter 0 to challenge: ')
        if (face !=0 and numFaces !=0):
                if (numFaces > frequency or face > value):
                        status = 1
                else:
                        print("Last bid was invalid")
                        face = input('Enter face value for your bid. Enter 0 to challenge: ')
                        numFaces = input('Enter number of face value in your bid. Enter 0 to challenge: ')
                        status=1
        bid[0] = numFaces
        bid[1] = face
        state['lastBid'] = bid
        return status

def MakeBidMsg(state):
    """Generates message to send a bid to the server."""
        """A bid of '300 Bid 0 0' is a challenge. """
        make_bid(state)
        bid  = state['lastBid']    
    bid = list(map(int,bid)) 
        status = "300 Bid " + str(bid[1]) + " " + str(bid[0])
    return status  

def challenge(roll, msg):
    """This function processes messages that are read through the socket. It
    receives the client's roll and shows the server's roll. It also determines
    whether or not the challenge made is valid and returns a status.
    """

    """You will need to complete this method """
    
    print('Client roll is: ' + roll)
    print('Opponent\'s roll is: ' + msg[8])



# s       = socket
# msg     = initial message being processed
def processMsgs(s, msg, state):
    """This function processes messages that are read through the socket. It
        returns a status, which is an integer indicating whether the operation
        was successful"""
        
    status = -2
        gen = int(state['gen'])                         # integer generator
        prime = int(state['prime'])                     # integer prime
        sKey = int(state['SecretKey'])          # secret key
        rcvrPK = int(state['RcvrPubKey'])       # receiver's public key
        nonce = int(state['nonce'])                     # Number used only once
    bids = int(state['Bids'])           # bids       = number of bids made
    dice  = state['Dice']               # Dice = values of dice
    dice = list(map(int,dice))          # Converting dice values to ints

    strTest = serverHello()
    if (strTest in msg and status==-2):
        msg = ##Complete this line
        print("Message sent: " + msg)
        s.sendall(bytes(msg,'utf-8'))
        status = 1
    
    strTest = "111 Generator and Prime Rcvd"
    if (strTest in msg and status==-2):
        msg = ##Complete this line
        s.sendall(bytes(msg, 'utf-8'))
        status = 1
    
    strTest = "120 PubKey"
    if (strTest in msg and status==-2):
        RcvdStr = msg.split(' ')
        rcvrPK = int(RcvdStr[2])
        nonce = generateNonce()
        while (nonce >= prime):
            nonce = generateNonce()
        msg = ##Complete this line.
        print("Message sent: " + str(msg))
        s.sendall(bytes(msg, 'utf-8'))
        state['nonce'] = nonce
        state['RcvrPubKey'] = rcvrPK
        status = 1
    
    strTest = "130 Ciphertext"
    if (strTest in msg and status==-2):
        Pub = computePublicKey(gen, prime, sKey)
        RcvdStr = msg.split(' ')
        y1 = int(RcvdStr[2])
        srvrCtxt = int(RcvdStr[3])
        print("Ciphertext received: " + str(y1) +"," + str(srvrCtxt))
        dcryptedNonce = decryptMsg(srvrCtxt, y1, sKey, prime)
        if (abs(nonce - dcryptedNonce) == 5):
            print("Final status code: 150 OK")
        else:
            print("Final status code: 400 Error")
        status = 0              # To terminate loop at client.
    
    strDiceRoll = "205 Roll Dice ACK"
    if (strDiceRoll in msg and status==-2):
        DiceValues = msg[18:].split(',')
        if bids < 2:
            msg = MakeBidMsg(state):
            s.sendall(bytes(msg,'utf-8'))
            bids += 1
            status = 1
        else:
            status = 0
        state['Bids'] = bids
    
    strBidAck = "305 Bid ACK"
    if (strBidAck in msg and status==-2):
        print("Message received: " + msg)
        BidReceived = msg[12:].split(' ')
        if bids < 2:
            msg = MakeBidMsg(state):
            s.sendall(bytes(msg,'utf-8'))
            bids += 1
            status = 1
        else:
            status = 0
        state['Bids'] = bids
    
    strSuccess = "150 OK"
    strFailure = "400 Error"
    if ((strSuccess in msg or strFailure in msg) and status==-2):
                status = 0 # To terminate loop at client
        
        if status==-2:
                print("Incoming message was not processed. \r\n Terminating")
                status = -1
        return status                

def main():
        """Driver function for the project"""
        args = sys.argv
        if len(args) != 3:
                print ("Please supply a server address and port.")
                sys.exit()
        serverHost = str(args[1])       # The remote host
        serverPort = int(args[2])       # The same port as used by the server
        print("\nClient of _____")
        print('''
        The dice in this program have a face value in the range 1--6.
        No error checking is done, so ensure that the bids are in the correct range.
        Follow the on-screen instructions.
        ''')
        random.seed()
        dice = [random.randint(1,6), random.randint(1,6), random.randint(1,6),
            random.randint(1,6),random.randint(1,6)]
        
        while (True):
                prime = int(input('Enter a valid prime between 1024 and 65536: '))
                generator = int(input('Enter a positive integer less than the prime just entered: '))
                if (IsValidGenerator(generator, prime)): break
        nonce = generateNonce()
        # To ensure that the nonce can always be encrypted correctly.
        while (nonce >= prime):
                nonce = generateNonce()

    bids = 0
        lastBid = [0,0]
        # Bogus values that will be overwritten with values read from the socket.
        secretKey = computeSecretKey(generator, prime)
        rcvrPK = 60769
        state = {'prime': prime, 'gen': generator, 'SecretKey': secretKey,
        'RcvrPubKey': rcvrPK, 'nonce': nonce, 'LastBid': lastBid, , 'Bids': bids,
        'Dice': dice}
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((serverHost, serverPort))
        msg = serverHello()
        s.sendall(bytes(msg,'utf-8'))
        status = 1
        while (status==1):
                msg = s.recv(1024).decode('utf-8')
                if not msg:
                        status = -1
                else:
                        status = processMsgs(s, msg, state)
        if status < 0:
                print("Invalid data received. Closing")
        s.close()

if __name__ == "__main__":
        main()
Add a comment
Know the answer?
Add Answer to:
The Diffie-Hellman public-key encryption algorithm is an alternative key exchange algorithm that is used by protocols...
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
  • Question1: Alice and Bob use the Diffie–Hellman key exchange technique with a common prime q =...

    Question1: Alice and Bob use the Diffie–Hellman key exchange technique with a common prime q = 1 5 7 and a primitive root a = 5. a. If Alice has a private key XA = 15, find her public key YA. b. If Bob has a private key XB = 27, find his public key YB. c. What is the shared secret key between Alice and Bob? Question2: Alice and Bob use the Diffie-Hellman key exchange technique with a common...

  • 5. Diffie-Hellman key exchange. Alice and Bob use Diffie-Hellman key exchange protocol to communicate in secret....

    5. Diffie-Hellman key exchange. Alice and Bob use Diffie-Hellman key exchange protocol to communicate in secret. They publicly announce a prime number p = 23 and a primitive root r = 5 under modulus 23, Alice picks a secret key a-6 and in turn receive the key ß-19 from Bob (a.) (2 points) What is the key that Alice sends to Bob? b) (2 points) What is the shared secret key?

  • For client and server communication By using Diffe and Helman algorithm(DH) generate a secret session key(k)...

    For client and server communication By using Diffe and Helman algorithm(DH) generate a secret session key(k) from both sides (from client and server separately) by using Java .and also by accepting some message from client by using the generated secret session key (K) encrypt the message from client-side and send to server and server uses the generated secret session key(k) of his own and decrypt the received encrypted message in java. thanks in advance.

  • Alan and Bill agree (through a public exchange) on using the Diffie-Hellman algorithm to create a...

    Alan and Bill agree (through a public exchange) on using the Diffie-Hellman algorithm to create a common secret key. They also agree on two public numbers: q (large prime number),  (generator mod q): q = 13,  = 3 Alan generates a random RA =11. Bill generates a random RB =13. (a) What is the SA Alan sends to Bill? (i.e. SA =? (3 points) (b) What is the SB Bill sends to Alan? (i.e. SB =? (3 points)...

  • Diffie-Hellman Key Exchange: Alice and Bob wants to agree on a key. First, both agree on...

    Diffie-Hellman Key Exchange: Alice and Bob wants to agree on a key. First, both agree on p = 23 and g = 5 which is public. Alice chooses her secret key xA = 8 and Bob xB = 14. (a) What will be the shared secret key? (b) DH Key exchange is vulnerable to the following attack. Adversary sits between Alice and Bob, intercepting all messages. Alice and Bob thinks they talk to each other while in fact both talking...

  • 1. In a scenario where Nancy and Matthew are using public key encryption, which keys will...

    1. In a scenario where Nancy and Matthew are using public key encryption, which keys will Matthew have the ability to see in his public keyring (--list-keys)? 2.    If Nancy wishes to send a message to Matthew, which key does she use to encrypt the message? 3.    If Matthew receives an encrypted message from Nancy, which key does he use to read it?   4.    If Matthew wishes to send a message to Nancy, which key does he use to encrypt...

  • 1. (a) Explain the terms “data encryption, authentication, and message integrity,” often used in the networks...

    1. (a) Explain the terms “data encryption, authentication, and message integrity,” often used in the networks security literature. (3 Points) (b) Lorenzo likes to send to his close friend Art a secret market data related to their business using public key cryptography (RSA algorithm). He chooses two prime numbers 7 and 11, and a public key e = 13 to encrypt the data. Art uses d=37 to decrypt the data. Indicate why (e, 77) and (d, 77) are valid public...

  • In a RSA cryptosystem, a participant A uses two prime numbers p = 13 and q...

    In a RSA cryptosystem, a participant A uses two prime numbers p = 13 and q = 17 to generate her public and private keys. If the public key of A is 35, then the private key of A is 11. Alice wants to encrypt a message to Bob by using the RSA algorithm and using keys in (A) The plaintext = “HI”. Answer: _______________

  • prime factorization. Assume that zoy wants to send a message to sam. sam generates public and...

    prime factorization. Assume that zoy wants to send a message to sam. sam generates public and private keys using RSA Encryption algorithm and publishes the public key (n=4717, e=19). zoy has a secret message M to send. Nobody knows the value of M. She encrypts the message M using the public key and sends the encrypted message C=1466 to sam. alex is an intruder who knows RSA and prime factorization well. She captures the encrypted message C=1466. She also has...

  • 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...

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