def test_update_after_digest(self):
        msg=b("rrrrttt")

        # Normally, update() cannot be done after digest()
        h = SHA3.new(data=msg[:4])
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = SHA3.new(data=msg).digest()

        # With the proper flag, it is allowed
        h = SHA3.new(data=msg[:4], update_after_digest=True)
        self.assertEquals(h.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h.update(msg[4:])
        self.assertEquals(h.digest(), dig2)
예제 #2
0
def hasher(obj):
    """
    :return: SHA3_512 hasher object
    """
    assert valid_type(obj, 'Transaction', 'Block', 'bytes')
    return SHA3_512.new().update(obj if type(obj) ==
                                 bytes else to_json(obj).encode())
예제 #3
0
def create_collection(database,
                      collection,
                      login=None,
                      password=None,
                      system=False):
    old_directory = os.getcwd()
    enter_in_system_directory()
    if os.path.isdir(database):
        os.chdir(database)
        if os.path.isfile("system.bs"):
            with open("system.bs", 'rb') as file:
                try:
                    data = bson.loads(file.read())
                except (IndexError, bson.struct.error):
                    os.chdir(old_directory)
                    return Answer(
                        "Error The file with the signature of database {} is corrupted"
                        .format(database),
                        error=True)
                if "name" in data:
                    if system or ("login" in data and "password" in data and data["login"] == login \
                                          and data["password"] == SHA3_512.new(password.encode('utf-8')).hexdigest()):
                        if data["name"] != database:
                            os.chdir(old_directory)
                            return Answer(
                                "Error The file with the signature of database {} is corrupted"
                                .format(database),
                                error=True)
                        if not data["collections"]:
                            data["collections"] = {}
                        if collection in data["collections"]:
                            os.chdir(old_directory)
                            return Answer(
                                'Collection {} of database {} already exist'.
                                format(collection, database),
                                error=True)
                        else:
                            data["collections"][collection] = {
                                "files": {
                                    '0':
                                    "{}.bs".format(
                                        get_hash({
                                            "collection": collection,
                                            "files": '0'
                                        }))
                                }
                            }
                            with open(
                                    data["collections"][collection]["files"]
                                ['0'], 'wb'):
                                pass
                    else:
                        os.chdir(old_directory)
                        return Answer(
                            'Login or password for database {} are incorrect'.
                            format(database),
                            error=True)
            try:
                data_to_write = bson.dumps(data)
            except (IndexError, bson.struct.error):
                os.chdir(old_directory)
                return Answer(
                    "The file with the signature of database {} is corrupted".
                    format(database),
                    error=True)
            with open('system.bs', 'wb') as file_to_write:
                file_to_write.write(data_to_write)
            os.chdir(old_directory)
            return Answer("Operation finished")
    os.chdir(old_directory)
    return Answer("Database {} does not exit or corrupted".format(database),
                  error=True)
예제 #4
0
import cryptocode
from Cryptodome.Hash import SHA3_512

aa = input("Are you going to open or create a file? (open/create):   ")

if aa == ('open'):
    a = input("Whats the title?   ")
    b = input("What's the password?   ")
    obj = SHA3_512.new()
    obj.update(bytes((a), encoding='utf-8'))
    e = (obj.hexdigest())
    f = open((e) + ".txt", "r")
    encoded = f.read()
    decoded = cryptocode.decrypt(encoded, (b))
    print(decoded)

if aa == ('create'):
    a = input("Whats the title?   ")
    b = input("What do you want to write?   \n\n\n")
    c = input("What do you want your password to be?   ")
    obj = SHA3_512.new()
    obj.update(bytes((a), encoding='utf-8'))
    e = (obj.hexdigest())
    encoded = cryptocode.encrypt((b), (c))
    f = open((e) + ".txt", "w")
    f.write(encoded)
    f.close()
    print(encoded)
예제 #5
0
 def __init__(self):
     """Initiation and command loop instructions of AquaSilva RMCA."""
     print("[INFO]: Starting host AquaSilva RMC Application...")
     print("[INFO]: Declaring variables...")
     self.socket = None
     self.host = ""
     self.port = 64220
     self.connect_retries = 0
     self.operation_status = 0  # 0 = manual, 1 = auto
     self.state_valve_outlet = False
     self.state_valve_inlet = False
     self.state_light = False
     self.state_light_level = 0
     print("[INFO]: Loading configurations...")
     config_parse_load = configparser.ConfigParser()
     try:
         config_parse_load.read("main.cfg")
         self.host = config_parse_load["NET"]["ip"]
         self.port = config_parse_load["NET"]["port"]
         self.port = int(self.port)
         raw_key = config_parse_load["ENCRYPT"]["key"]
         raw_key_hash = MD5.new(
             raw_key.encode(encoding="ascii", errors="replace"))
         self.key = raw_key_hash.hexdigest()
         self.key = self.key.encode(encoding="ascii", errors="replace")
         self.hmac_key = config_parse_load["ENCRYPT"]["hmac_key"]
         self.auth = config_parse_load["ENCRYPT"]["auth"]
         self.auth = self.auth.encode(encoding="ascii", errors="replace")
     except configparser.Error as ce:
         print(
             "[FAIL]: Failed to load configurations! See below for details."
         )
         print(ce)
     except FileNotFoundError:
         print(
             "[FAIL]: Failed to load configurations! Configuration file is missing."
         )
     pass
     host.state_reset(self)
     print("[INFO]: Starting background processes...")
     self.process_sensor_collect = host.create_process(
         host.sensor_collect, self)
     print("[INFO]: Creating open server socket...")
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.setblocking(False)
     self.socket.settimeout(5)
     self.socket.bind((socket.gethostname(), self.port))
     self.socket.setblocking(True)
     self.socket.listen(1)
     connection, client_address = self.socket.accept()
     self.socket.setblocking(False)
     with connection:
         print("[INFO]: Received connection from ", client_address, ".")
         connection.sendall(
             host.send(self, b"rmca-1.0:connection_acknowledge"))
         data = SHA3_512.new(host.receive(
             self,
             connection.recv(4096))).hexdigest().encode(encoding="ascii",
                                                        errors="replace")
         if data == self.auth:
             print("[INFO]: Client authenticated!")
             connection.sendall(
                 host.send(self, b"rmca-1.0:connection_acknowledge"))
         else:
             print(
                 "[FAIL]: Client authentication invalid! Given code does not match authentication code."
             )
             connection.sendall(
                 host.send(self, b"rmca-1.0:authentication_invalid"))
             self.socket.close()
             host.restart()
         pass
         while True:
             command = host.receive(self, connection.recv(4096))
             if command == b"rmca-1.0:command_shutdown":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 host.shutdown()
             elif command == b"rmca-1.0:command_reboot":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 host.reboot()
             elif command == b"rmca-1.0:command_update":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 host.os_update()
             elif command == b"rmca-1.0:disconnected":
                 self.socket.close()
                 print("[INFO]: Client has disconnected.")
                 host.restart()
             elif command == b"rmca-1.0:sensor_collect":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 sensor_data_now = self.sensor_data[self.sensor_data_index]
                 for x in sensor_data_now:
                     sensor_data_now[x].encode(encoding="ascii",
                                               errors="replace")
                 pass
                 connection.sendall(
                     host.send(
                         self, sensor_data_now[0] + b" " +
                         sensor_data_now[1] + b" " + sensor_data_now[2] +
                         b" " + sensor_data_now[3] + b" " +
                         sensor_data_now[4] + b" " + sensor_data_now[5]))
             elif command == b"rmca-1.0:sensor_data_clear":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 host.stop_process(self.process_sensor_collect, False)
                 connection.sendall(
                     host.send(self, pickle.dumps(self.sensor_data)))
                 connection.sendall(
                     host.send(
                         self,
                         str(self.sensor_data_index).encode(
                             encoding="ascii", errors="replace")))
                 self.sensor_data = []
                 self.sensor_data_index = 0
                 self.process_sensor_collect = host.create_process(
                     host.sensor_collect, self)
             elif command == b"rmca-1.0:command_ch_check":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 connection.sendall(host.send(self, ch_check()))
             elif command == b"rmca-1.0:state_get":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 states = [
                     str(self.operation_status),
                     str(self.state_valve_outlet),
                     str(self.state_valve_inlet),
                     str(self.state_light),
                     str(self.state_light_level)
                 ]
                 states_index = 4
                 while states_index != (0 - 1):
                     connection.sendall(
                         host.send(self, states[states_index]))
                     states_index -= 1
                 pass
             elif command == b"rmca-1.0:state_reset":
                 connection.sendall(
                     host.send(self, b"rmca-1.0:connection_acknowledge"))
                 host.state_reset(self)
             elif command == b"rmca-1.0:command_auto_start":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     host.state_reset(self)
                     self.operation_status = 1
                     self.task_auto = host.create_process(host.auto, self)
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:command_auto_stop":
                 if self.operation_status == 1:
                     connection.sendall(
                         host.send(self, b"rca-1.0:connection_acknowledge"))
                     host.state_reset(self)
                     host.stop_process(self.task_auto, False)
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:command_valve_inlet_toggle":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     self.state_valve_inlet = not self.state_valve_inlet
                     host.serial("/dev/ttyACM0", "send", ">")
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:command_valve_outlet_toggle":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     self.state_valve_outlet = not self.state_valve_outlet
                     host.serial("/dev/ttyACM0", "send", "<")
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:light_toggle":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     self.state_light = not self.state_light
                     host.serial("/dev/ttyACM0", "send", "L")
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:light_reset":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     host.serial("/dev/ttyACM0", "send", ":")
                     self.state_light_level = 100
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             elif command == b"rmca-1.0:light_adjust":
                 if self.operation_status == 0:
                     connection.sendall(
                         host.send(self,
                                   b"rmca-1.0:connection_acknowledge"))
                     self.state_light_level = int(
                         host.receive(self, connection.recv(4096)))
                     host.serial("/dev/ttyACM0", "send", ":")
                     # TODO add calculation for turn amount
                 else:
                     connection.sendall(
                         host.send(
                             self,
                             b"rmca-1.0:operation_state_incompatible"))
                 pass
             else:
                 connection.sendall(
                     host.send(self, b"rmca-1.0:unknown_command"))
             pass  # add more keys here
         pass
     pass