示例#1
0
def test_RSA(inverse,
             message="The quick brown fox jumps over the lazy dog.",
             bit_length=4096,
             e=65537,
             powmodn=bit_pow_mod_n):

    print("Generating ", bit_length, "-bit primes...")

    scheme = RSA(powmodn=powmodn, inverse=inverse, gmp=True)
    (p, q, n, l, e, d, public_key,
     private_key) = scheme.generate_keys(bit_length, e)

    print("\nOriginal plaintext message: ", message)

    m = string2int(message)
    print("\nEncrypting message...")
    c = scheme.rsa_encrypt(m, public_key)
    ciphertext = int2string(c)
    print("  Ciphertext: ", ciphertext)

    print("\nDecrypting message...")
    [m2, running_time] = rt2(scheme.rsa_decrypt, c, private_key)
    message2 = int2string(m2)
    print("  Message decrypted by rsa_decrypt: ", message2)
    print("  Running time for rsa_decrypt: ", running_time)

    print("\nDecrypting message using Chinese Remainder Theorem...")
    [m3, running_time] = rt4(scheme.CRT_rsa_decrypt, c, private_key, p, q)
    message3 = int2string(m3)
    print("  Message decrypted by CRT_rsa_decrypt: ", message3)
    print("  Running time for CRT_rsa_decrypt: ", running_time)

    return (p, q, n, l, e, d, public_key, private_key, m, c, message,
            ciphertext)
示例#2
0
def main():
    # input as found in Exercise7_in7_to_student_Crowley.txt
    # first prime p

    p = 13
    # second prime q
    q = 149
    # encryption exponent e
    e = 257
    # encrypted message r
    r = 1907
    print("Running RSA Algorithms to find the RSA Modulus (n), the decryption exponent (d), and the decrypted message (s) for the given input:")
    print('')
    print(f"first prime p: {p}")
    print(f"second prime q: {q}")
    print(f"encryption exponent e: {e}")
    print(f"encrypted message r: {r}")
    print("")
    print("Initializing RSA class with the given input...")

    test = RSA(p, q, e)

    n = test.getPublicKeyPair()[0]
    d = test._d
    s = test.decryptMessage(r)

    print("\nResults")
    print("~*" * 8)
    print(f"RSA Modulus n: {n}")
    print(f"Decryption exponent d (this should be private!): {d}")
    print(f"Decrypted message s: {s}")
    print(f"n, d, s = {n}, {d}, {s}")
    print("~*" * 8)
示例#3
0
	def disp_ring_data(self):
		acc=RSA()
		temp = self.head
		print("------- Node", temp.key,"-------")
		for entry in temp.data:
			print("\t<---->")
			print(">>FILE NAME:\n", entry.name)
			print(">>PUBLIC KEY:\n", entry.pubkey)
			content=entry.content
			if not users_df[users_df['user']==curr_user][entry.name].isna().values[0]:
				print("Decrypting with private key...")
				print(">>CONTENT:\n", acc.decipher_text(content,int(users_df[users_df['user']==curr_user][entry.name].values[0]),entry.pubkey))
			else:
				print("Unable to decrypt without private key.")
				print(">>ENCRYPTED CONTENT:\n", entry.content)
			print("\t<---->\n")

		while(temp.next != self.head):
			temp = temp.next
			print("------- Node", temp.key,"-------")
			for entry in temp.data:
				print("\t<---->")
				print(">>FILE NAME:\n", entry.name)
				print(">>PUBLIC KEY:\n", entry.pubkey)
				content=entry.content
				if not users_df[users_df['user']==curr_user][entry.name].isna().values[0]:
					print("Decrypting with private key...")
					print(">>CONTENT:\n", acc.decipher_text(content,int(users_df[users_df['user']==curr_user][entry.name].values[0]),entry.pubkey))
				else:
					print("Unable to decrypt without private key.")
					print(">>ENCRYPTED CONTENT:\n", entry.content)
				print("\t<---->\n")
示例#4
0
def create_decrypt_running_time_table(message,
                                      e,
                                      start,
                                      stop,
                                      step,
                                      trials,
                                      inverse,
                                      powmodn=bit_pow_mod_n):

    scheme = RSA(powmodn=powmodn, inverse=inverse)

    m = string2int(message)

    print("bit_length,Naïve_fast_exponentiation,CRT_fast_exponentiation")

    for bit_length in range(start, stop + 1, step):
        sum_rt = sum_rt_crt = 0

        for i in range(trials):
            (p, q, n, l, e, d, public_key,
             private_key) = scheme.generate_keys(bit_length, e)
            c = scheme.rsa_encrypt(m, public_key)

            # Accumulate naïve recursive running times across trials
            sum_rt += rt2(scheme.rsa_decrypt, m, private_key)[1]

            # ditto for CRT
            sum_rt_crt += rt4(scheme.CRT_rsa_decrypt, c, private_key, p, q)[1]

        print(bit_length, sum_rt / trials, sum_rt_crt / trials, sep=',')
示例#5
0
 def initServer(self):
     self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     self.serverSock.bind((self.UDP_IP_ADDRESS, self.UDP_PORT_NO))
     self.RSA = RSA()
     print("Monitorando o endereço: " + self.UDP_IP_ADDRESS + ":" +
           str(self.UDP_PORT_NO))
     threading.Thread(target=self.listenMessages).start()
示例#6
0
文件: Envelope.py 项目: evukelic/NOS
    def encrypt(self):
        """
        Encryption method.
        :return: symmetric algorithm object
        """
        # message is encrypted by the given symmetric algorithm
        if self._algorithm == "AES":
            sym_alg = AES_DES3(self._key_type, self._message, self._mode)
            self._path = Constants.aes_secret_key_path
        else:
            sym_alg = AES_DES3(self._key_type, self._message, self._mode,
                               False)
            self._path = Constants.des3_secret_key_path

        # encryption
        key, cipher = sym_alg.encrypt()
        self._cipher = cipher

        # key is encrypted by the RSA asymmetric algorithm
        rsa = RSA(self._rsa_key, key, True)
        crypt_key = rsa.encrypt()
        self._crypt_key = crypt_key
        Helper.write_envelope([self._algorithm, 'RSA'], [key, crypt_key],
                              base64.b64encode(cipher), bytes.hex(crypt_key),
                              Constants.envelope_path)

        return sym_alg
示例#7
0
class ISO_RSA:
    def __init__(self, l):  # l is the length of p and q
        self.l = l
        self.p = 0
        self.q = 0
        self.N = 0
        self.public_key = 0
        self.secret_key = 0
        self.rsa = RSA(l)

    def gen(self, fixed_public_key=False):
        self.rsa.gen(fixed_public_key)
        self.p = self.rsa.p
        self.q = self.rsa.q
        self.N = self.rsa.N
        self.public_key = self.rsa.public_key
        self.secret_key = self.rsa.secret_key

    def enc(self, m):
        x = generate_x(self.N)
        y = prime.exp_mod(x, self.public_key, self.N)
        k = sha256(x.to_bytes(TEXT_SIZE, byteorder='big')).digest()
        iv = urandom(BLOCK_SIZE)
        encryption_suite = AES.new(k, AES.MODE_CBC, iv)
        c = encryption_suite.encrypt(m.to_bytes(
            TEXT_SIZE, byteorder='big'))  # using AES-256
        return y, c, iv

    def dec(self, y, c, iv):
        x = prime.exp_mod(y, self.secret_key, self.N)
        k = sha256(x.to_bytes(TEXT_SIZE, byteorder='big')).digest()
        decryption_suite = AES.new(k, AES.MODE_CBC, iv)
        return int.from_bytes(decryption_suite.decrypt(c),
                              byteorder='big')  # using AES-256
示例#8
0
 def run_RSA_block(s):
     r = RSA(16)
     print(r._p)
     print(r._q)
     c = r.encrypt_block(s)
     print(c.hex())
     m = r.decrypt_block(c)
     assert s.hex() == m.hex()
示例#9
0
 def __init__(self, l):  # l is the length of p and q
     self.l = l
     self.p = 0
     self.q = 0
     self.N = 0
     self.public_key = 0
     self.secret_key = 0
     self.rsa = RSA(l)
示例#10
0
 def test_code_decode(self):
     user1 = RSA.RSAGKP(10)
     publickey = user1[0]
     privkey = user1[1]
     message = 1122334455
     secret = RSA.RSAEP(publickey, message)
     # print("len(secret) = " + str(len(str(secret))))
     self.assertEqual(message, RSA.RSADP(privkey, secret))
示例#11
0
 def __init__(self):
     self.p = p
     self.q = q
     self.n = RSA.find_n(self, p, q)
     self.totient = RSA.find_totient(self, p, q)
     self.e = RSA.find_totient_coprime(self, self.totient)
     self.d = RSA.find_inverse(self, self.e, self.totient)
     self.public_key = (n, e)
示例#12
0
    def __init__(self, n=128):
        self._n = n
        self._k0 = 4
        self._k1 = 4
        self._block_size = self._n - self._k0 - self._k1

        self.hash = SHA256()
        self.rsa = RSA(self._n)
示例#13
0
def verify_ciphers():
    rsa = RSA()
    for i in range(100):
        for cipher_name, ciphers in cipher_list.items():
            if not ciphers.verify("test"):
                print(f"{cipher_name} failed!")
                break
        if not rsa.verify("test"):
            print("RSA failed!")
            break
示例#14
0
 def __init__(self, nbits=512, outpath=None, keypath=None):
     self.a = RSA()
     if keypath != None:
         self.a.inputKey(keypath)
         self.mode = self.a.mode
         return
     if outpath == None:
         outpath = 'PublickeyCipher\\'
     self.a.generateKey(nbits)
     self.a.outputPublicKey(outpath)
     self.a.outputPrivateKey(outpath)
示例#15
0
文件: UIRSAtool.py 项目: tiagobka/RSA
 def __init__(self, keySize: int = 1024):
     self.filePath = "/data/data.dat"
     self.mainWindow = Tk()
     self.mainWindow.geometry("630x500")
     #self.mainWindow.configure(background = "black")
     self.mainWindow.title("RSA Encrypter-Decrypter")
     self.mainWindow.grid_columnconfigure(0, minsize=10)
     self.mainWindow.grid_rowconfigure(10, minsize=20)
     self.keySize = keySize
     #Instantiate RSA class, Key will be 1024 by default
     self.rsa = RSA(self.keySize)
     self.option = IntVar(0)
示例#16
0
 def test_encdec(self):
     '''
     Test regular encoding and decoding of numbers
     '''
     a = DynamInt()
     a.setData("25")
     rsa = RSA(0)
     rsa.p.setData("11")
     rsa.q.setData("3")
     rsa.e.setData("3")
     rsa.n.setData("33")
     rsa.phi.setData("20")
     rsa.d.setData("7")
     d =  rsa.powmod(a,rsa.e,rsa.n)
     f =  rsa.powmod(d,rsa.d,rsa.n)
     self.assertEqual(a.data, f.data)
示例#17
0
 def setUp(self):
     self.p= DynamInt(10)
     self.q = DynamInt(10)
     #self.p.setData("821089628001493")
     #self.q.setData("1872967539195764008553239")   
     
     self.rsa = RSA(0)        
     self.rsa.createkeys(self.p, self.q)
示例#18
0
def send():
    msg = my_msg.get()
    my_msg.set("")
    msg = NAME + ": " + msg
    print(Fore.BLUE, end='')
    print(msg)
    msg_list.insert(tkinter.END, msg)
    msg = RSA.encrypt(msg, public_key_1)
    CLIENT.send(msg.encode("utf8"))
def send():
    messageS = my_msg.get()
    my_msg.set("")
    messageS = NAME + ": " + messageS
    print(Fore.BLUE, end='')
    print(messageS)
    msg_list.insert(tkinter.END, messageS)
    messageS = RSA.encrypt(messageS, public_key_2)
    CLIENT.send(messageS.encode("utf8"))
示例#20
0
    def authenticate(self, sock):
        data = sock.recv(4096)
        username = data.decode()
        print(username)
        f = open('Users.txt', 'rb')
        users = pickle.load(f)
        f.close()
        currUser = ''
        for user in users:
            if user.username == username:
                currUser = username
                break
        if currUser == '':
            sock.sendall('Username not in record'.encode())
            return False
        sock.sendall('Username Received'.encode())

        data = b''
        payload_size = struct.calcsize("L")
        print("Expecting Password")
        while len(data) < payload_size:
            data += sock.recv(4096)
        packed_msg_size = data[:payload_size]
        data = data[payload_size:]
        msg_size = struct.unpack("L", packed_msg_size)[0]
        while len(data) < msg_size:
            data += sock.recv(4096)
        block_data = data[:msg_size]
        data = data[msg_size:]
        password = pickle.loads(block_data)
        rsa = RSA()
        password = rsa.getDecryption(password, prKey[0], prKey[1])

        f = open('Users.txt', 'rb')
        users = pickle.load(f)
        f.close()
        for user in users:
            if user.username == username:
                currUser = user
                break
        hashedPT = hashlib.sha256(password.encode()).hexdigest()
        if not hashedPT == user.password:
            return False
        return True
示例#21
0
def calculation(message,
                n,
                e,
                d,
                p,
                q,
                startzustand=[1, 1, 1, 1, 0, 0, 0, 0],
                verbose=False):
    ### Alice ###
    ## 1,
    a = bitarray(startzustand)
    start_lfsr_alice = LFSR.lfsr(a, [0, 1, 3, 4])
    key = [next(start_lfsr_alice) for _ in range(120)]
    key = "".join(str(x) for x in startzustand + key)
    print("--ALICE--------")
    print("LFSR-Key: {}".format(helper.get_split_string_from_list(list(key))))

    ## 2,
    rsa = RSA(p="", q="", n=n, e=e)
    if verbose:
        rsa.print_stats()
    c_1 = rsa.short_public_exponent_encrypt(int("".join(
        str(i) for i in startzustand),
                                                base=2),
                                            verbose=verbose)
    print("RSA Ciphertext: {}".format(c_1))

    ## 3,
    aes = AES(key)
    c_2 = aes.encrypt(message, verbose=verbose)
    print("AES Ciphertext: {}".format(c_2))

    ### Bob ###
    ## 1,
    rsa = RSA(p=p, q=q, e=e, private_key=d)
    print("--BOB----------")
    print("Decryption....")
    bin_str = bin(rsa.chinese_decrypt(c_1, verbose=verbose))[2:]
    print("RSA Plaintext: {}".format(
        helper.get_split_string_from_list(list(bin_str))))

    ## 2,
    a = bitarray(bin_str)
    start_lfsr_bob = LFSR.lfsr(a, [0, 1, 3, 4])
    key_bob = [next(start_lfsr_bob) for _ in range(120)]
    key_bob = "".join(str(x) for x in list(bin_str) + key_bob)
    print("LFSR-Key: {}".format(
        helper.get_split_string_from_list(list(bin_str))))

    ## 3,
    aes = AES(key_bob)
    corresponding_message = aes.decrypt(c_2, verbose=verbose)
    print("Message: {}".format(corresponding_message))
    return message
示例#22
0
class TestRSAOperations(unittest.TestCase):

    def setUp(self):
        self.p= DynamInt(10)
        self.q = DynamInt(10)
        #self.p.setData("821089628001493")
        #self.q.setData("1872967539195764008553239")   
        
        self.rsa = RSA(0)        
        self.rsa.createkeys(self.p, self.q)
    def test_encdec(self):
        '''
        Test regular encoding and decoding of numbers
        '''
        a = DynamInt()
        a.setData("25")
        rsa = RSA(0)
        rsa.p.setData("11")
        rsa.q.setData("3")
        rsa.e.setData("3")
        rsa.n.setData("33")
        rsa.phi.setData("20")
        rsa.d.setData("7")
        d =  rsa.powmod(a,rsa.e,rsa.n)
        f =  rsa.powmod(d,rsa.d,rsa.n)
        self.assertEqual(a.data, f.data)
        
        
        
    def test_disguise(self):
        strr = "iamaboy"
        rsa = RSA(0)
        num=rsa.disguise(strr)
        self.assertEqual("iamaboy", rsa.reveal(num))
    def test_encryptionDecryption(self):
        # make sure we can encrypt and decrypt
        crypted = self.rsa.encrypt("iam")
        result = self.rsa.decrypt(crypted)
        temp=''
        for i in result:
            temp = temp+i
        self.assertEqual("iam", temp)
示例#23
0
def console_mode():
    print 'Welcome to RSA!'
    p, q = _get_primes_from_user()
    if not p or not q:
        bit_len = _get_bit_len_from_user()
    else:
        bit_len = max(p, q).bit_length()
    keys = key_gen.get_RSA_keys(bit_len, p, q)
    rsa_instance = RSA(n=keys[0][1], public_key=keys[0][0], private_key=keys[1][0], key_size=bit_len)
    while True:
        msg = _get_msg_to_enc()
        if msg == 'exit':
            break
        try:
            enc = rsa_instance.encrypt(msg)
            print 'Enc msg is: {}'.format(enc)
            dec = rsa_instance.decrypt(enc)
            print 'Dec msg is: {}'.format(dec)
        except Exception as e:
            print e
示例#24
0
    def setKey(self, message, new_bits):  #generate the RSA ans IDs

        self.message = message

        self.bits = new_bits

        self.e_RSA = 65537  # this value is given

        self.demoRSA = RSA()

        self.demoRSA.RSA(self.bits, self.e_RSA)

        self.demoRSA.sigGeneration(self.message)

        self.updateRSAKeys()

        self.IDs = int(1780119054 *
                       random.random())  #not necessary to generate

        self.serverID = 1780119054  #just give -> can change any numbers
def receive():
    msg_list.insert(tkinter.END, "Usuario: %s " % NAME)
    msg_list.insert(tkinter.END, "Conexion exitosa")
    while True:
        try:
            messageR = CLIENT.recv(BUFFER_SIZE).decode("utf8")
            messageR = RSA.deEncrypt(messageR, private_key_1)
            print(Fore.YELLOW, end='')
            print(">" + messageR)
            msg_list.insert(tkinter.END, messageR)
        except OSError:
            break
示例#26
0
class DSA:
    def __init__(self, P, Q):
        self.P = P
        self.Q = Q
        self.encryptor = RSA(self.P, self.Q)
        self.e, self.d, self.n = self.encryptor.generate_keys()

    def get_hash(self, message):

        hash_input = bytes(message, "utf-8")
        hash_digest = SHA1HASH(hash_input).final_hash()

        return hash_digest

    def sign_document(self, input_file):

        with open(input_file) as f:
            message = f.read()

        hash_digest = self.get_hash(message)

        print("Public keys are e:{}, n:{}".format(self.e, self.n))
        print("Private keys are d:{}, n:{}".format(self.d, self.n))

        ciphertext = self.encryptor.encrypt(hash_digest)
        return ciphertext

    def verify_document(self, input_file, ciphertext):

        with open(input_file) as f:
            message = f.read()

        hash_digest = self.get_hash(message)

        plaintext = self.encryptor.decrypt(ciphertext)

        if plaintext == hash_digest:
            return False
        else:
            return True
示例#27
0
文件: Signature.py 项目: evukelic/NOS
 def sign(self):
     """
     Signing method.
     :return: signature
     """
     _hash = SHA_2(self._sha, self._message).hash()
     rsa = RSA(self._rsa_key, None)
     self._rsa = rsa
     # sign
     signature = pkcs1_15.new(self._rsa.private_key).sign(_hash)
     # write signature to the file
     Helper.write_signature(['SHA-2', 'RSA'], [hex(int(self._sha)), hex(self._rsa.private_key.size_in_bits())], signature, Constants.signature_path)
     self._signature = signature
示例#28
0
def command_line():
    '''Command line wrapper for RSA.py.'''
    parser = argparse.ArgumentParser(
        description='Command line interface for RSA encryption')
    parser.add_argument('-n',
                        '--new-keys',
                        action='store_true',
                        help='Whether or not new keys should be generated.')
    parser.add_argument('-m',
                        '--message',
                        action='store',
                        type=str,
                        help='Message to be encoded.')
    parser.add_argument('-c',
                        '--coded-message',
                        action='store',
                        type=str,
                        help='Location of message to be decoded.')
    parser.add_argument('-k',
                        '--key-files',
                        action='store',
                        type=str,
                        help='TODO')
    parser.add_argument('-s',
                        '--store-keys',
                        action='store',
                        type=str,
                        help='Desired file location for output of keys')
    arguments = parser.parse_args()

    if arguments.new_keys:
        rsa = RSA(arguments.store_keys)
        rsa.RSA_keygen()

    if arguments.message:
        rsa = RSA(arguments.store_keys)
        rsa.RSA_encode(arguments.message, arguments.key_files)

    if arguments.coded_message:
        rsa = RSA(arguments.store_keys)
        message = rsa.RSA_decode(arguments.coded_message, arguments.key_files)

        print(message)
示例#29
0
def test2():
    rsa = RSA()
    rsa.e = 3
    rsa.d = 2011
    rsa.n = 3127
    message = "hello"

    print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n))
    print("Message: " + message)

    enc = rsa.encrypt(message)
    print("Encrypted message: " + enc)
    dec = rsa.decrypt(enc)
    print("Decrypted message: " + dec)

    sig = "andres"
    print("Signature: " + sig)
    dec2 = rsa.decrypt(sig, True)
    print("Generated Signature: " + dec2)
    auth = rsa.encrypt(dec2, True)
    print("After Authentication: " + auth)
示例#30
0
def test():
    rsa = RSA()
    rsa.e = 3
    rsa.d = 2011
    rsa.n = 3127
    message = "hello"

    print("Test known values e={}, d={}, n={}".format(rsa.e, rsa.d, rsa.n))
    print("Message to encrypt/decrypt: " + message)

    enc = rsa.encrypt(message)
    print("Encrypted message: " + enc)
    dec = rsa.decrypt(enc)
    print("Decrypted message: " + dec)
示例#31
0
class Bob:
    def __init__(self,y,keys):
        self.y = y
        self.rsa = RSA(keys)
        self.util = Utilities()

    def computation(self,c1,m1,p):
        m2 = list()
        for i in range(xr+1):
            if i ==0:
                m2.append(-1)
                continue
            m2.append(self.rsa.decrypt(c1+i))
        self.m2 = m2
        count = 1
        random.seed(datetime.now())   
        while count != 0:
            count = 0
            self.p =p
            # input("p ki toh")
            z= list(range(xr+1))
            for i in range(1,xr+1):
                z[i] = self.m2[i] %self.p 
            for i in range(1,xr+1):
                for j in range(1,xr+1):
                    if(abs(z[i]-z[j]) < 2 and i!=j ):
                        print(i , " ",j )
                        count += 1
                        input("enter to contuneue")
                        break         
                if count >0:
                    break
        self.z = z

        for i in range(1,xr+1):
            if i>y:
                self.z[i] = self.z[i]+1
        return (self.z,self.p)
               
    def getZ(self):
        return self.z

    def getResult(self, response):
        if response:
            print("Value of Alice is greater than Bob's")
        else:
            print("Bob's value is greater than Alice's")
    def run(self):
        global Globalvariable

        while 1:
            message_recu = self.connexion.recv(1024).decode("Utf8")
            if message_recu[0:14] == "##Rsapubkeyis#":
                if not Globalvariable['RSA_Recieved']:
                    message = message_recu[14:].split("#")
                    Globalvariable['OtherRsaE'], Globalvariable[
                        'OtherRsaN'] = int(message[0]), int(message[1])
                    self.connexion.send("##YesRsa".encode("Utf8"))
                    Rsa = RSA()
                    Globalvariable["EncRC4Key"] = Rsa.crypt(
                        Globalvariable["OtherRsaE"],
                        Globalvariable["OtherRsaN"], Globalvariable["RC4Key"])
                    Globalvariable['RSA_Recieved'] = True
                    color_print(
                        "Public Anahtarı -->" +
                        str(Globalvariable["OtherRsaE"]) +
                        str(Globalvariable["OtherRsaN"]), 'red')
                    color_print(
                        "RC4 Private Anahtarı -->" + Globalvariable["RC4Key"],
                        'red')
                    color_print(
                        "Şifrelenmiş Anahtar -->" +
                        str(Globalvariable["EncRC4Key"]), 'red')
                else:
                    self.connexion.send("##YesRsa".encode("Utf8"))
            elif message_recu == "##YesRsa":
                Globalvariable['RSA_Sent'] = True
            elif message_recu[:6] == "##RC4#":
                if Globalvariable["OtherRC4"] == "":
                    Rsa = RSA()
                    Globalvariable["OtherRC4"] = Rsa.decrypt(
                        Globalvariable["d"], Globalvariable["n"],
                        int(message_recu[6:]))
                    self.connexion.send("##YesRC4".encode("Utf8"))
                else:
                    self.connexion.send("##YesRC4".encode("Utf8"))
            elif message_recu == "##YesRC4":
                if not Globalvariable["RC4_sent"]:
                    Globalvariable["RC4_sent"] = True

            elif Globalvariable['RSA_Sent'] and Globalvariable[
                    'RSA_Recieved'] and message_recu[
                        0:
                        14] != "##Rsapubkeyis#" and message_recu != "##YesRsa" and message_recu != "##YesRC4":
                Rc44 = RC4()

                Rc44.shuffle(str(Globalvariable["OtherRC4"]))

                message = Rc44.Crypt(message_recu)
                color_print("Mesaj -->" + message, 'yellow')
                color_print("Şifrelenmiş Mesaj -->" + message_recu, 'blue')
示例#33
0
class Alice:
    def __init__(self,x,keys):
        self.x = x
        self.rsa = RSA(keys)
        self.util = Utilities()
        

    def computation(self,bobKey,m1):
        self.m1 = m1
        self.c = self.rsa.encrypt(self.m1,PUKY=bobKey)
        self.c1 = self.c - self.x
        return self.c1
    
    def generateResults(self,z,p):
        if z[self.x ]%p == self.m1 % p :
            return False
        return True
 def __init__(self, HOST, PORT, NICK):
     super(ClientThread, self).__init__()
     self.ONLINE_LIST = []
     self.nick = NICK
     self.cbox = None
     self.RSA_Scheme = RSA()
     self.BREA_Scheme = BREA()
     self.receiver = "broadcast"
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sep = chr(7)
     self.broadcast = 1
     self.HOST = socket.gethostbyname(str(HOST))
     self.PORT = PORT
     self.isconnected = 1
     self.root = 0
     self.online_list = []
     try:
         self.sock.connect((self.HOST, self.PORT))
     except:
         self.isconnected = 0
示例#35
0
文件: main.py 项目: nunch/IT-5202E
'''
Created on 26 nov. 2015

@author: yo
'''
from RSA import RSA
import time

if __name__ == '__main__':
    rsa = RSA()
    #truc=rsa.primeFactorsDecomposition(1234567890123456789)
    a={1:2,3:9}
    a=5
    truc=0
    start_time = time.time()
    #truc=rsa.pollard(26915353)
    elapsed_time = time.time() - start_time
    print(elapsed_time)
    print(truc)
    
    start_time = time.time()
    truc=rsa.quadraticSieve(10585477741304331)
    elapsed_time = time.time() - start_time
    print(truc)
    print(elapsed_time)
示例#36
0
 def test_disguise(self):
     strr = "iamaboy"
     rsa = RSA(0)
     num=rsa.disguise(strr)
     self.assertEqual("iamaboy", rsa.reveal(num))
class ClientThread(Thread):
    def __init__(self, HOST, PORT, NICK):
        super(ClientThread, self).__init__()
        self.ONLINE_LIST = []
        self.nick = NICK
        self.cbox = None
        self.RSA_Scheme = RSA()
        self.BREA_Scheme = BREA()
        self.receiver = "broadcast"
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sep = chr(7)
        self.broadcast = 1
        self.HOST = socket.gethostbyname(str(HOST))
        self.PORT = PORT
        self.isconnected = 1
        self.root = 0
        self.online_list = []
        try:
            self.sock.connect((self.HOST, self.PORT))
        except:
            self.isconnected = 0

    def reconnect(self):
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.HOST, self.PORT))
            self.sock.send('2' + self.sep + self.nick + self.sep + self.RSA_Scheme.getPublicKey())
            data = self.sock.recv(4096)
            self.online_list = data.split(self.sep)
            if self.online_list[0] == '2':
                for i in range(1, len(self.online_list), 2):
                    self.cbox.online.addItem(self.online_list[i])
                    self.ONLINE_LIST.append((self.online_list[i], self.online_list[i+1]))
        except:
            pass

    def run(self):
        while True:
            try:
                msg = self.sock.recv(4096)
            except:
                self.ONLINE_LIST = []
                self.online_list = []
                self.cbox.online.clear()
                self.reconnect()
                continue
            ins = msg.split(self.sep)
            if ins[0] == '1':
                if self.cbox.connected.text() == "Connected to " + ins[1]:
                    self.cbox.connected.setText("Connected to <No User>")
                for i in range(self.cbox.online.count()):
                    if self.cbox.online.item(i).text() == ins[1]:
                        self.cbox.online.takeItem(i)
                        break
                for i in self.ONLINE_LIST:
                    if i[0] == ins[1]:
                        self.ONLINE_LIST.remove(i)
                        break
            elif ins[0] == '2':
                for i in range(1, len(ins), 2):
                    self.cbox.online.addItem(ins[i])
                    self.ONLINE_LIST.append((ins[i], ins[i+1]))
            elif ins[0] == '3':
                if ins[2] == self.nick or self.root == 1:
                    key = ins[4]
                    msg = self.BREA_Scheme.decrypt(ins[3], self.RSA_Scheme.decrypt(key))
                    self.cbox.win.append("[" + ins[1] + "] " + msg)
            elif ins[0] == "4":
                self.cbox.win.append("[" + ins[1] + "] " + ins[2])

    def nickValidate(self, txt):
        sent = "2" + self.sep + txt + self.sep + self.RSA_Scheme.getPublicKey()
        self.sock.send(sent)
        ret = self.sock.recv(4096)
        ret = ret.split(self.sep)
        self.online_list = ret
        return ret