Ejemplo n.º 1
0
def main():
    print("=== Test of my implementation of DSA signer/verifyier ===")
    test_MyDSASigner()
    print("=== Verifying signature ===")
    msg = b"""For those that envy a MC it can be hazardous to your health\nSo be friendly, a matter of life and death, just like a etch-a-sketch\n"""
    hb = SHA.new(msg).digest()
    hi = int.from_bytes(hb, byteorder="big")
    assert hi == 0xD2D0714F014A9784047EAECCF956520045C45265  # check from website
    y = number.bytes_to_long(
        b"\x08\x4a\xd4\x71\x9d\x04\x44\x95\x49\x6a\x32\x01\xc8\xff\x48\x4f\xeb\x45\xb9\x62\xe7\x30\x2e\x56\xa3\x92\xae\xe4\xab\xab\x3e\x4b\xde\xbf\x29\x55\xb4\x73\x60\x12\xf2\x1a\x08\x08\x40\x56\xb1\x9b\xcd\x7f\xee\x56\x04\x8e\x00\x4e\x44\x98\x4e\x2f\x41\x17\x88\xef\xdc\x83\x7a\x0d\x2e\x5a\xbb\x7b\x55\x50\x39\xfd\x24\x3a\xc0\x1f\x0f\xb2\xed\x1d\xec\x56\x82\x80\xce\x67\x8e\x93\x18\x68\xd2\x3e\xb0\x95\xfd\xe9\xd3\x77\x91\x91\xb8\xc0\x29\x9d\x6e\x07\xbb\xb2\x83\xe6\x63\x34\x51\xe5\x35\xc4\x55\x13\xb2\xd3\x3c\x99\xea\x17"
    )
    r = 548099063082341131477253921760299949438196259240
    s = 857042759984254168557880549501802188789837994940
    myDSA = MyDSASigner()
    print("Verification:", myDSA.verify((r, s), hb, y))
    print("=== Breaking x from k ===")
    k = find_k(r)
    x = (s * k - hi) * number.inverse(r, q)
    x = x % q
    print("x:", x)
    print("=== Verifying x by signer ===")
    sig = myDSA.sign(hb, x, k)
    assert (r, s) == sig
    print("OK")
    print("=== Verifying x by hash ===")
    xh = hex(x)[2:]
    print("encoded x:", xh)
    ch = SHA.new(xh.encode("ascii")).digest()
    print("SHA-1 hash of x:", hex(int.from_bytes(ch, byteorder="big"))[2:])
    assert hex(int.from_bytes(ch, byteorder="big"))[2:] == "954edd5e0afe5542a4adf012611a91912a3ec16"
Ejemplo n.º 2
0
def EMSAPSSVER(M, EM, emBits, sLen = 16):
    mHash = SHA.new(M).digest()
    hLen = len(mHash)
    emLen = utils.ceil(emBits, 8)

    if emLen < hLen + sLen + 2 or EM[len(EM) - 1] != '\xbc':
        print "Inconsistent"
        return False

    maskedDB, h = EM[:emLen - hLen - 1], EM[emLen - hLen - 1: -1]

    octets, bits = (8 * emLen - emBits) / 8, (8 * emLen - emBits) % 8
    zero = maskedDB[:octets] + chr(ord(maskedDB[octets]) & ~(255 >>bits))

    for c in zero:
        if c != '\x00':
            return False

    dbMask = MGF(h, emLen - hLen - 1)
    DB = stringXOR(maskedDB, dbMask)
    newByte = chr(ord(DB[octets]) & (255 >> bits))
    DB = ('\x00' * octets) + newByte + DB[octets+1:]

    for c in DB[:emLen - hLen - sLen - 2]:
        if c != '\x00':
            return False

    if DB[emLen - hLen - sLen - 2] != '\x01':
        return False

    salt = DB[-sLen:]
    m_prime = ('\x00' * 8) + mHash + salt
    h_prime = SHA.new(m_prime).digest()

    return h_prime == h
Ejemplo n.º 3
0
def calculate_dh_secret(their_public, my_private):
    #validate public key to protect against a small subgroup attack
    if their_public < 2 or their_public > p-1:
        print("invalid public key")
        return None
    if pow(their_public, q, prime) != 1:
        print("invalid public key")
        return None
    # Calculate the shared secret
    shared_secret = pow(their_public, my_private, prime)

    # Hash the value so that:
    # (a) There's no bias in the bits of the output
    #     (there may be bias if the shared secret is used raw)
    # (b) We can convert to raw bytes easily
    # (c) We could add additional information if we wanted
    # Feel free to change SHA256 to a different value if more appropriate
    #TOM: changed to SHA-1 to comply with RFC standard

    #oid for AES-256
    keyspecificinfo = "aes 42"
    #number of bits in AES-256 key
    supppubinfo = "00 00 01 00 "
    #first block of 160 bits, we need an additional 96 bits
    KM1 = SHA.new(bytes(shared_secret + "00 00 00 01" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    KM2 = SHA.new(bytes(shared_sected + "00 00 00 02" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    KM3 = SHA.new(bytes(shared_sected + "00 00 00 03" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    #the shared hash has 60 bytes
    #we need 32 for the key and 16 more for the iv
    shared_hash = KM1 + KM2 + KM3
    return shared_hash
Ejemplo n.º 4
0
 def aes_calculate(self, msg_key, direction="to server"):
     x = 0 if direction == "to server" else 8
     sha1_a = SHA.new(msg_key + self.auth_key[x:x+32]).digest()
     sha1_b = SHA.new(self.auth_key[x+32:x+48] + msg_key + self.auth_key[48+x:64+x]).digest()
     sha1_c = SHA.new(self.auth_key[x+64:x+96] + msg_key).digest()
     sha1_d = SHA.new(msg_key + self.auth_key[x+96:x+128]).digest()
     aes_key = sha1_a[0:8] + sha1_b[8:20] + sha1_c[4:16]
     aes_iv = sha1_a[8:20] + sha1_b[0:8] + sha1_c[16:20] + sha1_d[0:8]
     return aes_key, aes_iv
Ejemplo n.º 5
0
    def checkPeer(self, addr, port, peer_pub_key, self_pub_key, connection):
        peer_pub_key_hash = SHA.new()
        peer_pub_key_hash.update(peer_pub_key)
        self_pub_key_hash = SHA.new()
        self_pub_key_hash.update(self_pub_key)

        print "Checking: addr:{}, port:{}, peer_pub_key_hash:{}, self_pub_key_hash:{}".format(
            addr, port, peer_pub_key_hash.hexdigest(), self_pub_key_hash.hexdigest())
        return True
Ejemplo n.º 6
0
def decryptAES(file, ciphertext):
    # print "AES"
    text = b''
    # base64_decoded_text = base64.b64decode(ciphertext)
    base64_decoded_text =ciphertext.decode('base64')
    key = "0xccb97558940b82637c8bec3c770f86fa3a391a56"


    #read salt from file
    fo = open(file, "rb")
    salt = readBytes(fo)

    version = struct.unpack('b', fo.read(1))[0]

    # read encryptionKey from file
    if version != -1:
        encrypt_key = readBytes(fo)
        if version >=2:
            encrypt_key = readBytes(fo)

    # var 'key2key' means RC2 key to AES key
    print "encrypt_key(%d): %s" % (len(encrypt_key), encrypt_key.encode('hex'))
    hasher = SHA.new()
    hasher.update(salt)
    hasher.update(key)
    # hasher.update(key)
    # hasher.update(salt)
    key2key = hasher.digest()
    print key2key.encode('hex')

    for i in range(1, 5):
        hasher = SHA.new()
        hasher.update(key2key)
        key2key = hasher.digest()
        print key2key.encode('hex')

    print "key2key len:", len(key2key)
    print "key2key:", key2key.encode("hex")

    print encrypt_key[:8].encode('hex')
    rc2 = ARC2.new(key2key[8:], ARC2.MODE_CBC, key2key[:8])

    print encrypt_key[8:].encode('hex')
    key = rc2.decrypt(encrypt_key)

    print "key:", key.encode('hex')


    # iv = ciphertext.index(0, 16)
    # ciphertext2 = ciphertext.index(16)
    #
    # AESCipher = AES.new(key, AES.MODE_CBC, iv)
    #
    # text = AESCipher.decrypt(ciphertext2)

    fo.close()
    return text
Ejemplo n.º 7
0
 def verify_sign(self,busi_data,sign):
     print publickey,privatekey
     signn=base64.b64decode(sign)
     h=SHA.new(busi_data)
     verifier = pk.new(publickey)
     if verifier.verify(SHA.new(busi_data), sign):
         print "verify data ok"
         return True
     else:
         print "verify data failed"
         return False
Ejemplo n.º 8
0
def test_extract_k():
    print('=== Extract k from two signatures ===')
    myDSA = MyDSASigner()
    x = 42
    k = 57
    h1 = SHA.new(b'test message 1').digest()
    h2 = SHA.new(b'test message 2').digest()
    s1 = myDSA.sign(h1, x, k)
    s2 = myDSA.sign(h2, x, k)
    k1 = extract_k(s1, s2, h1, h2)
    k2 = extract_k(s2, s1, h2, h1)
    assert k1 == k2
Ejemplo n.º 9
0
 def _checkSignaturePath(self, path, signature, maxDepth=128):
   if len(path) > maxDepth:
     return self._checkSignature(path, signature)       
   
   candidate = ''
   for index, segment in enumerate(path):
     candidate = SHA.new(candidate + segment).hexdigest()
     if hexToBase(SHA.new(candidate + str(Root.componentSecret)).hexdigest()[:20]) == signature:                
       #verify the implementations are in sync
       return self._checkSignature(path[:index+1], signature)  
   else:      
     return False
Ejemplo n.º 10
0
def addUser( configSettings, userName, passWord ):
    dbInst = DBStorage.DBStorage( "Cron", configSettings[ 'dbhost' ], configSettings[ 'dbtype' ], 
                                            userName=configSettings[ 'dbuser' ], passWord=configSettings[ 'dbpass' ] )
    dbInst.dbOpen()
    instanceCursor = dbInst.getCursor()
    sqlToRun = "SELECT userName FROM Users WHERE userName = '******';" % userName
    dbInst.execSQL( instanceCursor, sqlToRun )
    retRow = dbInst.returnSingle( instanceCursor )
    if retRow is None:
        print "Adding User: %s" % userName
        sqlToRun = "INSERT INTO Users VALUES( NULL, '%s', '%s' );" % ( userName, sha.new( passWord ).digest() )
        dbInst.execSQL( instanceCursor, sqlToRun )
    else:
        print "Updating Password For User: %s" % userName
        dbInst.execSQL( instanceCursor, "UPDATE Users SET userPassWord = '******';" % sha.new( passWord ).digest() )
Ejemplo n.º 11
0
    def run():
        #get command line arguments and initialize socket
        connection_type, hostname, k1, k2 = get_args()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        #calculate first 128 bits of hash of key k1
        k1_sha = SHA.new(k1.encode())
        k1_sha_digest_128 = k1_sha.digest()[:16]

        #calculate first 128 bits of hash of key k1
        k2_sha = SHA.new(k2.encode())
        k2_sha_digest_128 = k2_sha.digest()[:16]

        if connection_type == 'client':
            try:
                s.connect((hostname, PORT_NUM))
                inputs_list = [s, sys.stdin]
                outputs_list = [s]

                #starts listening for a message from the server or user inpu
                while True:
                    inputs_ready, outputs_ready, exceptions_ready = select.select(inputs_list, outputs_list, [])
                    for curr_socket in inputs_ready:
                        if curr_socket == sys.stdin:
                            send_message(k1_sha_digest_128, k2_sha_digest_128, outputs_ready)
                        elif curr_socket == s:
                            receive_message(curr_socket, k1_sha_digest_128, k2_sha_digest_128, inputs_list, outputs_list)
            except socket.error:
                print 'No active server at specified hostname'

        elif connection_type == 'server':
            s.bind(('', PORT_NUM))
            s.listen(1)
            inputs_list = [s, sys.stdin]
            outputs_list = []

            #start listening for hosts trying to connect, user input or messages from the client
            while True:
                inputs_ready, outputs_ready, exceptionsReady = select.select(inputs_list, outputs_list, [])
                for curr_socket in inputs_ready:
                    if curr_socket == s:
                        c, addr = s.accept()
                        inputs_list.append(c)
                        outputs_list.append(c)
                    elif curr_socket == sys.stdin:
                        send_message(k1_sha_digest_128, k2_sha_digest_128, outputs_ready)
                    else:
                       receive_message(curr_socket, k1_sha_digest_128, k2_sha_digest_128, inputs_list, outputs_list)
Ejemplo n.º 12
0
 def _parse_kexdh_init(self, m):
     # server mode
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > P - 1):
         raise SSHException('Client kex "e" is out of range')
     K = pow(self.e, self.x, P)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init)
     hm.add_string(key)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.rng, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Ejemplo n.º 13
0
 def Generate(self):
     if not os.path.exists(self.source_dir_):
         print("The source directory %s is invalid." % self.source_dir_)
         return
     try:
         zip_file = '%s.tmp' % self.output_file_
         self.__Compress(self.source_dir_, zip_file)
         signer = PKCS1_v1_5.new(self.RSAkey)
         zfile = open(zip_file, 'rb')
         sha = SHA.new(zfile.read())
         signature = signer.sign(sha)
         xpk = open(self.output_file_, 'wb')
         zfile.seek(0)
         print('Generating XPK package: %s' % self.output_file_)
         xpk.write('\x43\x72\x57\x6B')
         xpk.write(struct.pack('<I', len(self.pubkey)))
         xpk.write(struct.pack('<I', len(signature)))
         xpk.write(self.pubkey)
         xpk.write(signature)
         xpk.write(zfile.read())
         zfile.close()
         xpk.close()
         print('Generated new XPK package %s successfully.'
               % self.output_file_)
     except IOError:
         if os.path.exists(self.output_file_):
             os.remove(self.output_file_)
         traceback.print_exc()
     finally:
         if os.path.exists(zip_file):
             os.remove(zip_file)
Ejemplo n.º 14
0
 def _parse_kexdh_gex_init(self, m):
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > self.p - 1):
         raise SSHException('Client kex "e" is out of range')
     self._generate_x()
     self.f = pow(self.g, self.x, self.p)
     K = pow(self.e, self.x, self.p)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init,
            key)
     if not self.old_style:
         hm.add_int(self.min_bits)
     hm.add_int(self.preferred_bits)
     if not self.old_style:
         hm.add_int(self.max_bits)
     hm.add_mpint(self.p)
     hm.add_mpint(self.g)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.randpool, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Ejemplo n.º 15
0
 def _verify_sign(self, public_key, sign_str, sign):
     rsa_key = RSA.importKey(public_key)
     signer = PKCS1_v1_5.new(rsa_key)
     digest = SHA.new(sign_str)
     if signer.verify(digest, base64.decodestring(sign)):
         return True
     return False
Ejemplo n.º 16
0
 def _parse_kexdh_gex_reply(self, m):
     host_key = m.get_string()
     self.f = m.get_mpint()
     sig = m.get_string()
     if (self.f < 1) or (self.f > self.p - 1):
         raise SSHException('Server kex "f" is out of range')
     K = pow(self.f, self.x, self.p)
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K)
     hm = Message()
     hm.add(self.transport.local_version, self.transport.remote_version,
            self.transport.local_kex_init, self.transport.remote_kex_init,
            host_key)
     if not self.old_style:
         hm.add_int(self.min_bits)
     hm.add_int(self.preferred_bits)
     if not self.old_style:
         hm.add_int(self.max_bits)
     hm.add_mpint(self.p)
     hm.add_mpint(self.g)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     self.transport._set_K_H(K, SHA.new(str(hm)).digest())
     self.transport._verify_key(host_key, sig)
     self.transport._activate_outbound()
Ejemplo n.º 17
0
def sign(message, sender_private_key):

    h = SHA.new(message)
    signer = PKCS1_v1_5.new(sender_private_key)
    signature = signer.sign(h)
    
    return signature
Ejemplo n.º 18
0
def H2(message):
	# hash the message
	digest = SHA.new(message).hexdigest()
	# convert to integer
	x = int(digest, 16)
	# take it mod p
	return x % p
Ejemplo n.º 19
0
 def randomize(self, N = 0):
     "Adds N bits of entropy to random pool.  If N is 0, fill up pool."
     import os, string, time
     if N <= 0:
         bits = self.bits - self.entropy
     else:
         bits = N*8
     if bits == 0:
         return
     #rintbits,'bits of entropy are now required.  Please type on the keyboard'
     #rint'until enough randomness has been accumulated.'
     kb = KeyboardEntry()
     s=''    # We'll save the characters typed and add them to the pool.
     hash = self._hash
     e = 0
     try:
         while e < bits:
             temp=str(bits-e).rjust(6)
             os.write(1, temp)
             s=s+kb.getch()
             e += self.add_event(s)
             os.write(1, 6*chr(8))
         self.add_event(s+hash.new(s).digest() )
     finally:
         kb.close()
     #rint'\n\007 Enough.  Please wait a moment.\n'
     self.stir_n()   # wash the random pool.
     kb.close(4)
Ejemplo n.º 20
0
def asymmetricSign(message, key):
	"""Returns a signature of inpString signed with 'key'."""
	key = RSA.importKey(key)
	h = SHA.new()
	h.update(message)
	signer = PKCS1_PSS.new(key)
	return binascii.b2a_base64(signer.sign(h))
Ejemplo n.º 21
0
def pam_conv(auth,query_list,userdata):
	resp = []

	for i in range(len(query_list)):
		query, type = query_list[i]
		if type == PAM.PAM_PROMPT_ECHO_ON:
			val = raw_input(query)
			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ECHO_OFF:
			challenge = os.urandom(20)
			sha1 = SHA.new(challenge)
			sha1.update(challenge)
			digest = sha1.digest()
			print "PYTHON digest: %s" % digest
			print "PYTHON Encoded digest: %s" % base64.b64encode(digest)
			cc = ccHandler()
			cc.openSession()
			signed = cc.sign(challenge)
			val = base64.b64encode(digest)+'-'+signed

			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ERROR_MSG or type == PAM.PAM_PROMPT_TEXT_INFO:
			print query
			resp.append(('', 0))
		else:
			return None

	return resp
Ejemplo n.º 22
0
def rsa_sign(para_str):
    """对请求参数做rsa签名"""
    para_str = para_str.encode('utf-8')
    key = RSA.importKey(settings.ALIPAY_PRIVATE_KEY)
    h = SHA.new(para_str)
    signer = PKCS1_v1_5.new(key)
    return base64.b64encode(signer.sign(h))
Ejemplo n.º 23
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32+dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
Ejemplo n.º 24
0
def sign_rsa_sha1(base_string, rsa_private_key):
    """**RSA-SHA1**

    Per `section 3.4.3`_ of the spec.

    The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
    algorithm as defined in `RFC3447, Section 8.2`_ (also known as
    PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5.  To
    use this method, the client MUST have established client credentials
    with the server that included its RSA public key (in a manner that is
    beyond the scope of this specification).

    NOTE: this method requires the python-rsa library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3
    .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2

    """
    # TODO: finish RSA documentation
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA

    key = RSA.importKey(rsa_private_key)
    if isinstance(base_string, unicode_type):
        base_string = base_string.encode("utf-8")
    h = SHA.new(base_string)
    p = PKCS1_v1_5.new(key)
    return binascii.b2a_base64(p.sign(h))[:-1].decode("utf-8")
Ejemplo n.º 25
0
def sign(xml, private, public, cert, sign_element='</s:Security>'):
    '''
    Return xmldsig XML string from xml_string of XML.
    @param xml: str of bytestring xml to sign
    @param private: publicKey Private key
    @param public: publicKey Public key
    @return str: signed XML byte string
    '''
    if isinstance(xml, unicode):
        xml = xml.encode('utf-8', 'xmlcharrefreplace')
    signed_info_xml = _generate_signed_info(xml)

    signer = PKCS1_v1_5.PKCS115_SigScheme(private)
    signature_value = signer.sign(SHA.new(c14n(signed_info_xml)))

    signature_xml = PTN_SIGNATURE_XML % {
        'signed_info_xml': signed_info_xml,
        'signature_value': binascii.b2a_base64(signature_value)[:-1],
        'key_info_xml': _generate_key_info_xml_rsa(public.key.n,
                                                   public.key.e,
                                                   cert)
    }

    position = xml.rfind(sign_element)
    return xml[0:position] + signature_xml + xml[position:]
Ejemplo n.º 26
0
    def _get_build_list_sha1(self):
        sha = SHA.new()
        # add public key and then LF to hash
        pem_ck = self._public_key.exportKey('PEM')
        sha.update(pem_ck)
        sha.update(BuildList.NEWLINE)

        # add title and LF to hash
        sha.update(self._title.encode('utf-8'))
        sha.update(BuildList.NEWLINE)

        # add timestamp and LF to hash
        sha.update(self.timestamp.encode('utf-8'))
        sha.update(BuildList.NEWLINE)

        # add CONTENT_START and LF line to hash
        sha.update((BuildList.CONTENT_START + '\n').encode('utf-8'))

        # add serialized NLHTree to hash, each line terminated by LF
        sha.update(self._tree.__str__().encode('utf-8'))

        # add CONTENT_END and LF line to hash
        sha.update((BuildList.CONTENT_END + '\n').encode('utf-8'))

        # add LF to hash
        sha.update(BuildList.NEWLINE)
        return sha
Ejemplo n.º 27
0
def encrypt(N, e, message, L = ""):
    lHash = SHA.new(L).digest()
    hLen = len(lHash)
    mLen = len(message)
    k = numOctets(N)

    if mLen > k - (2*hLen) - 2:
        print "Message too long"
        return -1

    lPS = (k - mLen - 2*hLen - 2)
    PS = '\x00' * lPS
    DB = ''.join((lHash, PS, '\x01', message))

    seed = I2OSP(utils.gen_random(hLen * 8), hLen)

    dbMask = MGF(seed, k - hLen - 1)
    maskedDB = stringXOR(DB, dbMask)

    seedMask = MGF(maskedDB, hLen)
    maskedSeed = stringXOR(seed, seedMask)

    EM = ''.join(('\x00', maskedSeed, maskedDB))

    m = OS2IP(EM)

    c = RSAEP(N, e, m)

    cipherText = I2OSP(c, k)

    return cipherText
Ejemplo n.º 28
0
	def do_GET(self):
		"""Sends commands b64 encoded in HTTP responses
		"""
		global last_command, output_ready,command_ready,password, salt
		if ((self.client_address[0] == socket.gethostbyname(host)) and command_ready):
			self.send_response(200) # begin sending response
			if encrypt:
				salt = self.headers["Content-Salt"].strip() # extract the salt the client is using
				if verbose: print "received salt from client: "+salt
				hasher = SHA.new() # new hasher
				hasher.update(password + salt) # create the hash of the string passwordsalt
				rc4 = ARC4.new(hasher.hexdigest()) # use the hash for password to avoid weak key scheduling 
				self.end_headers() # end of response headers
				self.wfile.write(base64.b64encode(rc4.encrypt(last_command))) # send payload
			else: 
				# send payload without encryption
				self.end_headers()
				self.wfile.write(base64.b64encode(last_command))
			command_ready=False # wait for next command
			
		else:
			# GET does not come from the client we are currently listening to or there is no command available yet
			self.send_response(200) # send empty response and end
			self.send_header("Content-Type","0") # no command issued
			self.end_headers()
			
		# Check special header to know client current polling period
		if "Next-Polling-In" in self.headers:
			global next_polling,timestamp,client_sync
			next_polling = self.headers["Next-Polling-In"] # so the server can calculate roughly next polling
			# set the time of last request
			timestamp = int(time.time())
			client_sync = True
Ejemplo n.º 29
0
    def parse_response(self, form, success=True):
        """Parse and return payment response."""
        fields = {
            # Successful payment
            '1101': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',   #  6..10
                     'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'),    # 11..15
            # Unsuccessful payment
            '1901': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'REF', 'MSG')                                      #  6..7
        }
        # See which response we got
        resp = form.get('VK_SERVICE', None)
        if not resp and resp not in fields:
            raise InvalidResponseError
        success = resp == '1101'

        Random.atfork()

        # Parse and validate MAC
        m = self._build_mac(fields[resp], form)
        f = lambda x: form.get('VK_%s' % x)
        if not PKCS1_v1_5.new(self.keychain.public_key) \
                         .verify(SHA.new(m), b64decode(f('MAC'))):
            raise InvalidResponseError
        # Save payment data
        data = {}
        if success:
            for item in ('T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',
                         'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'):
                data[item] = f(item)
        return PaymentResponse(self, data, success)
Ejemplo n.º 30
0
def encrypt_for_master(data):
    # Encrypt the file so it can only be read by the bot master
    h=SHA.new(data)
    key = RSA.importKey(open(os.path.join("pastebot.net", "master_rsa.pub")).read())
    cipher = PKCS1_v1_5.new(key)
    ciphertext = cipher.encrypt(data+h.digest())
    return ciphertext
Ejemplo n.º 31
0
def update():
    validate_uuid = UUID(request.form['uuid'])
    uuid = str(validate_uuid)
    session = ws.hashlib.sha256(config.SESSION_SECRET + uuid).hexdigest()
    email = request.form['email'] if 'email' in request.form else None

    if config.LOCALDEVBYPASSDB:
        session_challenge = session + "_challenge"
        session_pubkey = session + "_public_key"

        if session_challenge not in session_store:
            print 'Challenge not in session'
            abort(403)

        if session_pubkey not in session_store:
            print 'Public key not in session'
            abort(403)

        challenge = session_store.get(session_challenge)
        signature = request.form['signature']
        wallet = request.form['wallet']
        pubkey = session_store.get(session_pubkey)

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print 'Challenge signature not verified'
            abort(403)

        write_wallet(uuid, wallet)
        session_store.delete(session_challenge)
    else:
        ROWS = dbSelect(
            "select challenge,pubkey from sessions where sessionid=%s",
            [session])
        if len(ROWS) == 0 or ROWS[0][0] == None:
            print 'Challenge not in session'
            abort(403)

        if len(ROWS) == 0 or ROWS[0][1] == None:
            print 'Public key not in session'
            abort(403)

        challenge = ROWS[0][0]
        signature = request.form['signature']
        wallet = request.form['wallet']
        pubkey = ROWS[0][1]

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print 'Challenge signature not verified'
            abort(403)

        write_wallet(uuid, wallet, email)
        dbExecute(
            "update sessions set challenge=NULL, timestamp=DEFAULT where sessionid=%s",
            [session])
        dbCommit()

    return ""
Ejemplo n.º 32
0
def cc42():
    """42. Bleichenbacher's e=3 RSA Attack

RSA with an encrypting exponent of 3 is popular, because it makes the
RSA math faster.

With e=3 RSA, encryption is just cubing a number mod the public
encryption modulus:

  c = m ** 3 % n

e=3 is secure as long as we can make assumptions about the message
blocks we're encrypting. The worry with low-exponent RSA is that the
message blocks we process won't be large enough to wrap the modulus
after being cubed. The block 00:02 (imagine sufficient zero-padding)
can be "encrypted" in e=3 RSA; it is simply 00:08.

When RSA is used to sign, rather than encrypt, the operations are
reversed; the verifier "decrypts" the message by cubing it. This
produces a "plaintext" which the verifier checks for validity.

When you use RSA to sign a message, you supply it a block input that
contains a message digest. The PKCS1.5 standard formats that block as:

 00h 01h ffh ffh ... ffh ffh 00h ASN.1 GOOP HASH

As intended, the ffh bytes in that block expand to fill the whole
block, producing a "right-justified" hash (the last byte of the hash
is the last byte of the message).

There was, 7 years ago, a common implementation flaw with RSA
verifiers: they'd verify signatures by "decrypting" them (cubing them
modulo the public exponent) and then "parsing" them by looking for
00h 01h ... ffh 00h ASN.1 HASH.

This is a bug because it implies the verifier isn't checking all the
padding. If you don't check the padding, you leave open the
possibility that instead of hundreds of ffh bytes, you have only a
few, which if you think about it means there could be squizzilions of
possible numbers that could produce a valid-looking signature.

How to find such a block? Find a number that when cubed (a) doesn't
wrap the modulus (thus bypassing the key entirely) and (b) produces a
block that starts "00h 01h ffh ... 00h ASN.1 HASH".

There are two ways to approach this problem:

* You can work from Hal Finney's writeup, available on Google, of how
 Bleichenbacher explained the math "so that you can do it by hand
 with a pencil".

* You can implement an integer cube root in your language, format the
 message block you want to forge, leaving sufficient trailing zeros
 at the end to fill with garbage, then take the cube-root of that
 block.

Forge a 1024-bit RSA signature for the string "hi mom". Make sure your
implementation actually accepts the signature!
"""
    print """Note: pycrypto explicitly checks for this attack
(see https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Signature/PKCS1_v1_5.py#L159)
so this uses an intentionally broken signature verifier that doesn't check padding.
"""

    def broken_verify_rsa_sha1(msg, key, sig):
        asn1_sha1 = '\x000!0\t\x06\x05+\x0e\x03\x02\x1a\x05\x00\x04\x14'
        h = hashlib.sha1(msg).digest()

        m = key.encrypt(sig, 0)[0]
        offset = m.find('\xff\x00') + 1
        asn1_hash = m[offset:offset + 36]
        if asn1_hash == asn1_sha1 + h:
            return True
        return False

    msg = "hi mom"

    #generate sig with throwaway key to get asn1+hash
    key = RSA.generate(1024, e=3)
    h = SHA.new(msg)
    ss = PKCS1_v1_5.new(key)
    psig = ss.sign(h)
    raw = key.encrypt(psig, 0)[0]
    print 'Generate sig with throwaway key to get asn1+hash'
    print 'Valid Sig:', raw.encode('hex')
    print 'Verified: ', broken_verify_rsa_sha1(msg, key, psig)

    #build the new block
    asn1_hash = raw[raw.find('\xff\x00') + 1:]
    prefix = '\x01' + '\xff' * 4
    suffix = '\x01' * 87
    sig = prefix + asn1_hash + suffix
    #print sig.encode('hex')
    x = bytes_to_long(sig)
    newsig = nth_root(x, 3)

    #generate new key with e=3 to test forgery
    key = RSA.generate(1024, e=3)
    print
    print 'Test forgery with new key'
    print 'Forged Sig:', long_to_bytes(newsig**3).encode('hex')
    print 'Verified: ', broken_verify_rsa_sha1(msg, key, long_to_bytes(newsig))
Ejemplo n.º 33
0
if __name__ == '__main__':
    try:
        addr = '127.0.0.1'
        port = 4444
        sock = socket.socket()
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        sock.bind((addr, port))
        sock.listen(1)
        print('Listening on ' + addr + ':' + str(port) + '.')
        clients = load_json()
        while True:
            if available(sock):
                client, addr = sock.accept()
                uid = str(SHA.new(str(uuid.uuid1())).hexdigest())
                clients[uid] = client_t(uid, client)
            keep_clients = {}
            for key in clients:
                if clients[key].update():
                    keep_clients[key] = clients[key]
                    save_json(keep_clients)
                else:
                    print(key + ': Removed.')
            clients = keep_clients
            time.sleep(0.1)
    except KeyboardInterrupt:
        exit(1)
    except Exception as error:
        print('Error - ' + str(error))
        exit(1)
Ejemplo n.º 34
0
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA

# Verify
h = open("studentEncrypted.txt", "rb").read()
h = SHA.new(h)

signature = open("digitalLicense.txt", "rb").read()
key = RSA.importKey(open('public_key.pem').read())
verifier = PKCS1_v1_5.new(key)
if verifier.verify(h, signature):
    print("The signature is authentic.")
else:
    print("The signature is not authentic.")
Ejemplo n.º 35
0
    print "解密(decrypt)"
    print "message:" + text

    assert text == message, 'decrypt falied'

# 签名与验签
print "3、 签名与验签"

# Master 使用自己的私钥对内容进行签名
print "签名"
with open('master-private.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    signer = Signature_pkcs1_v1_5.new(rsakey)
    digest = SHA.new()
    digest.update(message)
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)

print signature

print "验签"
with open('master-public.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    verifier = Signature_pkcs1_v1_5.new(rsakey)
    digest = SHA.new()
    # Assumes the data is base64 encoded to begin with
    digest.update(message)
    is_verify = verifier.verify(digest, base64.b64decode(signature))
def get_signature(key, data):
    return PKCS1_v1_5.new(key).sign(SHA.new(data))
Ejemplo n.º 37
0
    def verify(self, data, sig):
        """Verify the signature on a block of data"""

        return PKCS1_v1_5.new(self._key).verify(SHA.new(data), sig)
Ejemplo n.º 38
0
def miner(q, privatekey_readable, public_key_hashed, address):
    from Crypto.PublicKey import RSA
    Random.atfork()
    key = RSA.importKey(privatekey_readable)
    rndfile = Random.new()
    tries = 0
    firstrun = True
    begin = time.time()

    if pool_conf == 1:
        #do not use pools public key to sign, signature will be invalid

        self_address = address
        address = pool_address

        #ask for diff percentage
        s_pool = socks.socksocket()
        s_pool.settimeout(0.3)
        if tor_conf == 1:
            s_pool.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        s_pool.connect((pool_ip_conf, 8525))  # connect to pool
        print("Connected")

        print(
            "Miner: Asking pool for share qualification difficulty requirement"
        )
        connections.send(s_pool, "diffp", 10)
        pool_diff_percentage = int(connections.receive(s_pool, 10))
        print(
            "Miner: Received pool for share qualification difficulty requirement: {}%"
            .format(pool_diff_percentage))
        s_pool.close()
        #ask for diff percentage

    while True:
        try:

            # calculate new hash
            nonces = 0
            # calculate difficulty
            s_node = socks.socksocket()
            if tor_conf == 1:
                s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
            s_node.connect((node_ip_conf, int(port)))  # connect to local node

            connections.send(s_node, "blocklast", 10)
            blocklast = connections.receive(s_node, 10)
            db_block_hash = blocklast[7]

            connections.send(s_node, "diffget", 10)
            diff = connections.receive(s_node, 10)
            s_node.close()

            diff = int(diff[1])

            diff_real = int(diff)

            if pool_conf == 0:
                diff = int(diff)

            else:  # if pooled
                diff_pool = diff_real
                diff = percentage(pool_diff_percentage, diff_real)

                if diff > diff_pool:
                    diff = diff_pool

            mining_condition = bin_convert(db_block_hash)[0:diff]

            # block_hash = hashlib.sha224(str(block_send) + db_block_hash).hexdigest()

            while tries < diff_recalc_conf:
                start = time.time()

                nonce = hashlib.sha224(rndfile.read(16)).hexdigest()[:32]
                mining_hash = bin_convert(
                    hashlib.sha224(
                        (address + nonce +
                         db_block_hash).encode("utf-8")).hexdigest())

                end = time.time()
                if tries % 2500 == 0:  #limit output
                    try:
                        cycles_per_second = 1 / (end - start)
                        print(
                            "Thread{} {} @ {:.2f} cycles/second, difficulty: {}({}), iteration: {}"
                            .format(q, db_block_hash[:10], cycles_per_second,
                                    diff, diff_real, tries))
                    except:
                        pass
                tries = tries + 1

                if mining_condition in mining_hash:
                    tries = 0

                    print("Thread {} found a good block hash in {} cycles".
                          format(q, tries))

                    # serialize txs

                    block_send = []
                    del block_send[:]  # empty
                    removal_signature = []
                    del removal_signature[:]  # empty

                    s_node = socks.socksocket()
                    if tor_conf == 1:
                        s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1",
                                        9050)
                    s_node.connect((node_ip_conf,
                                    int(port)))  # connect to config.txt node
                    connections.send(s_node, "mpget", 10)
                    data = connections.receive(s_node, 10)
                    s_node.close()

                    if data != "[]":
                        mempool = data

                        for mpdata in mempool:
                            transaction = (str(mpdata[0]), str(mpdata[1][:56]),
                                           str(mpdata[2][:56]),
                                           '%.8f' % float(mpdata[3]),
                                           str(mpdata[4]), str(mpdata[5]),
                                           str(mpdata[6]), str(mpdata[7])
                                           )  # create tuple
                            # print transaction
                            block_send.append(
                                transaction
                            )  # append tuple to list for each run
                            removal_signature.append(
                                str(mpdata[4]
                                    ))  # for removal after successful mining

                    # claim reward
                    block_timestamp = '%.2f' % time.time()
                    transaction_reward = (str(block_timestamp),
                                          str(address[:56]), str(address[:56]),
                                          '%.8f' % float(0), "0", str(nonce)
                                          )  # only this part is signed!
                    # print transaction_reward

                    h = SHA.new(str(transaction_reward).encode("utf-8"))
                    signer = PKCS1_v1_5.new(key)
                    signature = signer.sign(h)
                    signature_enc = base64.b64encode(signature)

                    if signer.verify(h, signature) == True:
                        print("Signature valid")

                        block_send.append(
                            (str(block_timestamp), str(address[:56]),
                             str(address[:56]), '%.8f' % float(0),
                             str(signature_enc.decode("utf-8")),
                             str(public_key_hashed), "0",
                             str(nonce)))  # mining reward tx
                        print("Block to send: {}".format(block_send))
                        #  claim reward
                        # include data

                        tries = 0

                        # submit mined block to node

                        if sync_conf == 1:
                            check_uptodate(300)

                        if pool_conf == 1:
                            mining_condition = bin_convert(
                                db_block_hash)[0:diff_real]
                            if mining_condition in mining_hash:
                                print(
                                    "Miner: Submitting block to all nodes, because it satisfies real difficulty too"
                                )
                                nodes_block_submit(block_send)

                            try:
                                s_pool = socks.socksocket()
                                s_pool.settimeout(0.3)
                                if tor_conf == 1:
                                    s_pool.setproxy(socks.PROXY_TYPE_SOCKS5,
                                                    "127.0.0.1", 9050)
                                s_pool.connect(
                                    (pool_ip_conf, 8525))  # connect to pool
                                print("Connected")

                                print(
                                    "Miner: Proceeding to submit mined block to pool"
                                )

                                connections.send(s_pool, "block", 10)
                                connections.send(s_pool, self_address, 10)
                                connections.send(s_pool, block_send, 10)
                                s_pool.close()

                                print("Miner: Block submitted to pool")

                            except Exception as e:
                                print("Miner: Could not submit block to pool")
                                pass

                        if pool_conf == 0:
                            nodes_block_submit(block_send)
                    else:
                        print("Invalid signature")
            tries = 0

        except Exception as e:
            print(e)
            time.sleep(0.1)
            if debug_conf == 1:
                raise
            else:
                pass
def get_checksum(data):
    return SHA.new(data).digest()
Ejemplo n.º 40
0
from Crypto.Hash import SHA
from gmpy2 import *
anSHA1 = '0954edd5e0afe5542a4adf012611a91912a3ec16'
sha = SHA.new()
sha.update('''For those that envy a MC it can be hazardous to your health
So be friendly, a matter of life and death, just like a etch-a-sketch
''')
H = sha.hexdigest()
p = 0x800000000000000089e1855218a0e7dac38136ffafa72eda7859f2171e25e65eac698c1702578b07dc2a1076da241c76c62d374d8389ea5aeffd3226a0530cc565f3bf6b50929139ebeac04f48c3c84afb796d61e5a4f9a8fda812ab59494232c7d2b4deb50aa18ee9e132bfa85ac4374d7f9091abc3d015efc871a584471bb1
q = 0xf4f47f05794b256174bba6e9b396a7707e563c5b
g = 0x5958c9d3898b224b12672c0b98e06c60df923cb8bc999d119458fef538b8fa4046c8db53039db620c094c9fa077ef389b5322a559946a71903f990f1f7e0e025e2d7f7cf494aff1a0470f5b64c36b625a097f1651fe775323556fe00b3608c887892878480e99041be601a62166ca6894bdd41a7054ec89f756ba9fc95302291
r0 = 548099063082341131477253921760299949438196259240
s = 857042759984254168557880549501802188789837994940
for k in xrange(65537):
    r = pow(g, k, p) % q
    if r == r0:
        x = (s*k - int(H,16)) * invert(r,q) % q
        print 'x : ', x
        break
Ejemplo n.º 41
0
def generate_hash() -> str:
    """Generates a hash str"""
    return SHA.new(
        str(rando()).encode(
        lambdacoin.constants.STRING_ENCODING)).\
        hexdigest()
Ejemplo n.º 42
0
print("[MITM] B->M: B")
#print("B: "+str(bigB))

print("[MITM] M->A: p")
#print("p: "+str(p))

print("\n[MITM] A has Key: (p ** a) % p")

print("[MITM] B has Key: (p ** b) % p")
print("[MITM] M has Key: \n(p ** a) % p\n(p ** b) % p\n(A ** b) % p")

###A->B###
print("\n[MITM] A->M:")
iv=random.Random.get_random_bytes(16)
k_a2m=SHA.new(str(pow(p,a,p)).encode()).digest()
e_a=AES.new(k_a2m[:16],AES.MODE_CBC,iv)
m_a="A"*16
message_a2m=e_a.encrypt(m_a.encode())+iv
print(message_a2m)

print("\n[MITM] M read message from A with key (p ** a) % p: ")
d_a2m=AES.new(k_a2m[:16],AES.MODE_CBC,message_a2m[16:])
p_a2m=d_a2m.decrypt(message_a2m[:16])
print(p_a2m.decode())
print("[MITM] And M pack this message with key (p ** b) % p and relay to B: ")
k_m2b=SHA.new(str(pow(p,b,p)).encode()).digest()
iv_m2b=random.Random.get_random_bytes(16)
e_m2b=AES.new(k_m2b[:16],AES.MODE_CBC,iv_m2b)
message_m2b=e_m2b.encrypt(p_a2m)+iv_m2b
print(message_m2b)
Ejemplo n.º 43
0
    def merge(self, data, peer_ip, c, size_bypass=False, wait=False, revert=False):
        """
        Checks and merge the tx list in out mempool
        :param data:
        :param peer_ip:
        :param c:
        :param size_bypass: if True, will merge whatever the mempool size is
        :param wait: if True, will wait until the main db_lock is free. if False, will just drop.
        :param revert: if True, we are reverting tx from digest_block, so main lock is on. Don't bother, process without lock.
        :return:
        """
        if not data:
            return "Mempool from {} was empty".format(peer_ip)

        mempool_result = []

        if data == '*':
            raise ValueError("Connection lost")

        try:
            if self.peers_sent[peer_ip] > time.time():
                self.app_log.warning("Mempool ignoring merge from frozen {}".format(peer_ip))
                mempool_result.append("Mempool ignoring merge from frozen {}".format(peer_ip))
                return mempool_result
        except:
            # unknown peer
            pass

        if not essentials.is_sequence(data):
            with self.peers_lock:
                self.peers_sent[peer_ip] = time.time() + 10 * 60
            self.app_log.warning("Freezing mempool from {} for 10 min - Bad TX format".format(peer_ip))
            mempool_result.append("Bad TX Format")
            return mempool_result

        mempool_result.append("Mempool merging started from {}".format(peer_ip))

        if not revert:
            while self.db_lock.locked():  # prevent transactions which are just being digested from being added to mempool
                if not wait:
                    # not reverting, but not waiting, bye
                    # By default, we don't wait.
                    mempool_result.append("Locked ledger, dropping txs")
                    return mempool_result
                self.app_log.warning("Waiting for block digestion to finish before merging mempool")
                time.sleep(1)
        # if reverting, don't bother with main lock, go on.

        mempool_size = self.size()  # caulculate current mempool size before adding txs

        # TODO: we check main ledger db is not locked before beginning, but we don't lock? ok, see comment in node.py. since it's called from a lock, it would deadlock.
        # merge mempool
        #while self.lock.locked():
        #    time.sleep(1)
        with self.lock:
            try:
                block_list = data

                if not isinstance(block_list[0], list):  # convert to list of lists if only one tx and not handled
                    block_list = [block_list]

                for transaction in block_list:  # set means unique, only accepts list of txs

                    if (mempool_size < 0.3 or size_bypass) or \
                            (len(str(transaction[7])) > 200 and mempool_size < 0.4) \
                            or (Decimal(transaction[3]) > Decimal(5) and mempool_size < 0.5) \
                            or (transaction[1] in self.config.mempool_allowed and mempool_size < 0.6):
                        # condition 1: size limit or bypass,
                        # condition 2: spend more than 25 coins,
                        # condition 3: have length of openfield larger than 200
                        # all transactions in the mempool need to be cycled to check for special cases,
                        # therefore no while/break loop here

                        mempool_timestamp = '%.2f' % (quantize_two(transaction[0]))
                        mempool_address = str(transaction[1])[:56]
                        mempool_recipient = str(transaction[2])[:56]
                        mempool_amount = '%.8f' % (quantize_eight(transaction[3]))  # convert scientific notation
                        mempool_signature_enc = str(transaction[4])[:684]
                        mempool_public_key_hashed = str(transaction[5])[:1068]
                        mempool_operation = str(transaction[6])[:10]
                        mempool_openfield = str(transaction[7])[:100000]

                        # convert readable key to instance
                        mempool_public_key = RSA.importKey(base64.b64decode(mempool_public_key_hashed))
                        mempool_signature_dec = base64.b64decode(mempool_signature_enc)

                        acceptable = True

                        try:
                            # TODO: sure it will throw an exception?
                            # condition 1)
                            dummy = self.fetchall("SELECT * FROM transactions WHERE signature = ?;",
                                                  (mempool_signature_enc,))
                            if dummy:
                                # self.app_log.warning("That transaction is already in our mempool")
                                mempool_result.append("That transaction is already in our mempool")
                                acceptable = False
                                mempool_in = True
                            else:
                                mempool_in = False
                        except:
                            #print('sigmempool NO ', mempool_signature_enc)
                            mempool_in = False

                        # reject transactions which are already in the ledger
                        # TODO: not clean, will need to have ledger as a module too.
                        # dup code atm.
                        essentials.execute_param_c(c, "SELECT * FROM transactions WHERE signature = ?;",
                                        (mempool_signature_enc,), self.app_log)  # condition 2
                        try:
                            dummy = c.fetchall()[0]
                            #print('sigledger', mempool_signature_enc, dummy)
                            if dummy:
                                mempool_result.append("That transaction is already in our ledger")
                                # self.app_log.warning("That transaction is already in our ledger")
                                # reject transactions which are already in the ledger
                                acceptable = False
                                ledger_in = True
                                # Can be a syncing node. Do not request mempool from this peer until 10 min
                                with self.peers_lock:
                                    self.peers_sent[peer_ip] = time.time() + 10*60
                                self.app_log.warning("Freezing mempool from {} for 10 min.".format(peer_ip))
                                return mempool_result
                            else:
                                ledger_in = False
                        except:
                            #print('sigledger NO ', mempool_signature_enc)
                            ledger_in = False

                        # if mempool_operation != "1" and mempool_operation != "0":
                        #    mempool_result.append = ("Mempool: Wrong keep value {}".format(mempool_operation))
                        #    acceptable = 0

                        if mempool_address != hashlib.sha224(base64.b64decode(mempool_public_key_hashed)).hexdigest():
                            mempool_result.append("Mempool: Attempt to spend from a wrong address")
                            # self.app_log.warning("Mempool: Attempt to spend from a wrong address")
                            acceptable = False

                        if not essentials.address_validate(mempool_address) or not essentials.address_validate(mempool_recipient):
                            mempool_result.append("Mempool: Not a valid address")
                            # self.app_log.warning("Mempool: Not a valid address")
                            acceptable = False

                        if quantize_eight(mempool_amount) < 0:
                            acceptable = False
                            mempool_result.append("Mempool: Negative balance spend attempt")
                            # self.app_log.warning("Mempool: Negative balance spend attempt")

                        if quantize_two(mempool_timestamp) > time.time():  # dont accept future txs
                            acceptable = False

                        # dont accept old txs, mempool needs to be harsher than ledger
                        if quantize_two(mempool_timestamp) < time.time() - 82800:
                            acceptable = 0
                        # remove from mempool if it's in both ledger and mempool already
                        if mempool_in and ledger_in:
                            try:
                                # Do not lock, we already have the lock for the whole merge.
                                self.execute(SQL_DELETE_TX, (mempool_signature_enc, ))
                                self.commit()
                                mempool_result.append("Mempool: Transaction deleted from our mempool")
                            except:  # experimental try and except
                                mempool_result.append("Mempool: Transaction was not present in the pool anymore")
                                pass  # continue to mempool finished message

                                # verify signatures and balances

                        essentials.validate_pem(mempool_public_key_hashed)

                        # verify signature
                        verifier = PKCS1_v1_5.new(mempool_public_key)

                        my_hash = SHA.new(str((mempool_timestamp, mempool_address, mempool_recipient, mempool_amount,
                                               mempool_operation, mempool_openfield)).encode("utf-8"))
                        if not verifier.verify(my_hash, mempool_signature_dec):
                            acceptable = False
                            mempool_result.append("Mempool: Wrong signature in mempool insert attempt: {}".
                                                  format(transaction))
                            # self.app_log.warning("Mempool: Wrong signature in mempool insert attempt")

                        # verify signature
                        if acceptable:

                            # verify balance
                            # mempool_result.append("Mempool: Verifying balance")
                            mempool_result.append("Mempool: Received address: {}".format(mempool_address))

                            # include mempool fees
                            result = self.fetchall("SELECT amount, openfield FROM transactions WHERE address = ?;",
                                                   (mempool_address, ))
                            debit_mempool = 0

                            if result:
                                for x in result:
                                    debit_tx = quantize_eight(x[0])
                                    fee = quantize_eight(essentials.fee_calculate(x[1]))
                                    debit_mempool = quantize_eight(debit_mempool + debit_tx + fee)
                            else:
                                debit_mempool = 0

                            # include the new block
                            credit_ledger = Decimal("0")
                            for entry in essentials.execute_param_c(c, "SELECT amount FROM transactions WHERE recipient = ?;",
                                                         (mempool_address, ), self.app_log):
                                try:
                                    credit_ledger = quantize_eight(credit_ledger) + quantize_eight(entry[0])
                                    credit_ledger = 0 if credit_ledger is None else credit_ledger
                                except:
                                    credit_ledger = 0

                            credit = credit_ledger

                            debit_ledger = Decimal("0")
                            for entry in essentials.execute_param_c(c, "SELECT amount FROM transactions WHERE address = ?;",
                                                         (mempool_address,), self.app_log):
                                try:
                                    debit_ledger = quantize_eight(debit_ledger) + quantize_eight(entry[0])
                                    debit_ledger = 0 if debit_ledger is None else debit_ledger
                                except:
                                    debit_ledger = 0

                            debit = debit_ledger + debit_mempool

                            fees = Decimal("0")
                            for entry in essentials.execute_param_c(c, "SELECT fee FROM transactions WHERE address = ?;",
                                                         (mempool_address, ), self.app_log):
                                try:
                                    fees = quantize_eight(fees) + quantize_eight(entry[0])
                                    fees = 0 if fees is None else fees
                                except:
                                    fees = 0

                            rewards = Decimal("0")
                            for entry in essentials.execute_param_c(c, "SELECT sum(reward) FROM transactions WHERE recipient = ?;",
                                                         (mempool_address, ), self.app_log):
                                try:
                                    rewards = quantize_eight(rewards) + quantize_eight(entry[0])
                                    rewards = 0 if rewards is None else rewards
                                except:
                                    rewards = 0

                            balance = quantize_eight(credit - debit - fees + rewards - quantize_eight(mempool_amount))
                            balance_pre = quantize_eight(credit_ledger - debit_ledger - fees + rewards)

                            fee = essentials.fee_calculate(mempool_openfield)

                            time_now = time.time()

                            if quantize_two(mempool_timestamp) > quantize_two(time_now) + drift_limit:
                                mempool_result.append(
                                    "Mempool: Future transaction not allowed, timestamp {} minutes in the future".
                                    format(quantize_two((quantize_two(mempool_timestamp) - quantize_two(time_now))
                                    / 60)))
                                # self.app_log.warning("Mempool: Future transaction not allowed, timestamp {} minutes in the future.")


                            elif quantize_two(time_now) - 86400 > quantize_two(mempool_timestamp):
                                mempool_result.append("Mempool: Transaction older than 24h not allowed.")
                                # self.app_log.warning("Mempool: Transaction older than 24h not allowed.")

                            elif quantize_eight(mempool_amount) > quantize_eight(balance_pre):
                                mempool_result.append("Mempool: Sending more than owned")
                                # self.app_log.warning("Mempool: Sending more than owned")
                            elif quantize_eight(balance) - quantize_eight(fee) < 0:
                                mempool_result.append("Mempool: Cannot afford to pay fees")
                                # self.app_log.warning("Mempool: Cannot afford to pay fees")

                            # verify signatures and balances
                            else:
                                self.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)",
                                             (str(mempool_timestamp), str(mempool_address), str(mempool_recipient),
                                              str(mempool_amount), str(mempool_signature_enc),
                                              str(mempool_public_key_hashed),
                                              str(mempool_operation), str(mempool_openfield)))
                                mempool_result.append("Mempool updated with a received transaction from {}".
                                                      format(peer_ip))
                                self.commit()  # Save (commit) the changes

                                mempool_size = mempool_size + sys.getsizeof(str(transaction)) / 1000000.0
                    else:
                        mempool_result.append("Local mempool is already full for this tx type, skipping merging")
                        # self.app_log.warning("Local mempool is already full for this tx type, skipping merging")
                        return mempool_result  # avoid spamming of the logs
                # TODO: Here maybe commit() on c to release the write lock?
            except Exception as e:
                self.app_log.warning("Mempool: Error processing: {} {}".format(data, e))
                if self.config.debug_conf == 1:
                    raise
        try:
            return e, mempool_result
        except:
            return mempool_result
Ejemplo n.º 44
0
def genSHA(text):
    h = SHA.new(bytes(text, 'utf-8'))
    return h.hexdigest()
Ejemplo n.º 45
0
    temp = (received, )
    receivedDecrypted = alicePrivateKey.decrypt(temp)
    #receivedDecrypted = alicePublicKey._decrypt(temp)
    # only works with alice's private key, not with her public key...
    print 'after 2nd stage decryption:', receivedDecrypted
    print '\r'

    aposPos = receivedDecrypted.find('`')
    paddedMessage = receivedDecrypted[0:aposPos]
    hashedMessage = receivedDecrypted[aposPos + 1:len(receivedDecrypted)]

    BS = 16
    unpad = lambda s: s[:-ord(s[len(s) - 1:])]

    # VERIFY THE MESSAGE BY REHASHING THE PADDED ONE
    toVerify = SHA.new(paddedMessage).digest()
    verified = (toVerify == hashedMessage)
    print 'verified message integrity:', verified
    print '\r'

    # PRINT THE MESSAGE WE GOT FROM THE OTHER SIDE
    actualMessage = unpad(paddedMessage)
    print 'Message sent from the other side:'
    print actualMessage

inputText = raw_input('Enter Y for statistics, N to skip: ')

if inputText.capitalize() == 'Y':
    print 'number of Keys in file: 5'
    print 'SHA1 used for Digest'
    print 'DES3 used for Symmetric Key encryption'
Ejemplo n.º 46
0
def check_activation_key(activation_key, email):
    """
    Returns:
        None --- if OK
        a string --- message telling what's wrong
    """
    if activation_key is None:
        return _("No activation key provided")

    # We use ElGamal signature to forge and check the activation keys.
    # As you can guess from the key length and the signature length,
    # this is not secure *at* *all*, and this is not the point.
    #
    # Activation process is just a reminder to pay for the Windows version.
    # If you're smart enough to break this crappy private key here, you are
    # smart enough to build your own version of Paperwork for Windows.

    public_key = \
        b"gAN9cQAoWAEAAAB5cQFKbZDQClgBAAAAZ3ECSq6eZXtYAQAAAHBxA4oFj0ovuQB1Lg"
    public_key = unserialize_elgamal_key(public_key)
    activation_key = activation_key.encode("utf-8")
    email = b"" if email is None else email.encode("utf-8")

    if len(activation_key) < 10:
        return _("Invalid activation key (too short)")

    sig_type = activation_key[:1]
    payload = activation_key[:6]
    signature = activation_key[6:]

    if sig_type != b"E" and sig_type != b"I":
        return _("Invalid activation key (bad prefix: {})").format(
            sig_type.decode("utf-8"))

    if sig_type == b"E":
        # email has been hashed and the beginning of the hash of the email
        # is the signed payload
        h = SHA.new(email).digest()
        h = base64.encodebytes(h)
        h = strip_base64(h)
        if h[:5] != payload[1:]:
            return _("Email does not match the activation key")

    # sig_type == b"I" means we signed the invoice number, but I don't want
    # to annoy users by asking it back here.
    # (we ask the email here just to be really clear the activation key is
    # tied to their email address, and so it is personal)

    h = SHA.new(payload).digest()

    signature = pad_base64(signature)
    try:
        signature = base64.decodebytes(signature)
    except binascii.Error:
        return _("Activation key is corrupted")
    try:
        signature = pickle.loads(signature)
    except EOFError:
        return _("Invalid activation key (too short)")

    if not public_key.verify(h, signature):
        return _("Invalid activation key")

    return None
Ejemplo n.º 47
0
 def sign_transaction(self):
     private_key = self.sender._private_key
     signer = PKCS1_v1_5.new(private_key)
     h = SHA.new(str(self.to_dict()).encode('utf8'))
     return binascii.hexlify(signer.sign(h)).decode('ascii')
Ejemplo n.º 48
0
def generate(bits, randfunc, progress_func=None):
    """generate(bits:int, randfunc:callable, progress_func:callable)

    Generate a qNEW key of length 'bits', using 'randfunc' to get
    random data and 'progress_func', if present, to display
    the progress of the key generation.
    """
    obj = qNEWobj()

    # Generate prime numbers p and q.  q is a 160-bit prime
    # number.  p is another prime number (the modulus) whose bit
    # size is chosen by the caller, and is generated so that p-1
    # is a multiple of q.
    #
    # Note that only a single seed is used to
    # generate p and q; if someone generates a key for you, you can
    # use the seed to duplicate the key generation.  This can
    # protect you from someone generating values of p,q that have
    # some special form that's easy to break.
    if progress_func:
        progress_func('p,q\n')
    while (1):
        obj.q = getPrime(160, randfunc)
        #           assert pow(2, 159L)<obj.q<pow(2, 160L)
        obj.seed = S = long_to_bytes(obj.q)
        C, N, V = 0, 2, {}
        # Compute b and n such that bits-1 = b + n*HASHBITS
        n = (bits - 1) / HASHBITS
        b = (bits - 1) % HASHBITS
        powb = 2L << b
        powL1 = pow(long(2), bits - 1)
        while C < 4096:
            # The V array will contain (bits-1) bits of random
            # data, that are assembled to produce a candidate
            # value for p.
            for k in range(0, n + 1):
                V[k] = bytes_to_long(SHA.new(S + str(N) + str(k)).digest())
            p = V[n] % powb
            for k in range(n - 1, -1, -1):
                p = (p << long(HASHBITS)) + V[k]
            p = p + powL1  # Ensure the high bit is set

            # Ensure that p-1 is a multiple of q
            p = p - (p % (2 * obj.q) - 1)

            # If p is still the right size, and it's prime, we're done!
            if powL1 <= p and isPrime(p):
                break

            # Otherwise, increment the counter and try again
            C, N = C + 1, N + n + 1
        if C < 4096:
            break  # Ended early, so exit the while loop
        if progress_func:
            progress_func('4096 values of p tried\n')

    obj.p = p
    power = (p - 1) / obj.q

    # Next parameter: g = h**((p-1)/q) mod p, such that h is any
    # number <p-1, and g>1.  g is kept; h can be discarded.
    if progress_func:
        progress_func('h,g\n')
    while (1):
        h = bytes_to_long(randfunc(bits)) % (p - 1)
        g = pow(h, power, p)
        if 1 < h < p - 1 and g > 1:
            break
    obj.g = g

    # x is the private key information, and is
    # just a random number between 0 and q.
    # y=g**x mod p, and is part of the public information.
    if progress_func:
        progress_func('x,y\n')
    while (1):
        x = bytes_to_long(randfunc(20))
        if 0 < x < obj.q:
            break
    obj.x, obj.y = x, pow(g, x, p)

    return obj
Ejemplo n.º 49
0
def pkcs1_sign(data):
    key = RSA.importKey(open(PRIVATE_KEY_FILE).read())
    h = SHA.new(data)
    p = PKCS1_v1_5.new(key)
    return p.sign(h)
Ejemplo n.º 50
0
def miner(q, privatekey_readable, public_key_hashed, address):
    from Crypto.PublicKey import RSA
    Random.atfork()
    key = RSA.importKey(privatekey_readable)
    app_log = log.log("miner_" + q + ".log", debug_level_conf)
    rndfile = Random.new()
    tries = 0

    while True:
        try:
            tries = tries + 1
            # calculate new hash

            if tries % int(diff_recalc_conf
                           ) == 0 or tries == 1:  #only do this ever so often
                block_timestamp = '%.2f' % time.time()

                conn = sqlite3.connect(
                    "static/ledger.db"
                )  #open to select the last tx to create a new hash from
                conn.text_factory = str
                c = conn.cursor()
                execute(c, (
                    "SELECT block_hash, timestamp FROM transactions WHERE reward != 0 ORDER BY block_height DESC LIMIT 1;"
                ), app_log)
                result = c.fetchall()
                db_block_hash = result[0][0]
                timestamp_last_block = float(result[0][1])

                # calculate difficulty
                execute_param(c, (
                    "SELECT block_height FROM transactions WHERE CAST(timestamp AS INTEGER) > ? AND reward != 0"
                ), (timestamp_last_block - 1800, ), app_log)  # 1800=30 min
                blocks_per_30 = len(c.fetchall())

                diff = blocks_per_30 * 2

                # drop diff per minute if over target
                time_drop = time.time()

                drop_factor = 120  # drop 0,5 diff per minute

                if time_drop > timestamp_last_block + 120:  # start dropping after 2 minutes
                    diff = diff - (
                        time_drop - timestamp_last_block
                    ) / drop_factor  # drop 0,5 diff per minute (1 per 2 minutes)

                if time_drop > timestamp_last_block + 300 or diff < 37:  # 5 m lim
                    diff = 37  # 5 m lim
                    # drop diff per minute if over target

                app_log.warning(
                    "Mining, {} cycles passed in thread {}, difficulty: {}, {} blocks per minute"
                    .format(tries, q, diff, blocks_per_30 / 30))

            diff = int(diff)

            nonce = hashlib.sha224(rndfile.read(16)).hexdigest()[:32]

            #block_hash = hashlib.sha224(str(block_send) + db_block_hash).hexdigest()
            mining_hash = bin_convert(
                hashlib.sha224(address + nonce + db_block_hash).hexdigest())
            mining_condition = bin_convert(db_block_hash)[0:diff]

            if mining_condition in mining_hash:
                app_log.warning(
                    "Thread {} found a good block hash in {} cycles".format(
                        q, tries))

                # serialize txs
                mempool = sqlite3.connect("mempool.db")
                mempool.text_factory = str
                m = mempool.cursor()
                execute(m, ("SELECT * FROM transactions ORDER BY timestamp;"),
                        app_log)
                result = m.fetchall()  # select all txs from mempool
                mempool.close()

                #include data
                block_send = []
                del block_send[:]  # empty
                removal_signature = []
                del removal_signature[:]  # empty

                for dbdata in result:
                    transaction = (str(dbdata[0]), str(dbdata[1][:56]),
                                   str(dbdata[2][:56]),
                                   '%.8f' % float(dbdata[3]), str(dbdata[4]),
                                   str(dbdata[5]), str(dbdata[6]),
                                   str(dbdata[7]))  # create tuple
                    # print transaction
                    block_send.append(
                        transaction)  # append tuple to list for each run
                    removal_signature.append(str(
                        dbdata[4]))  # for removal after successful mining

                # claim reward
                transaction_reward = tuple
                transaction_reward = (str(block_timestamp), str(address[:56]),
                                      str(address[:56]), '%.8f' % float(0),
                                      "0", str(nonce)
                                      )  # only this part is signed!
                # print transaction_reward

                h = SHA.new(str(transaction_reward))
                signer = PKCS1_v1_5.new(key)
                signature = signer.sign(h)
                signature_enc = base64.b64encode(signature)

                block_send.append((str(block_timestamp), str(address[:56]),
                                   str(address[:56]), '%.8f' % float(0),
                                   str(signature_enc), str(public_key_hashed),
                                   "0", str(nonce)))  # mining reward tx
                # claim reward
                # include data

                tries = 0

                #submit mined block to node

                if sync_conf == 1:
                    check_uptodate(300, app_log)

                submitted = 0
                while submitted == 0:
                    try:
                        s = socks.socksocket()
                        s.connect((mining_ip_conf,
                                   int(port)))  # connect to local node
                        app_log.warning("Connected")

                        app_log.warning(
                            "Miner: Proceeding to submit mined block")

                        send(s, (str(len("block"))).zfill(10))
                        send(s, "block")
                        send(s, (str(len(str(block_send)))).zfill(10))
                        send(s, str(block_send))

                        submitted = 1
                        app_log.warning("Miner: Block submitted")

                    except Exception, e:
                        print e
                        app_log.warning(
                            "Miner: Please start your node for the block to be submitted or adjust mining ip in settings."
                        )
                        time.sleep(1)

                #remove sent from mempool

                mempool = sqlite3.connect("mempool.db")
                mempool.text_factory = str
                m = mempool.cursor()
                for x in removal_signature:
                    execute_param(
                        m, ("DELETE FROM transactions WHERE signature =?;"),
                        (x, ), app_log)
                    app_log.warning(
                        "Removed a transaction with the following signature from mempool: {}"
                        .format(x))
                mempool.commit()
                mempool.close()

                #remove sent from mempool

            #submit mined block to node

            #break
        except Exception, e:
            print e
            time.sleep(0.1)
            raise
Ejemplo n.º 51
0
def upload_and_submit():
    '''
    It reads the file you upload, takes only text file, gives an error mesage
    if any other filetype os uploaded.
    The Hex Keys generated are even length strings and the program gives an
    error message if the string lengths are odd.
    Using the RSA encryption and Crypto module, the private key along with
    message is signed and the signature is returned.
    Can open any text file from your computer.
    '''
    filename = filedialog.askopenfilename()
    if filename[-4:] == '.txt':
        f = open(filename, "r")
        message = f.read()
        login_user_entry = login_user.get()
        f = open(
            dir_path + "/user_database/" + login_user_entry + "_Wallet.txt",
            "r")
        data = yaml.load(f.read())
        f.close()

        connection = sqlite3.connect("user_database/" + login_user_entry +
                                     "_Wallet")
        fetchQuery = "SELECT PUBLICKEY,PRIVATEKEY FROM " + login_user_entry + "_DETAILS"
        result = executeQuery(connection, fetchQuery).fetchall()[0]
        connection.close()

        sender_public_address = result[0]
        sender_private_address = result[1]
        reciever_public_address = reciever_public_address_entry.get()

        if len(reciever_public_address) % 2 == 0:
            private_key = RSA.importKey(
                binascii.unhexlify(sender_private_address))
            signer = PKCS1_v1_5.new(private_key)
            a = SHA.new(str(message).encode('utf8'))
            signature = binascii.hexlify(signer.sign(a)).decode('ascii')

            Label(screen4,
                  text="Your message successfully signed and "
                  "ready to be verified").pack()

            f = open('open_transactions.txt', "r")
            open_list = yaml.load(f.read())
            open_list.append({
                'sender_name': login_user_entry,
                'sender_public_address': sender_public_address,
                'reciever_public_address': reciever_public_address,
                'transaction_signature': signature,
                'message': message
            })

            f = open('open_transactions.txt', "w")
            f.write(str(open_list))
            f.close()

            connection = sqlite3.connect("open_transactions")
            createQuery = "CREATE TABLE IF NOT EXISTS OPEN_TRANSACTIONS ('SENDERNAME' TEXT NOT NULL UNIQUE, " \
                          "'SENDERPUBLICADDRESS' TEXT NOT NULL UNIQUE," \
                          "'RECEIVERPUBLICADDRESS' TEXT NOT NULL UNIQUE," \
                          "'SIGNATURE' TEXT NOT NULL," \
                          "'MESSAGE' TEXT," \
                          "'TIMESTAMP' TEXT NOT NULL);"
            executeQuery(connection, createQuery)
            timestamp = datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d %H:%M:%S')
            insertQuery = "INSERT INTO OPEN_TRANSACTIONS(SENDERNAME,SENDERPUBLICADDRESS,RECEIVERPUBLICADDRESS,SIGNATURE,MESSAGE,TIMESTAMP) " \
                          "VALUES('"+login_user_entry+"','"+sender_public_address+"','"+reciever_public_address+"','"+signature+"','"+message+"','"+timestamp+"');"
            executeQuery(connection, insertQuery)
            query = "INSERT INTO " + login_user_entry + "_MESSAGES VALUES('" + timestamp + "','" + message + "');"
            executeQuery(connection, query)
            print("inserted message")
            connection.close()

            connection = sqlite3.connect("user_database/" + login_user_entry +
                                         "_Wallet")

            Button(screen4,
                   text='**Quit**',
                   height="4",
                   width="20",
                   command=exit).pack()
        else:
            Label(screen4,
                  text="Please check your address, it might be wrong",
                  fg="red",
                  font=("Arial", 15)).pack()
    else:
        Label(screen4, text="Please upload a text file", bg="grey",
              fg="white").pack()
PORT = 31337

POWLEN = 5

conn = remote(HOST, PORT)
conn.recvline()
challenge = '00000'
prefix = conn.recvline().split()[1]
print "[*] Got prefix: " + prefix

# Given a random prefix from the server,
# Compute an hash that verify the following condition
# sha1(prefix+str) starts with '00000'

responsehash = ""
charset = "abcdefghijklmnopqrstuvwxyz0123456789"

for i in itertools.product(charset, repeat=5):
    responsehash = SHA.new(prefix + ''.join(i)).hexdigest()

    if responsehash[:POWLEN] == challenge:
        response = ''.join(i)
        break

print "[*] Sending challenge response: " + response
conn.sendline(response)

conn.interactive()

exit()
Ejemplo n.º 53
0
    def sign(self, data):
        """Sign a block of data"""

        return PKCS1_v1_5.new(self._key).sign(SHA.new(data))
Ejemplo n.º 54
0
    def signatures(self, message):

        signer = PKCS1_v1_5.new(self.private_key)
        digest = SHA.new()
        digest.update(message)
        return signer.sign(digest)
Ejemplo n.º 55
0
from Crypto.Random import random
from Crypto.PublicKey import DSA
from Crypto.Hash import SHA

message = raw_input("Enter your message:")
key = DSA.generate(1024)

print "\nParameter Tuple"
print key

h = SHA.new(message).digest()
print "\nMessage Digest"
print h

k = random.StrongRandom().randint(1, key.q - 1)
print "\nLong Term Key Pair"
print k

sig = key.sign(h, k)
print "\nSignature Generation"
print sig

if key.verify(h, sig):
    print "\n"
    print "Verified.."
    print "Signature is correct"
else:
    print "Incorrect signature"
Ejemplo n.º 56
0
 def sign(self, content):
     rsakey = RSA.importKey(self._key)
     signer = PKCS1_v1_5.new(rsakey)
     digest = SHA.new(content.encode('cp1251'))
     return signer.sign(digest)
Ejemplo n.º 57
0
            #print y

            # create transactions for missing payouts
            timestamp = '%.2f' % time.time()

            payout_amount = Decimal(bet_amount * 2) - percentage(5, bet_amount)
            payout_openfield = "payout for " + tx_signature[:8]
            payout_operation = 0
            fee = fee_calculate(payout_openfield)

            #float(0.01 + (float(payout_amount) * 0.001) + (float(len(payout_openfield)) / 100000) + (float(payout_keep) / 10))  # 0.1% + 0.01 dust

            transaction = (str(timestamp), str(address), str(payout_address), '%.8f' % float(payout_amount-fee), str(payout_operation), str(payout_openfield))  # this is signed
            print(transaction)

            h = SHA.new(str(transaction).encode("utf-8"))
            signer = PKCS1_v1_5.new(key)
            signature = signer.sign(h)
            signature_enc = base64.b64encode(signature)
            print("Encoded Signature: {}".format(signature_enc.decode()))

            verifier = PKCS1_v1_5.new(key)
            if verifier.verify(h, base64.b64decode(signature_enc)):
                print("Signature OK")

            mempool = sqlite3.connect('mempool.db')
            mempool.text_factory = str
            m = mempool.cursor()

            passed = 0
            while passed == 0:
Ejemplo n.º 58
0
 def sign(self, message):
     h = SHA.new(message)
     signer = PKCS1_v1_5.new(self.key)
     signature = signer.sign(h)
     return signature
def get_hexchecksum(data):
    return SHA.new(data).hexdigest()
def GetSHA1(D):
    h = SHA.new()
    h.update(D)
    return h.hexdigest()[:32]