Exemplo n.º 1
0
def prob29():
     key = "YELLOW SUBMARINE"
     message = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
     appending = ';admin=true'

     # go through different key lengths
     for i in range(0, 64):
             message_padding = gen_sha1_padding(('a' * i) + message) # generate padding with the proposed key length
             sha1_hash = sha1.sha1(key + message) # do a normal sha1 

             # get the state from our sha1 results
             a  = int(sha1_hash[0:8], 16)
             b  = int(sha1_hash[8:16], 16)
             c  = int(sha1_hash[16:24], 16)
             d  = int(sha1_hash[24:32], 16)
             e  = int(sha1_hash[32:40], 16)    

             # generate new padding or when we append to the message
             new_pad = gen_sha1_padding(('a' * i) + message + message_padding + appending)
             # do sha1 with our previous state
             modified = sha1_with_regs(appending + new_pad, a, b, c, d, e)
             actual_sha1 = sha1.sha1(key + message + message_padding + appending)
             # compare our real sha1 result with what we proposed
             if (actual_sha1 == modified):
                     return True
     return False
Exemplo n.º 2
0
    def test_similar(self):
        """Test Similar SHA-1 Inputs

        Tests sets of messages with 1 bit of difference. Ensures that all
        messages produce unique hashes.

        Raises:
            AssertionError if test fails.
        """
        print '\n>>> running: test_similar'
        first_msg = bytearray(get_random_bytes())
        modified_msg = bytearray()

        # Pick a random byte, modify it by one bit
        byte_to_modify = random.randrange(0, len(first_msg))

        for i, byte in enumerate(first_msg):
            augmentor = 1 if i == byte_to_modify else 0
            modified_msg.append(byte + augmentor)

        first_digest = sha1.sha1(str(first_msg))
        modified_digest = sha1.sha1(str(modified_msg))

        print '... test_similar: checking digest differences'
        self.assertNotEqual(first_digest, modified_digest)

        print '... test_similar: success'
Exemplo n.º 3
0
def hmac(key, message):
    if len(key) > blocksize:
        key = sha1(key)
    if len(key) < blocksize:
        key = key + b'\0' * (blocksize - len(key))
   
    o_key_pad = xor(b'\x5c' * blocksize, key)
    i_key_pad = xor(b'\x36' * blocksize, key)
   
    return sha1(o_key_pad + sha1bytes(i_key_pad + message))
Exemplo n.º 4
0
    def create_key_exchange(self):
        # First generate pre_master
        pre_master = ""
        for _ in range(48):
            pre_master += chr(random.randint(0, 127))
        # Encrypt it and get the encrypted length
        pre_master_encrypt = rsa.encrypt_rsa(rsa.text_to_decimal(pre_master), self.server_pubkey.e,
                                             self.server_pubkey.n)
        key_length = util.get_length_in_bytes(pre_master_encrypt)

        client_key_exchange = bytearray((1234 + key_length) * '\x00', 'hex')
        client_key_exchange[0] = '\x03'
        client_key_exchange[1:5] = util.int_to_binary(1229 + key_length, 4)
        client_key_exchange[5:7] = self.session_id
        client_key_exchange[7:1210] = self.cert
        client_key_exchange[1210:1212] = util.int_to_binary(key_length, 2)
        client_key_exchange[1212:1212 + key_length] = util.int_to_binary(pre_master_encrypt, key_length)
        hash_credentials = sha1.sha1(self.userID + self.password)
        hash_credentials_nonced = sha1.sha1(sha1.digestToString(hash_credentials) + self.server_random)
        client_key_exchange[1212 + key_length:1232 + key_length] = util.int_to_binary(
            hash_credentials_nonced, 20)
        client_key_exchange[1232 + key_length:1234 + key_length] = '\xF0\xF0'

        # Calculate and store the master_secret
        self.master_secret = \
            sha1.sha1(
                sha1.digestToString(sha1.sha1(pre_master + sha1.digestToString(
                    sha1.sha1('A' + pre_master + self.client_random + self.server_random))))
                + sha1.digestToString(sha1.sha1(pre_master + sha1.digestToString(
                    sha1.sha1('BB' + pre_master + self.client_random + self.server_random))))
                + sha1.digestToString(sha1.sha1(pre_master + sha1.digestToString(
                    sha1.sha1('CCC' + pre_master + self.client_random + self.server_random)))))

        print "Sent ClientKeyExchange"
        return client_key_exchange
Exemplo n.º 5
0
def main():
    NIST_PRIME = 0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff
    g = 2
    k = 3

    server = SingleSRPServer(g, k, NIST_PRIME)
    client = SingleSRPClient(server, g, k, NIST_PRIME)

    client.register("hello", "12345")
    client.login("hello", "1")
    client.login("hello", "123456")
    client.login("hello", "12345df6")
    client.login("helloa", "12345")

    client.login("hello", "12345")
    
    # test 1 - using A = 0

    server = SingleSRPServer(g, k, NIST_PRIME)
    client = SingleSRPClient(server, g, k, NIST_PRIME)

    client.register("root", os.urandom(32))
    print server.whoami()
    salt, B = server.initiate_login("root", 0)
    false_K = sha1(str(0)).hexdigest() 
    false_tag = sha1_hmac(false_K).tag(salt)
    server.confirm_login(false_tag)
    print server.whoami()

    # test 2 - using A = N

    server = SingleSRPServer(g, k, NIST_PRIME)
    client = SingleSRPClient(server, g, k, NIST_PRIME)

    client.register("admin", os.urandom(32))
    print server.whoami()
    salt, B = server.initiate_login("admin", NIST_PRIME)
    false_K = sha1(str(0)).hexdigest() 
    false_tag = sha1_hmac(false_K).tag(salt)
    server.confirm_login(false_tag)
    print server.whoami()

    # test 2 - using A = N * 2

    server = SingleSRPServer(g, k, NIST_PRIME)
    client = SingleSRPClient(server, g, k, NIST_PRIME)

    client.register("god", os.urandom(32))
    print server.whoami()
    salt, B = server.initiate_login("god", NIST_PRIME*2)
    false_K = sha1(str(0)).hexdigest() 
    false_tag = sha1_hmac(false_K).tag(salt)
    server.confirm_login(false_tag)
    print server.whoami()
Exemplo n.º 6
0
 def test_sha_length_extension(self):
     """Challenge 29"""
     orig_message = 'comment1=cooking%20MCs;userdata=foo;comment2=%20like' \
             '%20a%20pound%20of%20bacon'
     # this is not known to attacker.
     key = Crypto.gen_random_key(100)
     suffix = ';admin=true;'
     orig_sha = sha1(key + orig_message)
     forged_message = Sha1Hash.pad(key + orig_message) + suffix
     forged_sha = sha1(forged_message)
     validate = lambda sha: sha == forged_sha
     self.assertTrue(extend_sha1(orig_sha, orig_message, suffix, validate))
Exemplo n.º 7
0
    def _complete_login(self, password):
        if self._salt is None or self._B is None:
            print "Complete initial login first"
            return False

        self._u = sha1("%x%x" % (self._A, self._B)).digest()
        x = sha1(self._salt + password).digest()
        S = pow(self._B - self._k * pow(self._g, x, self._N), self._a + self._u * x, self._N)

        K = sha1(str(S)).hexdigest()

        return self._server.confirm_login(sha1_hmac(K).tag(self._salt))
Exemplo n.º 8
0
 def test_sha_length_extension(self):
     """Challenge 29"""
     orig_message = 'comment1=cooking%20MCs;userdata=foo;comment2=%20like' \
             '%20a%20pound%20of%20bacon'
     # this is not known to attacker.
     key = Crypto.gen_random_key(100)
     suffix = ';admin=true;'
     orig_sha = sha1(key + orig_message)
     forged_message = Sha1Hash.pad(key + orig_message) + suffix
     forged_sha = sha1(forged_message)
     validate = lambda sha: sha == forged_sha
     self.assertTrue(extend_sha1(orig_sha, orig_message, suffix, validate))
Exemplo n.º 9
0
def hmac_sha1(key, msg):
    blk_sz = 64
    len_opt = 20
    ipad = chr(0x36) * blk_sz
    opad = chr(0x5C) * blk_sz
    if len(key) > blk_sz:
        key = sha1.sha1(key)
    key += chr(0) * (blk_sz - len(key))

    sub_msg = xor_encrypt.xor_encrypt_str(key, ipad)
    sub_msg = sha1.sha1(sub_msg + msg)
    msg = xor_encrypt.xor_encrypt_str(key, opad) + sub_msg
    return sha1.sha1(msg)
Exemplo n.º 10
0
def hash_password():
    print('Vložte heslo: ')
    password = input()

    hash = sha1(password.encode())

    print('Zahešované heslo: {}'.format(to_hex(*hash)))
Exemplo n.º 11
0
 def test_sha(self):
     testData = [b"test str", b"string longer than 512 bits" + b"A" * 512, b"very long" + b"X" * 3000, bytes(range(256))]
     for msg in testData:
         hash1 = sha1.sha1(msg)
         mac = hashlib.sha1(msg)
         hash2 = mac.hexdigest()
         self.assertEqual(hash1, hash2, "[ERROR] for msg: {}".format(msg))
Exemplo n.º 12
0
def handleHashValorSecreto():
	hvs=connection.recv(1024)
	print 'Se ha recibido el mensaje %s, el texto es %s y el hash %s'%(hvs,hvs[:-40],hvs[-40:])
	vs=getValorSecreto()
	hh=sha1.sha1(hvs[:-40]+vs)
	print hh,len(hh)
	print 'Al calcular el hash sha1 del texto \"%s\" mas el valor secreto %s se obtiene: %s que'%(hvs[:-40],vs,hh),' ' if hh==hvs[-40:] else ' no ', 'coincide'
Exemplo n.º 13
0
def hashnormal():
    sock.sendall('hn')
    msg=getMsg()
    h=sha1.sha1(msg)
    msg=msg+h
    sock.sendall(msg)
    return 0
Exemplo n.º 14
0
 def register(cls, password, realname, email):
     try:
         con = lite.connect('databases/pilearn.db')
         con.row_factory = lite.Row
         cur = con.cursor()
         cur.execute("SELECT * FROM user WHERE email=?", (email, ))
         if cur.fetchone():
             return -3
         cur.execute(
             "INSERT INTO user (name, realname, email, banned, role, reputation, aboutme, deleted, mergeto, labels, member_since) VALUES (?, ?, ?, 0, 1, 1, '', 0, 0, '[]', ?)",
             (realname, realname, email, time.time()))
         data = cur.lastrowid
         if password is not None:
             password = sha1(password)
             cur.execute(
                 "INSERT INTO login_methods (user_id, provider, email, password) VALUES (?, ?, ?, ?)",
                 (data, "local_account", email, password))
         con.commit()
         return data
     except lite.Error as e:
         print(e)
         return -3
     finally:
         if con:
             con.close()
Exemplo n.º 15
0
    def test_repeatable(self):
        """Test SHA-1 Repeatability

        Runs the SHA-1 hashing function multiple times to ensure the same
        outcome for any identical message input.
        """
        print('\n>>> running: test_repeatable')
        msg = bytearray(get_random_bytes())

        first_digest = sha1.sha1(bytes(msg))
        second_digest = sha1.sha1(bytes(msg))

        print('... test_repeatable: checking for identical digests')
        self.assertEqual(first_digest, second_digest)

        print('... test_repeatable: success')
Exemplo n.º 16
0
    def test_repeatable(self):
        """
        Test SHA-1 Repeatability
        Runs the SHA-1 hashing function multiple times to ensure the same
        outcome for any identical message input.
        """
        print('\n>>> running: test_repeatable')
        msg = bytearray(get_random_bytes())

        first_digest = sha1.sha1(bytes(msg))
        second_digest = sha1.sha1(bytes(msg))

        print('... test_repeatable: checking for identical digests')
        self.assertEqual(first_digest, second_digest)

        print('... test_repeatable: success')
Exemplo n.º 17
0
    def syscall_read(self, arg, ret):
        r = arg.data
        assert r.nr == syscall.NR_read

        fd = arg.data.args["fd"]
        inode = fd.inode
        dbg.syscallm("!", "#R<read#>: reading %s with %s" % (inode, r))

        # read & create mock object
        pn = kutil.get(inode)
        with open(pn, 'r') as f:
            f.seek(fd.offset)
            file_data = f.read(r.args["count"])

        sha = sha1(file_data)

        dbg.syscallm("!", "#R<read#>: sha1:%s (old:%s)" \
                % (hexdigest(sha), hexdigest(ret.origdata.args["buf"])))

        new_data = deepcopy(ret.origdata)
        new_data.args["buf"] = sha
        new_data.args["real_buf"] = file_data
        new_data.ret = len(file_data)

        return new_data
Exemplo n.º 18
0
def main():
    # 获取消息
    cipher_message = receiver().split(',')
    des_cipher = cipher_message[0]
    des_key_encrypted = cipher_message[1]
    signed_hash = cipher_message[2]

    # 获取rsa公钥、私钥
    rsa_d = int(read_message('./receiver/rsa_d.txt'), 16)
    rsa_n = int(read_message('./receiver/rsa_n.txt'), 16)
    rsa_e = int(read_message('./receiver/rsa_e.txt'), 16)

    # 解密消息签名
    hash_decrypted = rsa.rsa_decrypt(signed_hash, rsa_e, rsa_n)

    # 验证消息签名
    if hash_decrypted == sha1.sha1(des_cipher):
        print('\n消息签名验证成功,加密数据完整!')
    else:
        print('\n消息签名验证失败,加密数据不完整!')

    # 解密对称密钥
    des_key = rsa.rsa_decrypt(des_key_encrypted, rsa_d, rsa_n)

    # 解密密文
    msg = des.ECB_decrypt(des_cipher, des_key)

    # 将16进制密文转化为ASCII码
    msg = binascii.unhexlify(msg).decode()
    print('\nDecrypted messages: \n' + msg)
Exemplo n.º 19
0
def hashValorSecreto():
    sock.sendall('hvs')
    msg=getMsg()
    vs=getValorSecreto()
    h=sha1.sha1(msg+vs)
    msg=msg+h
    sock.sendall(msg)
    return 0
Exemplo n.º 20
0
def handleHashClaveSimetrica():
	hn=connection.recv(1024)
	print 'Se ha recibido el mensaje %s, el texto es %s y el hash %s'%(hn,hn[:-48],hn[-48:])
	k=getClave()
	hh=sha1.sha1(hn[:-48])
	print hh,len(hh)
	dhh=(aes.aes('d',hn[-48:],k))[:40]
	print 'Al desenciptar %s se obtiene %s'%(hn[-48:],dhh)
	print 'Al calcular el hash sha1 del texto \"%s\" se obtiene: %s que'%(hn[:-48],hh)+' ' if hh==dhh else ' no ', 'coincide'
Exemplo n.º 21
0
def hash_file(path, other=""):
    """ Return (h,hcontents) where:
          h is a hash of the path, the string other and the content to a prime
          hcontent is a classical hash of the content
      TODO: add metadata """
    hcontent = sha1(path)
    h = int(hashlib.sha1("f\0" + path + "\0" + other + "\0" + hcontent).hexdigest(), 16)
    hcontent = int(hcontent, 16)
    return (hash_to_prime(h), hcontent)
Exemplo n.º 22
0
def hashClaveSimetrica():
    sock.sendall('hcs')
    msg=getMsg()
    k=getClave()
    ha=sha1.sha1(msg)
    h=aes.aes('e',ha,k)#+aes.encriptarAes(ha[32:48],k)
    print 'largo hash Encriptado %d'%len(h)
    msg=msg+h
    sock.sendall(msg)
    return 0
Exemplo n.º 23
0
 def get_mbit(string, m=5):
     """
     Get the key of mbit using SHA1
     :param mac_port: the mac + port combination
     :param m: the value of m defualt to 5
     :return: returns the value from 0 to 2**m -1
     """
     hsh = sha1.sha1(string)
     m_bit = int(hsh, 16) % (2**m)
     return int(m_bit)
Exemplo n.º 24
0
    def H(data):
        chunk_list = [(128 - 20 * 6) * b"\x00"]
        for _ in range(6):
            data = sha1.sha1(data)
            chunk_list.append(data)

        ret = b"".join(chunk_list)

        assert len(ret) == 128
        return ret
Exemplo n.º 25
0
 def reset_deletion(cls, email, password):
     try:
         con = lite.connect('databases/pilearn.db')
         con.row_factory = lite.Row
         cur = con.cursor()
         cur.execute(
             "UPDATE user SET deleted=0 WHERE email=? AND password=?",
             (email, sha1(password)))
         con.commit()
         cur.execute("SELECT id FROM user WHERE email=? AND password=?",
                     (email, sha1(password)))
         data = cur.fetchone()["id"]
         return data
     except lite.Error as e:
         print(e)
         return -3
     finally:
         if con:
             con.close()
Exemplo n.º 26
0
def sha1_secret_mac(message, key):
    '''
	Implement a SHA-1 keyed MAC.
	Information about the SHA1 algorithm: https://tools.ietf.org/html/rfc3174
	The implementation of the SHA1 algorithm was taken from: https://github.com/ajalt/python-sha1
	This is used for message authentication,if one bit of data changes in the message
	the hash returned from the SHA1 algorithm completely changed,this is the so called
	avalanche effect.
	'''
    return sha1(key + message)
Exemplo n.º 27
0
def solve():
    old_message = ("comment1=cooking%20MCs;"
                   "userdata=foo;comment2=%"
                   "20like%20a%20pound%20of"
                   "%20bacon")
    old_tag = sha1(key_raw + old_message)
    print "[+] original tag : {}".format(old_tag)
    new_data = ";admin=true"
    new_tag = hash_extend_attack(old_message, hex2raw(old_tag), new_data)
    print '[+] new tag      : {}'.format(new_tag)
Exemplo n.º 28
0
    def initiate_login(self, user, A):
        if self._user != user:
            print "You must register first"
            return None, None

        self._A = A
        self._b = random.randint(0, 2**256) % self._N
        self._B = self._k * self._v + pow(self._g, self._b, self._N)
        self._u = sha1("%x%x" % (self._A, self._B)).digest()
        
        return self._salt, self._B
Exemplo n.º 29
0
def forge_sha1_mac(original_message, mac, append):
    h0, h1, h2, h3, h4 = struct.unpack('>IIIII', mac)
    for prefix_length in range(1, 20):
        print(f'PREFIX LENGTH: {prefix_length}')
        to_pad = b'a' * prefix_length  + original_message
        padded = get_sha1_padding(to_pad)
        new_mac = sha1(append, 8*(len(padded) + len(append)), h0, h1, h2, h3, h4)
        new_plaintext = padded[prefix_length:] + append
        if authenticate(new_plaintext, new_mac):
            return new_plaintext, new_mac
    return b'', b''
Exemplo n.º 30
0
 def test_sha(self):
     testData = [
         b"test str", b"string longer than 512 bits" + b"A" * 512,
         b"very long" + b"X" * 3000,
         bytes(range(256))
     ]
     for msg in testData:
         hash1 = sha1.sha1(msg)
         mac = hashlib.sha1(msg)
         hash2 = mac.hexdigest()
         self.assertEqual(hash1, hash2, "[ERROR] for msg: {}".format(msg))
Exemplo n.º 31
0
 def test_sha2state(self):
     testData = [b"test str", b"string longer than 512 bits" + b"A" * 512, b"very long" + b"X" * 3000, bytes(range(256))]
     for msg in testData:
         hash1 = sha1.sha1(msg)
         h0, h1, h2, h3, h4 = sha1.process_all(msg)
         a0, a1, a2, a3, a4 = sha1.sha2state(hash1)
         self.assertEqual(a0, h0)
         self.assertEqual(a1, h1)
         self.assertEqual(a2, h2)
         self.assertEqual(a3, h3)
         self.assertEqual(a4, h4)
Exemplo n.º 32
0
def main():
    dh = diffie_hellman.DiffieHellman()

    a_pri, a_pub, a_p, a_g = dh.gen_key_pair()
    m_pri, m_pub, m_p, m_g = dh.gen_key_pair()
    b_pri, b_pub, b_p, b_g = dh.gen_key_pair()

    a_sk = dh.gen_sec_key(m_pub, a_pri)
    key_a = sha1.sha1(str(a_sk))[:16]
    iv_a = my_rand.my_rand_byte(16)

    b_sk = dh.gen_sec_key(m_pub, b_pri)
    key_b = sha1.sha1(str(b_sk))[:16]
    iv_b = my_rand.my_rand_byte(16)

    plain_ori = my_rand.my_rand_str(my_rand.my_rand(30, 10))

    print "Sending following text from A to B..."
    print "\t" + plain_ori
    cipher = cbc_mode.cbc_encrypt(aes_128.aes_128_encrypt, iv_a, plain_ori, key_a)

    print "Text intercepted by M is:"
    plain = cbc_mode.cbc_decrypt(aes_128.aes_128_decrypt, iv_a, cipher, key_a)
    print "\t" + plain

    print "Forwarding text from M to B..."
    cipher = cbc_mode.cbc_encrypt(aes_128.aes_128_encrypt, iv_b, plain, key_b)

    print "Text received by B is:"
    plain = cbc_mode.cbc_decrypt(aes_128.aes_128_decrypt, iv_b, cipher, key_b)
    print "\t" + plain

    if plain == plain_ori:
        print "OK"
    else:
        print "Fail"
Exemplo n.º 33
0
    def test_similar(self):
        """
        Test Similar SHA-1 Inputs
        Tests sets of messages with 1 bit of difference. Ensures that all
        messages produce unique hashes.
        """
        print('\n>>> running: test_similar')
        first_msg = bytearray(get_random_bytes())
        modified_msg = bytearray()

        # Pick a random byte, modify it by one bit
        byte_to_modify = random.randrange(0, len(first_msg))

        for i, byte in enumerate(first_msg):
            augmentor = 1 if i == byte_to_modify else 0
            modified_msg.append(byte + augmentor)

        first_digest = sha1.sha1(bytes(first_msg))
        modified_digest = sha1.sha1(bytes(modified_msg))

        print('... test_similar: checking digest differences')
        self.assertNotEqual(first_digest, modified_digest)

        print('... test_similar: success')
Exemplo n.º 34
0
 def test_sha2state(self):
     testData = [
         b"test str", b"string longer than 512 bits" + b"A" * 512,
         b"very long" + b"X" * 3000,
         bytes(range(256))
     ]
     for msg in testData:
         hash1 = sha1.sha1(msg)
         h0, h1, h2, h3, h4 = sha1.process_all(msg)
         a0, a1, a2, a3, a4 = sha1.sha2state(hash1)
         self.assertEqual(a0, h0)
         self.assertEqual(a1, h1)
         self.assertEqual(a2, h2)
         self.assertEqual(a3, h3)
         self.assertEqual(a4, h4)
Exemplo n.º 35
0
def main():
    random.seed(time.time())
    # regular communication
    message = "This is a secret message".decode("base64")

    alice = DiffieHellman(NIST_GENERATOR, NIST_PRIME)
    bob = DiffieHellman(NIST_GENERATOR, NIST_PRIME)

    bob.get_response(alice.make_secret())
    alice.get_response(bob.make_secret())

    print "Alice's key:"
    print "%r" % (alice.session_key(),)
    print "Bob's key:"
    print "%r" % (bob.session_key(),)

    assert bob.session_key() == alice.session_key()

    bob_iv = os.urandom(16)
    alice_iv = os.urandom(16)

    alice_message = alice_iv + cbc.encrypt(alice.session_key()[:16], message, IV = alice_iv)
    bob_message = bob_iv + cbc.encrypt(bob.session_key()[:16], cbc.decrypt(bob.session_key()[:16], alice_message)[16:], IV = bob_iv)

    # mitm'd
    message = "Tm8gb25lIGNhbiByZWFkIHRoaXM=".decode("base64")

    alice = DiffieHellman(NIST_GENERATOR, NIST_PRIME)
    bob = DiffieHellman(NIST_GENERATOR, NIST_PRIME)

    mitm = DiffieHellman(NIST_GENERATOR, NIST_PRIME) 
    alice.make_secret()
    bob.make_secret()
    bob.get_response(NIST_PRIME)
    alice.get_response(NIST_PRIME)

    assert bob.session_key() == alice.session_key()

    real_key = bob.session_key()

    alice_message = alice_iv + cbc.encrypt(alice.session_key()[:16], message, IV = alice_iv)
    relayed_msg = alice_message
    bob_message = bob_iv + cbc.encrypt(bob.session_key()[:16], cbc.decrypt(bob.session_key()[:16], relayed_msg)[16:], IV = bob_iv)

    injected_key = sha1.sha1(hex(0).strip("0xL")).hexdigest().decode("hex")

    print "Alice and Bob's secret message:"
    print "%r" % (cbc.decrypt(injected_key[:16], relayed_msg)[16:],)
Exemplo n.º 36
0
    def test_comparison(self):
        """Test SHA-1 Library Accuracy

        Runs the custom SHA-1 hashing function implementation with other
        SHA-1 functions contained in the Python hashlib library.
        """
        print('\n>>> running: test_comparison')
        msg = bytearray(get_random_bytes())

        custom_sha1_digest = sha1.sha1(bytes(msg))
        stdlib_sha1_digest = hashlib.sha1(bytes(msg)).hexdigest()

        print('... test_comparison: checking for identical digests')
        self.assertEqual(custom_sha1_digest, stdlib_sha1_digest)

        print('... test_comparison: success')
Exemplo n.º 37
0
    def test_comparison(self):
        """
        Test SHA-1 Library Accuracy
        Runs the custom SHA-1 hashing function implementation with other
        SHA-1 functions contained in the Python hashlib library.
        """
        print('\n>>> running: test_comparison')
        msg = bytearray(get_random_bytes())

        custom_sha1_digest = sha1.sha1(bytes(msg))
        stdlib_sha1_digest = hashlib.sha1(bytes(msg)).hexdigest()

        print('... test_comparison: checking for identical digests')
        self.assertEqual(custom_sha1_digest, stdlib_sha1_digest)

        print('... test_comparison: success')
Exemplo n.º 38
0
    def confirm_login(self, t):
        if self._A is None or self._B is None:
            print "Initiate login first"
            return None
        S = pow(self._A * pow(self._v, self._u, self._N), self._b, self._N)
        K = sha1(str(S)).hexdigest() 

        self._A = None
        self._b = None
        self._B = None

        if sha1_hmac(K).verify(self._salt, t):
            self._logged_in = True
            return True
        else:
            return False
Exemplo n.º 39
0
def calc_hmac(key, msg):
    print()
    print('***** Start calc_hmac')

    # join key with message
    combo_bytes = key + msg
    print('combo_bytes:\t', end=' ')
    print(combo_bytes)

    return_me = sha1.sha1(combo_bytes)
    print('calculated hmac:', end=' ')
    print(return_me)

    print('----- End calc_hmac')

    return return_me
def nopass(url, string, value):
    #setpass = bytes(string, 'utf-8')
    #hash_object = sha1.sha1(setpass)
    nff = 0
    sha1hash = string
    LIST_OF_COMMON_PASSWORDS = str(
        urlopen(
            'https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-10000.txt'
        ).read(), 'utf-8')
    for guess in LIST_OF_COMMON_PASSWORDS.split('\n'):
        #msg = bytearray("123456", 'UTF-8')

        # custom_sha1_digest = sha1.sha1(bytes(msg))

        hashedGuess = sha1.sha1(bytes(guess, 'utf-8'))
        ns2 = nmd5.new(guess)
        require = "789"
        if guess == "street":
            print(ns2.hexdigest)
            print(sha1hash)
        if value == 1:
            require = hashedGuess
        if value == 2:
            require = ns2.hexdigest()
        if require == sha1hash:
            br = mechanize.Browser()
            br.set_handle_robots(False)
            br.open(url)
            br.select_form(name="x")
            br["id"] = "12"
            br["password"] = str(guess)
            res = br.submit()
            content = res.read()
            with open("mechanize_results.html", "wb") as f:
                f.write(content)
                T.insert(END, content)
            T1.insert(END, str(guess))
            nff = 1

        elif require != sha1hash:
            #T.insert(END, "Password guess "+str(guess)+" does not match, trying next...\n")
            if (nff == 0):
                print("Password guess ", str(guess),
                      " does not match, trying next...")
    if nff == 0:
        T1.insert(END, "NOT FOUND")
        print("Password not in database, we'll get them next time.")
Exemplo n.º 41
0
    def test_associativity(self):
        """Test SHA-1 associativity

        Tests the fact that sha1(ab) is equivalent to sha1(a) updated with b.
        """
        print('\n>>> running: test_associativity')
        msg1 = bytearray(get_random_bytes())
        msg2 = bytearray(get_random_bytes())

        first_digest = sha1.sha1(bytes(msg1) + bytes(msg2))

        sha = sha1.Sha1Hash()
        sha.update(msg1)
        sha.update(msg2)

        second_digest = sha.hexdigest()

        print('... test_associativity: checking for identical digests')
        self.assertEqual(first_digest, second_digest)

        print('... test_associativity: success')
Exemplo n.º 42
0
    def test_associativity(self):
        """
        Test SHA-1 associativity
        Tests the fact that sha1(ab) is equivalent to sha1(a) updated with b.
        """
        print('\n>>> running: test_associativity')
        msg1 = bytearray(get_random_bytes())
        msg2 = bytearray(get_random_bytes())

        first_digest = sha1.sha1(bytes(msg1) + bytes(msg2))

        sha = sha1.Sha1Hash()
        sha.update(msg1)
        sha.update(msg2)

        second_digest = sha.hexdigest()

        print('... test_associativity: checking for identical digests')
        self.assertEqual(first_digest, second_digest)

        print('... test_associativity: success')
Exemplo n.º 43
0
def forge_signature_make_admin(signature, message):
    admin_string = ';admin=true;'

    sha_state = split_sha_into_registers(signature)
    padded_length = len(sha1.ml_pad_message(message))

    pairs = []
    for key_length in xrange(4, 512):
        original_padded_message = sha1.ml_pad_message(message,
                                                      length=(len(message) +
                                                              key_length),
                                                      faking_message=True)

        forged_message = original_padded_message + admin_string

        forged_signature = sha1.sha1(admin_string,
                                     state=sha_state,
                                     length=len(forged_message) + key_length)

        pairs.append((forged_message, forged_signature))

    return pairs
Exemplo n.º 44
0
def main():
    cipher_message = []

    # 读取消息,将ASCII码转化为16进制
    msg = read_message('./sender/messages.txt').encode()
    msg = binascii.hexlify(msg).decode('ascii')

    # des的ECB模式加密消息
    des_key = read_message('./sender/des_key.txt')
    des_cipher = des.ECB_encrypt(msg, des_key)
    cipher_message.append(des_cipher)

    # 生成rsa公钥、私钥,并写入文件
    rsa_e, rsa_n, rsa_d = rsa.createKey(15)
    if os.path.isfile('./receiver/rsa_d.txt'):
        os.remove('./receiver/rsa_d.txt')
    write_message('./receiver/rsa_d.txt', hex(rsa_d)[2:])
    if os.path.isfile('./receiver/rsa_e.txt'):
        os.remove('./receiver/rsa_e.txt')
    write_message('./receiver/rsa_e.txt', hex(rsa_e)[2:])
    if os.path.isfile('./receiver/rsa_n.txt'):
        os.remove('./receiver/rsa_n.txt')
    write_message('./receiver/rsa_n.txt', hex(rsa_n)[2:])

    # rsa加密对称密钥
    des_key_encrypted = rsa.rsa_encrypt(des_key, rsa_e, rsa_n)
    cipher_message.append(des_key_encrypted)

    # sha-1生成消息认证码
    sha1_hash = sha1.sha1(des_cipher)

    # rsa对消息认证码数字签名
    signed_hash = rsa.rsa_encrypt(sha1_hash, rsa_d, rsa_n)
    cipher_message.append(signed_hash)

    # 将消息密文,RSA加密的对称密钥,数字签名后的sha-1消息认证码发送给接收端程序
    sender(','.join(cipher_message).encode())
    print('\nSent messages:\n' + ','.join(cipher_message))
Exemplo n.º 45
0
 def login(cls, email, password):
     try:
         con = lite.connect('databases/pilearn.db')
         con.row_factory = lite.Row
         cur = con.cursor()
         cur.execute(
             "SELECT user.* FROM user, login_methods WHERE login_methods.email=? AND (login_methods.password=? OR login_methods.password='') AND login_methods.provider='local_account' AND login_methods.user_id = user.id",
             (email, sha1(password)))
         data = cur.fetchone()
         if data is None:
             return -3
         else:
             if data["mergeto"]:
                 new_id = data["mergeto"]
                 return new_id
             if data["deleted"] == 1:
                 return -4
             else:
                 return data['id']
     except lite.Error as e:
         return -3
     finally:
         if con:
             con.close()
Exemplo n.º 46
0
    def passwdreset_run_request(cls, id, code, new_pass):
        try:
            con = lite.connect('databases/pilearn.db')
            cur = con.cursor()
            cur.execute(
                "SELECT login_method_id, user_id FROM password_reset_requests WHERE id=? AND verification_code=?",
                (id, code))
            result = cur.fetchone()
            if not result: return False
            lm_id, user_id = result

            cur.execute(
                "UPDATE login_methods SET password=? WHERE id=? AND user_id=?",
                (sha1(new_pass), lm_id, user_id))
            cur.execute(
                "UPDATE password_reset_requests SET deletion_date=? WHERE id=? AND verification_code=?",
                (time.time(), id, code))
            con.commit()
            return True
        except lite.Error as e:
            return False
        finally:
            if con:
                con.close()
Exemplo n.º 47
0
def sha1_auth(mac, text):
        return (sha1.sha1(text) == mac)
Exemplo n.º 48
0
 def getMbit(self, text, m=5):
     hsh = sha1.sha1(text)
     m_bit = int(hsh, 16) % (2**m)
     return int(m_bit)
Exemplo n.º 49
0
def sha1_secret_prefix(key, message):
        return sha1.sha1(key + message)
Exemplo n.º 50
0
def MAC(key: bytes, mess: bytes) -> bytes:
    return sha1.sha1(key + mess)
Exemplo n.º 51
0
#!/usr/bin/python
# testsha1.py
# under Python 2.4
#
# Copyright (c) 2005 Michael D. Leonhard
# 
# http://tamale.net/
# 
# This file is licensed under the terms described in the
# accompanying LICENSE file.

import sha1, sys

print "sha1, Copyright (C) 2005 Michael Leonhard (http://tamale.net/)"
if len( sys.argv ) > 1:
	shaHash = sha1.sha1()
	try:
		print "Reading " + sys.argv[1] + "..."
		theFile = file( sys.argv[1], 'rb' )
		while True:
			# read a chunk
			chunk = theFile.read( 8192 )
			# reached end of file, return the header
			if len( chunk ) == 0: break;
			# process the chunk
			shaHash.update( chunk )
		theFile.close()
		print "SHA-1: " + shaHash.hexdigest()
	except IOError, e: print e
else:
	print "Testing module with examples from RFC 3174"
Exemplo n.º 52
0
 def getHash(self):
     return sha1("[id:" + str(self.id) + ",name:" + self.getTitle() +
                 "]")[:15]
Exemplo n.º 53
0
    null_bytes = 64 - ((plain_length + 9) % 64)
    padding = b'\x80' + b'\0' * null_bytes + struct.pack(b'>Q', message_bit_length)
    return padding

def init_state(hexmac, length):
    hex_parts = [hexmac[i*8:(i+1)*8] for i in range(5)]
    int_parts = [int(h, 16) for h in hex_parts]
    obj = Sha1Hash()
    obj._h = int_parts
    obj._message_byte_length = length
    return obj        

plain = b"comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
with open('word.txt', 'rb') as fp:
    key = fp.read()
mac = sha1(key + plain)

print("Original MAC:", mac)

suffix = b';is_admin=true;'
attempt = key + plain
attempt += create_padding(len(attempt))
attempt += suffix
actual_mac = sha1(attempt)
print("Actual MAC:  ", actual_mac)

obj = init_state(mac, 2 * 64) 
obj.update(suffix)
new_mac = obj.hexdigest()
print("Updated MAC: ", new_mac)
Exemplo n.º 54
0
from binascii import *

response = b"HTTP/1.x 101 Switching Protocols\r\n"

c=b"dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11"  

# generate options
options = {}
# server should reject sessions who's Origin doesn't want to process
# Options["Origin"] # RFC doesn't specifically say this required, but probably is
# options["Host"] = o["Host"] # RFC doesn't specifically say this required, but probably is
options["Upgrade"] = b"websocket"
options["Connection"] = b"Upgrade"
# unclear why this process appends an unexpected \n
options["Sec-WebSocket-Accept"] = \
    b2a_base64(unhexlify(sha1(o["Sec-WebSocket-Key"] + magic)))[:-1]
if "Sec-Websocket-Extensions" in o:
    # client should fail connection on mismatch
    options["Sec-WebSocket-Extensions"] = o["Sec-WebSocket-Extensions"]
if "Sec-WebSocket-Protocol" in o:
    # client should fail connection on mismatch
    options["Sec-WebSocket-Protocol"] = o["Sec-WebSocket-Protocol"]

opts = b""
for key in options:
    opts += bytes(key,"utf-8") + b": " + options[key] + b"\r\n"

print(opts)

conn.send(response + opts + b"\r\n")
Exemplo n.º 55
0
 def checksum(f):
   return sha1(rebase(f))
Exemplo n.º 56
0
def sha1_mac(k, message):
	return sha1(k + message)
Exemplo n.º 57
0
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0)
ss.bind(("", 5008))
ss.listen(5)

print "TCPServer1 Waiting for client on port 7998"

while 1:
        client_socket, address = ss.accept()
        
        print "I got a connection from ", address
        
        stri = client_socket.recv(1024)
        
        alist = stri.split('\n')
        print alist[0]
        checkHash=sha1.sha1(str(alist[0]))
        print checkHash
        if checkHash == alist[1]:
                print "Message is valid"
                client_socket.send("Message is Verified")
        else:
                client_socket.send("Message could not be verified")
        client_socket.close()
        ss.close()
        print "Data sent!"

        break;


'''
cipher@blackfury-HP-eNVy:~/be-2/BE1$ python server.py 
Exemplo n.º 58
0
# TCP client example
import socket
import sha1
TCP_IP = '127.0.0.1'
TCP_PORT = 5008
BUFFER_SIZE = 1024

MESSAGE = raw_input("Enter a message: ")
digest = sha1.sha1(MESSAGE)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE+"\n")#could directly use s.send(MESSAGE+"\n"+digest) i dont know why but someone told me...
s.send(digest)#could comment this.
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data
Exemplo n.º 59
0
def testSHA1_1 ():
    test_text = os.urandom(50)
    m = hashlib.sha1(test_text).hexdigest()
    
    assert m == sha1.hash_in_hex(sha1.sha1(test_text))