Exemple #1
0
 def test_keygen_stdout(self):
   with contextlib.nested(mock.patch("sys.stdout"),
                          mock.patch("random.randint")) as (cout, rmock):
     rmock.side_effect=random.Random(34).randint
     stdout = StringIO.StringIO()
     cout.write = stdout.write
     rsa.keygen(["", "12", "-"])
     self.assertEquals(cPickle.loads(stdout.getvalue()).GetPublicKey(), 
                       self.key.GetPublicKey())
     self.assertEquals(cPickle.loads(stdout.getvalue()), self.key)
Exemple #2
0
 def test_keygen(self):
   with contextlib.nested(mock.patch("__builtin__.open"),
                          mock.patch("random.randint")) as (opener, rmock):
     rmock.side_effect=random.Random(34).randint
     opener.side_effect = self.opener_fxn
     rsa.keygen(["", "12", "key"])
     self.assertEquals(cPickle.loads(self.files["key"][0].getvalue()).GetPublicKey(), 
                       self.key.GetPublicKey())
     self.assertEquals(cPickle.loads(self.files["key"][0].getvalue()), 
                       self.key)
Exemple #3
0
  def test_too_short(self):
    with contextlib.nested(mock.patch("__builtin__.open"),
                           mock.patch("sys.stderr"),
                           mock.patch("random.randint")) as (opener, cerr, rmock):
      stderr = StringIO.StringIO()
      rmock.side_effect=random.Random(34).randint
      opener.side_effect = self.opener_fxn
      cerr.write = stderr.write

      rsa.keygen(["", "7", "key"])
      self.assertEquals(self.files["key"][0].getvalue(), "")

      rmock.side_effect=random.Random(34).randint
      rsa.keygen(["", "8", "key"])
      rmock.side_effect=random.Random(34).randint
      shortkey = rsa.RSAPrivateKey(8)
      self.assertEquals(cPickle.loads(self.files["key"][0].getvalue()).GetPublicKey(), 
                        shortkey.GetPublicKey())
      self.assertEquals(cPickle.loads(self.files["key"][0].getvalue()), shortkey)
      self.assertEquals(cPickle.loads(self.files["key.pub"][0].getvalue()),
                        shortkey.GetPublicKey())
Exemple #4
0
def process_rsa(args):
    if (args.mode.lower() == "keygen"):
        filename_pub = args.public_key if args.public_key != None else "key.pub"
        filename_priv = args.private_key if args.private_key != None else "key.priv"
        key_length = int(args.key_length) if args.key_length != None else 32

        rsa.keygen(filename_pub, filename_priv, length=key_length)
    elif (args.mode.lower() == "encrypt") or (args.mode.lower() == "decrypt"):
        if args.file == None:
            raise Exception("No file input on " + args.mode + "ion process")
        if (args.mode.lower() == "encrypt") and args.public_key == None:
            raise Exception("No public key given on " + args.mode +
                            "ion process")
        if (args.mode.lower() == "decrypt") and args.private_key == None:
            raise Exception("No private key given on " + args.mode +
                            "ion process")
        output = args.output if args.output != None else "result.encrypted"

        data = open(args.file, 'rb').read()
        print("Plaintext:\n", data)

        if args.mode.lower() == "encrypt":
            key = rsa.RSAPublicKey(from_file=True, filename=args.public_key)
            enc = True
        else:
            key = rsa.RSAPrivateKey(from_file=True, filename=args.private_key)
            enc = False

        result = rsa.process(encrypt=enc, data=data, RSA_key=key)

        print("Ciphertext:\n", binascii.hexlify(result))
        print("Size:", len(result), 'bytes')
        with open(output, 'wb') as fout:
            fout.write(result)

    else:
        raise Exception("Unsupported Mode " + args.cipher)
Exemple #5
0
    return decrypted_data


#e,d,c=rsa.keygen()
# e,d,c=7,23,187

host = '127.0.0.1'
port = 5000

clients = []

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)

pu, pr, m = rsa.keygen()

ser_pub_key = "`" + str(pu) + "," + str(m) + "`"
ser_pvt_key = (pr, m)

quitting = False
print("Server Started.")
while not quitting:
    try:
        key_received = False
        name_received = False
        current_data, addr = s.recvfrom(1024)
        # print(current_data, addr)

        data = current_data.decode("utf-8")
Exemple #6
0
    Decrypts input integer list into sentences
    """
    # print("Decrypting")
    words = data.split(",")
    decrypted_data = ""
    for i in range(0, len(words) - 1):
        decrypted_data += str(
            rsa.decode(rsa.endecrypt(words[i], public[0], public[1])))
    decrypted_data = decrypted_data.replace("'b'", "")
    decrypted_data = decrypted_data.replace("b'", "")
    decrypted_data = decrypted_data.replace("'", "")
    # print("Decrypted Data: ",decrypted_data)
    return decrypted_data


e, d, c = rsa.keygen()
print("Key generated: ", e, d, c)
clt_pub_key = (e, c)
clt_pvt_key = (d, c)


def receving(name, sock):
    while not shutdown:
        try:
            tLock.acquire()
            while True:
                data, addr = sock.recvfrom(1024)
                data = data.decode("utf-8")
                if (data[0] is "`" and data[-1] is "`"):
                    data = data[1:-1].split(",")
                    global ser_pub_key
Exemple #7
0
	def __init__(self):
		self.pubKey, self.privkey = rsa.keygen()
Exemple #8
0
'''
Approach based on Bleichenbacher's math
Currently broken
'''
def alternateForgeSignature(message, pubKey, hashFunction=hash.sha256):
	if pubKey[0] != 3:
		raise Exception("Cannot forge a signature for e != 3")

	blockLen = rsa.getBlocklen(pubKey)
	digestInt = hashFunction(message)

	hashLen = len(chr(0)+convert.intToByteString(digestInt))*8
	bitLen = blockLen*8

	dec.getcontext().prec = bitLen

	N = pow(2, hashLen) - digestInt

	cubeRoot = dec.Decimal(2)** (dec.Decimal(bitLen-15)/dec.Decimal(3.0)) - dec.Decimal(N) * dec.Decimal(2)**(dec.Decimal(bitLen-24-hashLen) - dec.Decimal((bitLen-15)*2)/dec.Decimal(3))

	print repr(convert.intToByteString(digestInt))
	print repr(convert.intToByteString(pow(int(cubeRoot), 3)))

	return rsa.decodeCiphertext([cubeRoot], pubKey)


if __name__ == "__main__":
	message = "hi mom"
	pubKey, _ = rsa.keygen()
	fakeSignature = forgeSignature(message, pubKey)
	print rsa.flawedCheckSignature(message, fakeSignature, pubKey)
Exemple #9
0
def Server(host, port):
    """
    Creates the server instance, sets up the server
    """

    port = int(port)

    try:
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((host, port))
        server.listen(5)

        print "* Waiting for partner to join conversation... *\n"
        conn, client_addr = server.accept()

        # print "Client connected: ", client_addr[0]
        print "* Client is attempting to connect... *\n"
    except Exception:
        pass

    # Waiting to receive client's public key
    recvIsComplete = False
    key = ""
    while not recvIsComplete:
        key += conn.recv(1024)
        if key.strip("~") and key[0] == "~" and key[-1] == "~":
            recvIsComplete = True

    key = key.strip("~").split(',')
    publicTuple = (key[0], key[1])
    print "* Client\'s Public Key received *"
    # Send public key to client
    e, d, c = RSA.keygen()
    sendPublic = str(d) + ',' + str(c)
    sendPrivate = str(e) + ',' + str(c)
    conn.send("~" + sendPublic + "~")
    print "Public and Private Keys are: " + '(' + sendPublic + ')' + ',' + '(' + sendPrivate + ')' + ' e: ' + str(
        e) + ' d: ' + str(d) + ' c: ' + str(c)
    print "* Public Key sent *"

    privateTuple = (e, c)
    # To check encrryptionwe are receiving the test string
    recvIsComplete = False
    data = ""
    while not recvIsComplete:
        data += conn.recv(1024)
        if data.strip("~") and data[0] == "~" and data[-1] == "~":
            recvIsComplete = True
    data = decrypt(data.strip("~"), publicTuple)
    if data != "~Client:abcdefghijklmnopqrstuvwxyz~":
        # print "data: ", data
        print "\n* Encryption could not be verified! Please try to reconnect... *\n"
        conn.send("~ABORT~")
        connClose(conn)
        return

    # Sending test string to make sure encryption is working properly
    data = "~Server:abcdefghijklmnopqrstuvwxyz~"
    data = encrypt(data.strip(), privateTuple)
    conn.send("~" + data + "~")

    # # Receving test string to make sure encryption is working properly
    # recvIsComplete = False
    # data = ""
    # while not recvIsComplete:
    #     data += conn.recv(1024)
    #     if data.strip("~") and data[0] == "~" and data[-1] == "~":
    #         recvIsComplete = True
    # if data != "~ABORT~":
    #     print "\n* Encryption Verified! *"
    # else:
    #     print "\n* Encryption could not be verified! Please try to reconnect... *\n"
    #     connClose(conn)
    #     return

    print "\n* Connected to chat *\n*"
    '''
    print "1. Type your messages below and hit Enter to send"
    print "2. Type \'file()\' and hit Enter to send a file in the current directory"
    print "3. Type \'quit()\' and hit Enter to leave the conversation\n"
    '''

    ReadThread = Thread_Manager('read', conn, publicTuple, None)
    WriteThread = Thread_Manager('write', conn, None, privateTuple)

    ReadThread.start()
    WriteThread.start()
    # Wait until client disconnects
    ReadThread.join()
    print "\n* Your partner has left the conversation. Press any key to quit... *\n "

    # Stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # Shut down client connection
    try:
        conn.shutdown(socket.SHUT_RDWR)
        conn.close()
    except:
        # Connection already closed
        pass

    # Shut down server
    connClose(server)
Exemple #10
0
def Client(host, port):
    """
    Creates the client instance, sets up the client
    """

    port = int(port)

    print "\n* Connecting to server... *\n"
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))

    # Send public key to server
    e, d, c = RSA.keygen()

    sendPublic = str(d) + "," + str(c)
    client.send("~" + sendPublic + "~")
    print "* Public Key sent *"

    # Wait to receive server's public key
    recvIsComplete = False
    key = ""
    while not recvIsComplete:
        key += client.recv(1024)
        if key.strip("~") and key[0] == "~" and key[-1] == "~":
            recvIsComplete = True

    key = key.strip("~").split(',')
    publicTuple = (key[0], key[1])
    print "* Server\'s Public Key received *"

    privateTuple = (e, c)

    # Sending test string to make sure encryption is working properly
    data = "~Client:abcdefghijklmnopqrstuvwxyz~"
    data = encrypt(data.strip(), privateTuple)
    client.send("~" + data + "~")

    # Receving test string to make sure encryption is working properly
    recvIsComplete = False
    data = ""
    while not recvIsComplete:
        data += client.recv(1024)
        if data.strip("~") and data[0] == "~" and data[-1] == "~":
            recvIsComplete = True

    if data != "~ABORT~":
        data = decrypt(data.strip("~"), publicTuple)
    if data != "~Server:abcdefghijklmnopqrstuvwxyz~":
        # print "data: ", data
        print "\n* Encryption could not be verified! Please try to reconnect... *\n"
        client.send("~ABORT~")
        connClose(client)
        return
    else:
        print "\n* Encryption Verified! *"

    print "\n* Connected to chat *\n*"
    '''
    print "1. Type your messages below and hit Enter to send"
    print "2. Type \'file()\' and hit Enter to send a file in the current directory"
    print "3. Type \'quit()\' and hit Enter to leave the conversation\n"
    '''

    ReadThread = Thread_Manager('read', client, publicTuple, None)
    WriteThread = Thread_Manager('write', client, None, privateTuple)

    ReadThread.start()
    WriteThread.start()

    ReadThread.join()
    print "\n* Your partner has left the conversation. Press any key to quit... *\n"

    # Stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # Shut down client connection
    connClose(client)
def Server(host, port):
    """
    Creates the server instance, sets up the server
    """

    port = int(port)

    try:
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((host, port))
        server.listen(5)

        print "* Waiting for partner to join conversation... *\n"
        conn, client_addr = server.accept()

        # print "Client connected: ", client_addr[0]
        print "* Client attempting to connect... *\n"
    except Exception:
        pass

    # Wait to receive client's public key
    recvIsComplete = False
    key = ""
    while not recvIsComplete:
        key += conn.recv(1024)
        if key.strip("~") and key[0] == "~" and key[-1] == "~":
            recvIsComplete = True

    key = key.strip("~").split(',')
    publicTuple = (key[0], key[1])
    print "* Client\'s Public Key received *"

    # Send public key to client
    e, d, c = RSA.keygen()
    sendPublic = str(d) + ',' + str(c)
    conn.send("~" + sendPublic + "~")
    print "* Public Key sent *"

    privateTuple = (e, c)

    # Receving test string to make sure encryption is working properly
    recvIsComplete = False
    data = ""
    while not recvIsComplete:
        data += conn.recv(1024)
        if data.strip("~") and data[0] == "~" and data[-1] == "~":
            recvIsComplete = True
    data = decrypt(data.strip("~"), publicTuple)
    if data != "~Client:abcdefghijklmnopqrstuvwxyz~":
        # print "data: ", data
        print "\n* Encryption could not be verified! Please try to reconnect... *\n"
        conn.send("~ABORT~")
        connClose(conn)
        return

    # Sending test string to make sure encryption is working properly
    data = "~Server:abcdefghijklmnopqrstuvwxyz~"
    data = encrypt(data.strip(), privateTuple)
    conn.send("~" + data + "~")

    # # Receving test string to make sure encryption is working properly
    # recvIsComplete = False
    # data = ""
    # while not recvIsComplete:
    #     data += conn.recv(1024)
    #     if data.strip("~") and data[0] == "~" and data[-1] == "~":
    #         recvIsComplete = True
    # if data != "~ABORT~":
    #     print "\n* Encryption Verified! *"
    # else:
    #     print "\n* Encryption could not be verified! Please try to reconnect... *\n"
    #     connClose(conn)
    #     return

    print "\n* Connected to chat *\n*"
    print "1. Type your messages below and hit Enter to send"
    print "2. Type \'file()\' and hit Enter to send a file in the current directory"
    print "3. Type \'quit()\' and hit Enter to leave the conversation\n"

    ReadThread = Thread_Manager('read', conn, publicTuple, None)
    WriteThread = Thread_Manager('write', conn, None, privateTuple)

    ReadThread.start()
    WriteThread.start()

    # Wait until client disconnects
    ReadThread.join()
    print "\n* Your partner has left the conversation. Press any key to quit... *\n "

    # Stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # Shut down client connection
    try:
        conn.shutdown(socket.SHUT_RDWR)
        conn.close()
    except:
        # Connection already closed
        pass

    # Shut down server
    connClose(server)
def Client(host, port):
    """
    Creates the client instance, sets up the client
    """

    port = int(port)

    print "\n* Connecting to server... *\n"
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, port))

    # Send public key to server
    e, d, c = RSA.keygen()
    sendPublic = str(d) + "," + str(c)
    client.send("~" + sendPublic + "~")
    print "* Public Key sent *"

    # Wait to receive server's public key
    recvIsComplete = False
    key = ""
    while not recvIsComplete:
        key += client.recv(1024)
        if key.strip("~") and key[0] == "~" and key[-1] == "~":
            recvIsComplete = True

    key = key.strip("~").split(',')
    publicTuple = (key[0], key[1])
    print "* Server\'s Public Key received *"

    privateTuple = (e, c)

    # Sending test string to make sure encryption is working properly
    data = "~Client:abcdefghijklmnopqrstuvwxyz~"
    data = encrypt(data.strip(), privateTuple)
    client.send("~" + data + "~")

    # Receving test string to make sure encryption is working properly
    recvIsComplete = False
    data = ""
    while not recvIsComplete:
        data += client.recv(1024)
        if data.strip("~") and data[0] == "~" and data[-1] == "~":
            recvIsComplete = True

    if data != "~ABORT~":
        data = decrypt(data.strip("~"), publicTuple)
    if data != "~Server:abcdefghijklmnopqrstuvwxyz~":
        # print "data: ", data
        print "\n* Encryption could not be verified! Please try to reconnect... *\n"
        client.send("~ABORT~")
        connClose(client)
        return
    else:
        print "\n* Encryption Verified! *"

    print "\n* Connected to chat *\n*"
    print "1. Type your messages below and hit Enter to send"
    print "2. Type \'file()\' and hit Enter to send a file in the current directory"
    print "3. Type \'quit()\' and hit Enter to leave the conversation\n"

    ReadThread = Thread_Manager('read', client, publicTuple, None)
    WriteThread = Thread_Manager('write', client, None, privateTuple)

    ReadThread.start()
    WriteThread.start()

    ReadThread.join()
    print "\n* Your partner has left the conversation. Press any key to quit... *\n"

    # Stop the write thread
    WriteThread.stopWrite()
    WriteThread.join()

    # Shut down client connection
    connClose(client)
Exemple #13
0
	def __init__(self):
		self.prevMessages = set()
		self.pubkey, self.privkey = rsa.keygen()
Exemple #14
0
'''
def extractPlaintext(ctext0, modulus0, ctext1, modulus1, ctext2, modulus2):
	ms0 = modulus1 * modulus2
	ms1 = modulus0 * modulus2
	ms2 = modulus1 * modulus0

	N = modulus0 * modulus1 * modulus2

	result = ((ctext0 * ms0 * rsa.modInverse(ms0, modulus0)) +
	         (ctext1 * ms1 * rsa.modInverse(ms1, modulus1)) +
			 (ctext2 * ms2 * rsa.modInverse(ms2, modulus2))) % N
	return cubeRoot(result)

if __name__ == "__main__":
	plaintext = "This is good"

	pubkey0, _ = rsa.keygen()
	pubkey1, _ = rsa.keygen()
	pubkey2, _ = rsa.keygen()

	ctext0 = rsa.encodeCiphertext(rsa.encryptString(plaintext, pubkey0), pubkey0)
	ctext1 = rsa.encodeCiphertext(rsa.encryptString(plaintext, pubkey1), pubkey1)
	ctext2 = rsa.encodeCiphertext(rsa.encryptString(plaintext, pubkey2), pubkey2)

	newplaintext = extractPlaintext(ctext0[0], pubkey0[1], ctext1[0], pubkey1[1], ctext2[0], pubkey2[1])

	newTextPlaintext = padding.stripPkcs7(convert.intToByteString(newplaintext))
	
	print newTextPlaintext == plaintext