Exemplo n.º 1
0
    def runTest(self):
        key = RSA.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
Exemplo n.º 2
0
    def runTest(self):
        key = RSA.generate(1024)
        hashed = SHA1.new(b("Test"))
        good_signature = PKCS1_PSS.new(key).sign(hashed)
        verifier = PKCS1_PSS.new(key.publickey())

        self.assertEqual(verifier.verify(hashed, good_signature), True)

        # Flip a few bits in the signature
        bad_signature = strxor(good_signature, bchr(1) * len(good_signature))
        self.assertEqual(verifier.verify(hashed, bad_signature), False)
Exemplo n.º 3
0
Arquivo: jws.py Projeto: lxp20201/lxp
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_PSS.new(key)
     res = verifier.verify(h, sig)
     if not res:
         raise BadSignature()
     else:
         return True
Exemplo n.º 4
0
 def verify(self, msg, sig, key):
     h = self.digest.new(msg)
     verifier = PKCS1_PSS.new(key)
     res = verifier.verify(h, sig)
     if not res:
         raise BadSignature()
     else:
         return True
Exemplo n.º 5
0
def sign_file(fi):
    # Read private key file in binary
    with open("master_private.pem", 'rb') as f:
        private_key = RSA.importKey(f.read())
    # Generate nonce
    nonce = str(Random.random.StrongRandom().getrandbits(20)).encode()
    # Hash the file
    hash_file = SHA256.new(fi)
    # RSA signature by using private key
    signature = PKCS1_PSS.new(private_key).sign(hash_file)
    return nonce + signature + fi
Exemplo n.º 6
0
def verify_file(fi):
    '''
    Check nonce first and the verify the signature
    '''
    with open('master_public.pem', 'rb') as f:
        public_key = RSA.importKey(f.read())
    nonce = fi[:6]
    sign = fi[6:518]
    msg = fi[518:]
    hash_msg = SHA256.new(msg)
    if nonce in used_nonce:
        print("Detect Replay Attack!!")
        f.close()
    else:
        used_nonce.append(nonce)
    if PKCS1_PSS.new(public_key).verify(hash_msg, sign):
        return True
    else:
        return False
Exemplo n.º 7
0
Arquivo: jws.py Projeto: lxp20201/lxp
 def sign(self, msg, key):
     h = self.digest.new(msg)
     signer = PKCS1_PSS.new(key)
     return signer.sign(h)
    def _init_signature_verifyer(self):
        pub_key = open(os.path.normpath(self._key_path), "r").read()
        logger.debug("Loaded public key for signature verification")
        rsakey = RSA.importKey(pub_key)

        self._signer = PKCS1_PSS.new(rsakey)
Exemplo n.º 9
0
 def sign(self, msg, key):
     h = self.digest.new(msg)
     signer = PKCS1_PSS.new(key)
     return signer.sign(h)
Exemplo n.º 10
0
if __name__ == '__main__':
    # Generating RSA Key Pair:
    key = RSA.generate(2048)  # Generate a key pair
    pubKey = key.publickey().export_key(
        'PEM')  # Export the public key as encoded as PEM
    keyFile = open('pubKey.pem',
                   'wb')  # Open a new file to save the public key
    keyFile.write(pubKey)  # Save the public key
    keyFile.close()  # Close the file
    # Finished Generating the Key Pair

    # Signing the Message Using the Private Key:
    messageFile = open('message.txt',
                       'r')  # Open the file containing the message for read
    message = messageFile.read()  # Read the message
    messageInByte = str.encode(
        message
    )  # Encode the message to bytes (the API accept text encoded in bytes)
    md5Hash = MD5.new(messageInByte)  # Generate the MD5 hash of the message
    signature = PKCS1_PSS.new(key).sign(
        md5Hash)  # Sign the generated hash using the private RSA key
    signFile = open('signature.txt',
                    'wb')  # Open a new file to save the signature
    signFile.write(signature)  # Write the signature to the file
    signFile.close()
    # Finished Signing the Hash
    print(
        "The public key has been saved to the file 'pubKey.pem'.\nThe signature has been saved to the file 'signature.txt' to be verified in the next part."
    )
Exemplo n.º 11
0
def main():
    # create sockets
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    HOST = socket.gethostname(
    )  # Symbolic name meaning all available interfaces
    PORT = 4321  # Arbitrary non-privileged port

    print('Socket created')

    try:
        s.bind((HOST, PORT))
    except socket.error as msg:
        print('Bind failed')
        sys.exit()

    print('Socket bind complete')

    s.listen(10)
    print('Socket now listening')
    dict = {}

    # say hello to Alice and Bob when they connect
    connAlice, addr = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))
    data = connAlice.recv(1024)
    if data.decode() == 'Alice':
        name = 'Alice'
        dict[addr] = 'Alice'
    else:
        print('Invalid client')
    reply = ('Hello' + name + '! ' + 'This is your connection: ' + addr[0] +
             ':' + str(addr[1]) + '. Please send me your encrypted secret.')

    connAlice.sendall(reply.encode())
    print('I said Hello to Alice')

    connBob, addr = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))
    data = connBob.recv(1024)
    if data.decode() == 'Bob':
        name = 'Bob'
        dict[addr] = 'Bob'
    else:
        print('Invalid client')
    reply = ('Hello' + name + '! ' + 'This is your connection: ' + addr[0] +
             ':' + str(addr[1]) + '. Please send me your encrypted secret.')
    connBob.sendall(reply.encode())
    print('I said Hello to Bob')

    #get homomorphic public key of Alice and Bob
    with open('homomorphic_key.txt') as json_file:
        data = json.load(json_file)
        public_key = paillier.PaillierPublicKey(n=int(data['public_key']))

    # receive Alice's encrypted secret
    AliceJSON = connAlice.recv(4096)
    received_dict = json.loads(AliceJSON)
    cipherAlice = paillier.EncryptedNumber(public_key,
                                           int(received_dict['cipher'][0]),
                                           int(received_dict['cipher'][1]))
    # receive Bob's encrypted secret
    BobJSON = connBob.recv(4096)
    received_dict = json.loads(BobJSON)
    cipherBob = paillier.EncryptedNumber(public_key,
                                         int(received_dict['cipher'][0]),
                                         int(received_dict['cipher'][1]))
    print('I have received Alice and Bob\'s secrets')

    # add them homomorphically
    minus = phe.encoding.EncodedNumber.encode(public_key, -1)
    cipherBob = minus * cipherBob
    added = cipherAlice + cipherBob
    # multiply it by a blinding factor so as to not leak any information
    blinding_factor = random.randint(1, 100000)
    encoded_blinding_factor = phe.encoding.EncodedNumber.encode(
        public_key, blinding_factor)
    added = added * encoded_blinding_factor
    added_secrets = {}
    # using the Server's public key, sign the answer that is to be sent back
    key = RSA.importKey(open("privkey.pem").read())
    h = SHA1.new()

    added_secrets['encrypted'] = str(added.ciphertext()), added.exponent
    h.update(str(added.ciphertext()).encode())
    h.update(str(added.exponent).encode())
    signer = PKCS1_PSS.new(key)
    signature = signer.sign(h)
    added_secrets['signature'] = binascii.hexlify(signature).decode('utf-8')
    answer = json.dumps(added_secrets).encode()
    # now send Alice and Bob the answer, they will decrypt it and find out if the secrets were equal
    try:
        # Set the whole string
        connAlice.sendall(answer)
        print('I have sent Alice the answer')
    except socket.error:
        # Send failed
        print('Send failed')
        sys.exit()
    try:
        # Set the whole string
        connBob.sendall(answer)
        print('I have sent Bob the answer')
    except socket.error:
        # Send failed
        print('Send failed')
        sys.exit()


# close all connections
    connAlice.close()
    connBob.close()
    s.close()
Exemplo n.º 12
0
def main():
    name =argv[1]
    # read the homomorphic public and private keys shared by Alice and Bob
    with open('homomorphic_key.txt') as json_file:
        data = json.load(json_file)
        public_key = paillier.PaillierPublicKey(n=int(data['public_key']))
        private_key = paillier.PaillierPrivateKey(public_key, data['private_key'][0],data['private_key'][1])
    # create an INET, STREAMing socket

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error:
        print('Failed to create socket')
        sys.exit()

    print('Socket Created')

    host = socket.gethostname()
    port = 4321;

    try:
        remote_ip = socket.gethostbyname(host)

    except socket.gaierror:
        # could not resolve
        print('Hostname could not be resolved. Exiting')
        sys.exit()

    # Connect to remote server
    s.connect((remote_ip, port))

    print('Socket Connected to ' + host + ' on ip ' + remote_ip)
    # Saying hello to the server
    message = name

    try:
        # Set the whole string
        s.sendall(message.encode())
    except socket.error:
        # Send failed
        print('Send failed')
        sys.exit()

    print('Message sent successfully')

    # Now receive data
    reply = s.recv(4096)

    print(reply)

    # encrypt the secret message with the homomorphic public key
    secret_message = int(argv[2])
    cipher = public_key.encrypt(secret_message)
    secret = {}
    secret['cipher'] = (str(cipher.ciphertext()), cipher.exponent)
    serialised = json.dumps(secret).encode()

    try:
        # Set the whole string
        # print(serialised)
        s.sendall(serialised)
        print('I have sent the encrypted secret')
    except socket.error:
        # Send failed
        print('Send failed')
        sys.exit()

    # Now receive the answer back from the server
    reply = s.recv(4096)
    # print(reply)
    received_dict = json.loads(reply)
    answer = paillier.EncryptedNumber(public_key, int(received_dict['encrypted'][0]),
                                         int(received_dict['encrypted'][1]))

    # first check the signature, Alice has access to the verification key of the Server
    key = RSA.importKey(open("pubkey.pem").read())
    h = SHA1.new()
    h.update(received_dict['encrypted'][0].encode())
    h.update(str(received_dict['encrypted'][1]).encode())
    signature =binascii.unhexlify(received_dict['signature'].encode('utf-8'))
    verifier = PKCS1_PSS.new(key)
    if verifier.verify(h, signature):
        print("The signature is authentic.")
    else:
        print("The signature is not authentic.")
    # now decrypt the answer using private key, if it is 0 then strings were equal otherwise unequal

    key_decrypt = private_key.decrypt(answer)
    if key_decrypt==0:
        print("The strings were equal!")
    else:
        print("The strings were unequal!")

    # close connections
    s.close()
Exemplo n.º 13
0
# *** Important Note: This part should be executed only after executing 'part1.2.py' ***
from Cryptodome.PublicKey import RSA
from Cryptodome.Signature import PKCS1_PSS
from Cryptodome.Hash import MD5

if __name__ == '__main__':
    # Verifying the Signature Generated From part1.2
    keyFile = open('pubKey.pem',
                   'r')  # Open the file containing the public key
    pubKey = RSA.import_key(keyFile.read(
    ))  # Importing the public key from the file created in the previous part
    verifier = PKCS1_PSS.new(pubKey)  # Creating a verifier with the public key
    messageFile = open('message.txt',
                       'r')  # Open the file containing the message for read
    message = messageFile.read()  # Read the message
    messageInByte = str.encode(
        message
    )  # Encode the message to bytes (the API accept text encoded in bytes)
    md5Hash = MD5.new(messageInByte)  # Generate the MD5 hash of the message
    signFile = open('signature.txt',
                    'rb')  # Open the file containing the signature for read
    signature = signFile.read()  # Saving the signature
    isAuth = verifier.verify(
        md5Hash,
        signature)  # Checking wether the signature is authentic or not
    if (isAuth):
        print("The signature is authentic.")
    else:
        print("The signature is not authentic.")
    # Finished Verifying