Example #1
0
File: net.py Project: yurial/yubtc
def makeMessage(magic, command, payload):
    """
    4   magic       uint32_t    Magic value indicating message origin network, and used to seek to next message when stream state is unknown
    12  command     char[12]    ASCII string identifying the packet content, NULL padded (non-NULL padding results in packet rejected)
    4   length      uint32_t    Length of payload in number of bytes
    4   checksum    uint32_t    First 4 bytes of sha256(sha256(payload))
    ?   payload     uchar[]     The actual data
"""
    from struct import pack
    from hash import sha256
    checksum = sha256(sha256(payload))[0:4]
    return pack('<L12sL4s', magic, command, len(payload), checksum) + payload
Example #2
0
	def decrypt(self, ciphertext):
		hashValue = hash.sha256(rsa.decodeCiphertext(ciphertext, self.pubkey))
		if hashValue in self.prevMessages:
			return ""
		else:
			self.prevMessages.add(hashValue)
			return map(lambda x: rsa.decryptInt(x, self.privkey), ciphertext)
Example #3
0
def base58CheckEncode(payload):
    from base58 import b58encode
    from hash import sha256

    def countLeadingZeroes(s):
        count = 0
        for c in s:
            if c == '\0':
                count += 1
            else:
                break
        return count

    checksum = sha256(sha256(payload))[0:4]
    result = payload + checksum
    return b'1' * countLeadingZeroes(result) + b58encode(result)
Example #4
0
    def mine(self, difficulty, diff_bits=None):
        if (diff_bits != None):
            if (diff_bits < difficulty):  # diff bits must be over or equal to difficulty
                return 'diff_bits too low'
            elif (diff_bits > 0):
                return 'bad diff_bits'
            else:
                # set self diff bits to the specifyed diff_bits
                self.diff_bits = diff_bits
        else:
            # set the target diff bits to the minimum difficulty (difficulty var)
            self.diff_bits = difficulty
            txn_count = 0
            for _ in self.transactions:
                txn_count += 1
            if (txn_count > 1):
                if (self.transactions[0].type != 1):
                    amount = BLOCK_REWARD
                    coinbase_txn = coinbase(MINING_ADDR, amount)
                    tmp = self
                    for i in range(len(self.transactions)):
                        if (i == 0):
                            tmp.transactions[0] = coinbase_txn
                        else:
                            tmp.transactions[i] = self.transactions[i-1]
                    tmp.transactions.append(self.transactions[-1])
                    self.transactions = tmp.transactions
            else:
                self.transactions.append(coinbase(MINING_ADDR, BLOCK_REWARD))
            work = self.as_bytes()
            target = diff2target(self.diff_bits)
            start = millis()
            begin = start
            hashes = 0
            for nonce in range(max_nonce):
                hashes += 1
                if (millis() - start >= 60000):
                    log.info(
                        "Mining at {} h/s".format(math.ceil(hashes/((millis()-start)/1000))))
                    start = millis()
                    hashes = 0
                # increment the nonce
                self.nonce = nonce
                work = self.as_bytes()

                # hash the block
                hash_result = sha256(work)
#				print("hash={} nonce={} value={} target={}".format(hash_result, nonce, int(hash_result, 16), target))
        # check if this is a valid result, below the target
                if (check_diff(self.diff_bits, hash_result) == True):
                    #  set the hash of self to the hash we found
                    self.hash = str(hash_result)
                    if nonce > 0 and millis()-begin > 0:
                        log.info(
                            "Avg. hashrate={} h/s".format(math.ceil(nonce/((millis()-begin)/1000))))
                    return None
Example #5
0
def base58CheckDecode(payload):
    from base58 import b58decode
    from hash import sha256

    def countLeadingOnes(s):
        count = 0
        for c in s:
            if c == '1':
                count += 1
            else:
                break
        return count

    nzeros = countLeadingOnes(payload)
    payload = payload[nzeros:]
    payload = b58decode(payload)
    checksum = payload[-4:]
    payload = b'\0' * nzeros + payload[:-4]
    calculated_checksum = sha256(sha256(payload))[:4]
    if checksum != calculated_checksum:
        raise Exception('ivalid checksum')
    return payload
Example #6
0
	def text_hash(self, i):

		s = self.coinbase["amount"] + self.coinbase["recipient"] if self.coinbase else ""

		for t in self.tx:
			s += t['amount'] + t['from'] + t['recipient']

		if self.previous:
			s += self.previous.hash
		else:
			s += "0" * 64

		return sha256(str(self.block) + str(i) +  s)
    def hash(self):

        s = self.coinbase["amount"] + self.coinbase[
            "recipient"] if self.coinbase else ""

        for t in self.tx:
            s += t.to_string()

        if self.previous:
            s += self.previous.hash
        else:
            s += "0" * 64

        return sha256(str(self.block) + str(self.nonce) + s)
Example #8
0
def create_index(basepath, includes=[], excludes=[], archive=None):
    basepath = os.path.normpath(basepath)
    fileindex = FileIndex(basepath)
    filefilter = FileFilter(includes=includes, excludes=excludes)
    # Read the files in the directory.
    queue = [basepath]
    while len(queue) > 0:
        path = queue.pop()
        if filefilter.is_filtered(path): continue
        try:
            if os.path.isdir(path):
                for child in os.listdir(path): queue.append(os.path.join(path, child))
            else:
                fd = create_descriptor(path, basepath)
                old_fd = archive[fd.relpath] if archive else None
                if not old_fd:
                    sys.stdout.write('Calculating SHA256 for {}... '.format(path))
                    starttime = time.time()
                    fd.sha256 = sha256 = hash.sha256(path)
                    sys.stdout.write('({})\n'.format(datetime.timedelta(seconds=time.time()-starttime)))
                    sys.stdout.flush()
                    if archive: archive.insert(fd)
                elif old_fd.size != fd.size or old_fd.mtime != fd.mtime:
                    sys.stdout.write('Calculating SHA256 for {}... '.format(path))
                    starttime = time.time()
                    fd.sha256 = sha256 = hash.sha256(path)
                    sys.stdout.write('({})\n'.format(datetime.timedelta(seconds=time.time()-starttime)))
                    sys.stdout.flush()
                    if archive: archive.update(fd)
                else:
                    fd.sha256 = old_fd.sha256
                fileindex.files.append(fd)
        except (EnvironmentError, SystemError) as e:
            sys.stderr.write('Could not process {}: {}\n'.format(path, e))
            sys.stderr.flush()
    return fileindex
Example #9
0
def do_work(filename, list_data, pkgname_parent="", flag_delete=False):
    logger_do_work = logging.getLogger("do_work")
    l = []

    for sub_filename in walk_dir(filename):

        if os.path.islink(sub_filename):
            os.unlink(sub_filename)
            logger_do_work.debug('unlink %s' % sub_filename)
            continue
        #FIXME: 判断解压临时存储位置是否能放得下
        #TODO: 考虑分片读取数据降低内存压力
        file_bindata = open(sub_filename, 'rb').read()
        d_md5 = hash.md5(file_bindata)
        d_sha1 = hash.sha1(file_bindata)
        d_sha256 = hash.sha256(file_bindata)
        filesize = os.stat(sub_filename).st_size

        cmd = 'file "%s" | cut -c %s-' % (sub_filename, len(sub_filename) + 3)
        logger_do_work.debug(cmd)
        filetype = os.popen(cmd).read().strip()
        if os.path.isfile(filename):
            t_filename = sub_filename[sub_filename.index(pkgname_parent) +
                                      len(pkgname_parent):]
        else:
            t_filename = sub_filename.partition(filename)[2]

        if is_pack(sub_filename):
            dir_temp = o_unpack.unpack(sub_filename)
            pkg_info = (t_filename, pkgname_parent, d_md5, d_sha1, d_sha256,
                        filesize, filetype)
            logger_do_work.debug("recursive do_work start: %s", t_filename)
            ll = do_work(dir_temp, list_data, t_filename, flag_delete=True)
            logger_do_work.debug("recursive do_work end: %s", t_filename)
            d = {}
            d[pkg_info] = ll
            l.append(d)
        else:
            l.append((t_filename, pkgname_parent, d_md5, d_sha1, d_sha256,
                      filesize, filetype))
            if flag_delete:
                removefiles(sub_filename)
    else:
        if flag_delete:
            removefiles(filename)
    return l
Example #10
0
def do_work(filename, list_data, pkgname_parent="", flag_delete=False):
    logger_do_work = logging.getLogger("do_work")
    l = []
        
    for sub_filename in walk_dir(filename):
        
        if os.path.islink(sub_filename):
            os.unlink(sub_filename)
            logger_do_work.debug('unlink %s' % sub_filename)
            continue
        #FIXME: 判断解压临时存储位置是否能放得下
        #TODO: 考虑分片读取数据降低内存压力
        file_bindata = open(sub_filename, 'rb').read()
        d_md5 = hash.md5(file_bindata)
        d_sha1 = hash.sha1(file_bindata)
        d_sha256 = hash.sha256(file_bindata)
        filesize = os.stat(sub_filename).st_size
        
        cmd= 'file "%s" | cut -c %s-' % (sub_filename, len(sub_filename)+3)
        logger_do_work.debug(cmd)
        filetype =os.popen(cmd).read().strip() 
        if os.path.isfile(filename):
            t_filename = sub_filename[sub_filename.index(pkgname_parent)+len(pkgname_parent):]
        else:
            t_filename = sub_filename.partition(filename)[2]
        
        if is_pack(sub_filename):
            dir_temp = o_unpack.unpack(sub_filename)
            pkg_info = (t_filename, pkgname_parent, d_md5, d_sha1, d_sha256, filesize, filetype)
            logger_do_work.debug("recursive do_work start: %s", t_filename)
            ll = do_work(dir_temp,list_data, t_filename, flag_delete=True)
            logger_do_work.debug("recursive do_work end: %s", t_filename)
            d = {}
            d[pkg_info] = ll
            l.append(d)
        else:
            l.append((t_filename, pkgname_parent, d_md5, d_sha1, d_sha256, filesize, filetype))
            if flag_delete:
                removefiles(sub_filename)
    else:
        if flag_delete:
            removefiles(filename)
    return l
Example #11
0
	def login(self, ip, port):
		sendSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sendSocket.connect((ip, port))
		
		sendSocket.send(str(self.username)+","+str(self.publicValue))

		salt, serverPublicValue = self.recieveServerValues(sendSocket)
		if salt is None or serverPublicValue is None:
			sendSocket.close()
			return False

		sharedSecret = convert.intToByteString(hash.sha256(convert.intToByteString(self.sharedSecretValue)))
		validator = srp.generateClientValidator(sharedSecret, salt)
		sendSocket.send(str(validator))

		if self.recieveOK(sendSocket):
			sendSocket.close()
			return True
		sendSocket.close()
		return False
Example #12
0
	def runServer(self):
		#Socket setup
		recieveSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		recieveSocket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)
		recieveSocket.bind(("", self.port))

		recieveSocket.listen(5)

		#Establish connection
		clientSock, _ = recieveSocket.accept()

		userName, clientPublicValue = self.recieveClientValues(clientSock)
		#Error case
		if userName is None or clientPublicValue is None:
			return

		passwordVerifier, salt = self.users[userName]
		sessionPrivateKey = srp.generatePrivateKey()

		u = random.randint(0, 2**128)

		#Send public values
		clientSock.sendall(str(convert.byteStringToInt(salt))+","+str(dh.generatePublicValue(sessionPrivateKey, srp.STANDARD_G, srp.STANDARD_N))+","+str(u))

		#Derive shared secret
		sharedSecret = pow(clientPublicValue*pow(passwordVerifier, u, srp.STANDARD_N), sessionPrivateKey, srp.STANDARD_N)
		sharedSecret = convert.intToByteString(hash.sha256(convert.intToByteString(sharedSecret)))

		clientValidator = self.recieveClientValidator(clientSock)
		#Error check
		if clientValidator is not None:
			if clientValidator == srp.generateClientValidator(sharedSecret, salt):
				clientSock.sendall("OK")
				return

		try:
			clientSock.sendall("NOTOK")
		except Exception:
			pass
Example #13
0
def radio_button_selection(selection, filepath, label):
    """ Get selection from the radio button

    Parameters
    ----------
    selection: int
        Algorithm choice between MD5 and SHA-256
    filepath: str
        A string representing the absolute path of the file
    label: Label()
        Text label representing the final hash (result)
    """
    algorithm_choice = selection.get()

    if algorithm_choice == 1:
        result_hash = hash.md5(filepath)
    elif algorithm_choice == 2:
        result_hash = hash.sha256(filepath)
    else:
        result_hash = "Error while computing hash"

    label.config(text=result_hash)
Example #14
0
	def login(self, ip, port):
		sendSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sendSocket.connect((ip, port))

		privateKey = srp.generatePrivateKey()
		
		sendSocket.send(str(self.username)+","+str(srp.generateClientPublicValue(privateKey)))

		salt, serverPublicValue, u = self.recieveServerValues(sendSocket)
		if salt is None or serverPublicValue is None or u is None:
			sendSocket.close()
			return False

		x = srp.getHashInt(self.password+salt)
		sharedSecret = pow(serverPublicValue, (privateKey+u*x), srp.STANDARD_N)
		sharedSecret = convert.intToByteString(hash.sha256(convert.intToByteString(sharedSecret)))
		validator = srp.generateClientValidator(sharedSecret, salt)
		sendSocket.send(str(validator))

		if self.recieveOK(sendSocket):
			sendSocket.close()
			return True
		sendSocket.close()
		return False
Example #15
0
def getHashInt(value):
	return hash.sha256(value)
Example #16
0
def sign_data(privkey, data):
    from hash import sha256
    datahash = sha256(sha256(data))
    return sign_hash(privkey=privkey, datahash=datahash)
Example #17
0
def seed2bin(seed, nonce=0):
    from hash import sha256, keccak256, blake256
    from struct import pack
    data = pack(">L", nonce) + str2bytes(seed)
    return sha256(keccak256(blake256(data)))
Example #18
0
 def text_hash(self, i):
     return sha256(str(self.block) + str(i) + self.data)
Example #19
0
 def hash(self):
     return sha256(str(self.block) + str(self.nonce) + self.data)
Example #20
0
	def generateClientValidator(self, password, salt, clientPublicValue, serverPrivateKey, u, debug = False):
		passwordVerifier = srp.generatePasswordVerifier(password, salt)
		sharedSecret = pow(clientPublicValue * pow(passwordVerifier, u, srp.STANDARD_N), serverPrivateKey, srp.STANDARD_N)
		sharedSecret = convert.intToByteString(hash.sha256(convert.intToByteString(sharedSecret)))
		return srp.generateClientValidator(sharedSecret, salt)
Example #21
0
def flawedCheckSignature(message, signature, publicKey):
    decryptedSignature = decryptString(signature, publicKey, True)
    messageDigest = convert.intToByteString(hash.sha256(message))
    return re.match(chr(0)+chr(1)+chr(255)+"+"+chr(0)+re.escape(messageDigest), decryptedSignature) is not None
Example #22
0
def serverDeriveSharedSecret(clientPublicValue, serverPrivateKey, passwordVerifier, g= STANDARD_G, k = STANDARD_K, N = STANDARD_N):
	publicValueHash = derivePublicValueHash(clientPublicValue, generateServerPublicValue(serverPrivateKey, passwordVerifier, g, k, N))
	S = pow(clientPublicValue*pow(passwordVerifier, publicValueHash, N), serverPrivateKey, N)
	return convert.intToByteString(hash.sha256(convert.intToByteString(S)))
Example #23
0
	def hash(self):
		s = self.previous.hash if self.previous else "0" * 64
		return sha256(str(self.block) + str(self.nonce) +  str(self.data) + s)
Example #24
0
	def text_hash(self, i):
		s = self.previous.hash if self.previous else "0" * 64
		return sha256(str(self.block) + str(i) + str(self.data) +  s)
Example #25
0
def derivePublicValueHash(publicValueA, publicValueB):
	return hash.sha256(convert.intToByteString(publicValueA) + convert.intToByteString(publicValueB))
Example #26
0
 def hash_in(self):
     work = self.as_bytes()
     self.hash = sha256(work)
     return self.hash
Example #27
0
def clientDeriveSharedSecret(password, salt, clientPrivateKey, serverPublicValue, g = STANDARD_G, k = STANDARD_K, N = STANDARD_N):
	x = getHashInt(password+salt)
	publicValueHash = derivePublicValueHash(generateClientPublicValue(clientPrivateKey, g, N), serverPublicValue)
	S = pow((serverPublicValue - k*pow(g, x, N)), (clientPrivateKey+publicValueHash*x), N)
	return convert.intToByteString(hash.sha256(convert.intToByteString(S)))