Example #1
0
def main():
    hpp_path = Path(utils.entry_script_dir(), '..', 'toml.hpp').resolve()
    hash1 = utils.sha1(utils.read_all_text_from_file(hpp_path, logger=True))
    print(rf'Hash 1: {hash1}')
    utils.run_python_script(r'generate_single_header.py')
    hash2 = utils.sha1(utils.read_all_text_from_file(hpp_path, logger=True))
    print(rf'Hash 2: {hash2}')
    if (hash1 != hash2):
        print(
            "toml.hpp wasn't up-to-date!\nRun generate_single_header.py before your commit to prevent this error.",
            file=sys.stderr)
        return 1
    print("toml.hpp was up-to-date")
    return 0
Example #2
0
def main():


    # Parsing the arguments through argparse module
    parser = argparse.ArgumentParser(description='Launch the miniSSL Server')
    parser.add_argument('address', help='Address of the server')
    parser.add_argument('port', help='Number of the port the server is listening on', type=int)
    parser.add_argument('clientcert', help='Name of the file containing the client certificate')
    parser.add_argument('clientkey', help='Name of the file containing the client key')
    args = parser.parse_args()

    try:

        # The SSLObject initiates the handshake procedure
        connection = SSLConnection(args.address, args.port, args.clientcert, args.clientkey)
        connection.client_init()

        # Once handshake has been done, we use miniGet (passing the SSLConnection object)
        miniget = miniGet(connection)
        payload = miniget.get()



        print 'Received:\t' + payload
        print 'Sha1Sum:\t' + utils.sha1(payload)

        f = open('received_file.txt', 'w')
        f.write(payload)
        f.close()

        connection.close()

    except Exception, e:
        print e
        return 
Example #3
0
def check_signature():
    if app.config['DEBUG']:
        return None

    # 跳过检查权限的URL
    skip_check_auth_urls = ['/favicon.ico']
    for url in skip_check_auth_urls:
        if request.path.startswith(url):
            return None

    secret = app.config['SECRET']
    signature = request.args.get('signature')
    timestamp = request.args.get('timestamp')
    nonce = request.args.get('nonce')

    no_auth_response = jsonify({
        'code': app.config['ERROR_CODE_NO_AUTH'],
        'message': '无权访问该接口'
    })

    if nonce is None or nonce == '' or timestamp is None or timestamp == '' or signature is None or signature == '':
        return no_auth_response

    now_timestamp = int(time.time())
    if not timestamp.isdigit() or abs(int(timestamp) - now_timestamp) > 30:
        return no_auth_response

    args = [f'secret={secret}']
    for key, value in request.args.items():
        if key != 'signature':
            args.append(f'{key}={value}')
    args.sort()

    if sha1('&'.join(args)) != signature:
        return no_auth_response
Example #4
0
 def finalize(self):
     """
     Calculate hash for this transaction when it's done.
     """
     vin = [i.get_state() for i in self.inputs]
     vout = [o.get_state() for o in self.outputs]
     self.hash = sha1("".join(vin).join(vout))
 def start(self):
     while True:
         print('------------------------------------')
         command = str(
             input('Choose your operation:\n'
                   '1 for upload\n'
                   '2 for download\n'
                   '3 for put\n'
                   '4 for get\n'
                   '5 for debug\n'
                   'or any other input to exit\n'))
         print('------------------------------------\n')
         if command == '1':
             filename = str(input('Filename:\n'))
             # upload file
             self.upload(filename)
         elif command == '2':
             filename = str(input('Filename:\n'))
             path = str(input('Path to save it:\n'))
             # download file
             self.download(filename, path)
         elif command == '3':
             # put
             s = str(input('Input key,value separated by \',\'\n'))
             key, value = s.split(',')
             hashed_value_of_file = utils.sha1(key)
             result = self.put(hashed_value_of_file, value)
             if result == 0:
                 print('Succeeded')
             else:
                 print('Failed')
         elif command == '4':
             # get
             key = str(input('Input key:\n'))
             hashed_value_of_file = utils.sha1(key)
             result, addr_list = self.get(hashed_value_of_file)
             if result == 0:
                 print('Succeeded')
                 print(str(addr_list))
             else:
                 print('Failed')
         elif command == '5':
             self.show_debug_info()
         else:
             return
Example #6
0
async def edit_comment(connection, user_token, comment_unique_key, text):
    comment = await _try_get_comment(connection, user_token,
                                     comment_unique_key)
    result = await db_api.add_or_update_comment_text(connection,
                                                     comment_id=comment["id"],
                                                     text=text,
                                                     text_hash=sha1(text))

    return result
Example #7
0
    def finalize(self):
        """
        Set timestamp and calculate the hash for this block. This should
        be called when block is ready to be checked against mining algorithm.
        """
        self.timestamp = datetime.now()

        txdata = map(lambda x: x.hash, self.transactions)
        self.hash = sha1("" + str(self.prev) + str(self.index) +
                         str(self.nonce) + "".join(txdata))
    def upload(self, filename):
        try:
            with open(filename, 'rb') as f:
                lines = f.readlines()
        except Exception as e:
            print('Cannot open file')
            return
        file = b''
        for line in lines:
            file += line

        hashed_value_of_file = utils.sha1(file)

        # step 1: Register (filename, hashed_value_of_file) at tracker
        with grpc.insecure_channel(self.tracker_addr) as channel:
            stub = p2p_service_pb2_grpc.P2PStub(channel)
            request = p2p_service_pb2.RegisterFileRequest(
                filename=filename, hashed_value_of_file=hashed_value_of_file)
            try:
                response = stub.rpc_register_file(request, timeout=20)
            except Exception:
                print("RPC failed")
                return
        if response.result == -1:
            print('Failed while registering to tracker')
            return

        # step2: Tracker gives fileholder the addr of a node in Chord (as the entrance of Chord)
        #  this is piggybacked in the return of RPC register_file
        self.entrance_addr = response.entrance_addr

        # step3: Fileholder put(hashed_value_of_file, fileholder_addr) to Chord
        result = self.put(hashed_value_of_file=hashed_value_of_file,
                          fileholder_addr=self.addr)
        # response: {int32 result: -1 for failed, 0 for succeeded;}

        if result == -1:
            print('Failed while putting local address to Chord')
            return

        # store this file into local memory storage
        global local_files
        local_files[hashed_value_of_file] = file

        if not self.file_server:
            # start file server
            server = threading.Thread(target=start_file_server,
                                      args=(self.addr, ))
            server.start()

        print('Upload succeeded!')
Example #9
0
    def check_signautre(self, sign):
        """ 验证消息的真实性 """
        if not sign['signature'] or not sign['timestamp'] or not sign['nonce']:
            return False

        params = [constants.TOKEN, str(sign['timestamp']), sign['nonce']]
        params.sort()
        params_str = ''.join(params)
        server_sign = utils.sha1(params_str)

        valid = False
        if server_sign == sign['signature']:
            valid = True
        return valid
Example #10
0
    def accept(self):
        request =self.sslconnection.clientsock.recv(1024)
        request_splitted = request.split('|')
        if request_splitted[0] == 'GET':
            try:
                with open (self.file, 'r') as requested_file:
                    payload=requested_file.read()

                message = self.miniget_encryption(payload)
                self.sslconnection.clientsock.send(message)

                print 'Sent:\t' + payload
                print 'Sha1Sum\t:' + utils.sha1(payload)

            except IOError:
                self.clientsock.send('Invalid file request')
Example #11
0
def _create_comment_identifiers(text):
    return str(uuid4()), sha1(text)
Example #12
0
def check_and_upload(url, filename, sha1):
    if not os.path.exists(filename) or utils.sha1(filename) != sha1:
        if not utils.copy_file_from_url(url, filename, sha1):
            return False

    return True
Example #13
0
def write_sha1(out_dir, in_file):
    sha1 = utils.sha1(in_file)
    utils.write_sha1(sha1, out_dir + "sha1.sum")
Example #14
0
def check_and_upload(url, filename, sha1):
    if not os.path.exists(filename) or utils.sha1(filename) != sha1:
        if not utils.copy_file_from_url(url, filename, sha1):
            return False

    return True
Example #15
0
def write_sha1(out_dir, in_file):
    sha1 = utils.sha1(in_file)
    utils.write_sha1(sha1, out_dir + "sha1.sum")