예제 #1
0
    def test_partial_decryption_w_task_monitor(self):
        """
        Test that partial decryption can be monitored using a TaskMonitor 
        object.
        """
        # Get a new task monitor and a counter
        task_monitor = TaskMonitor()
        partialDecryptionCounter = Counter()

        # Register a task monitor callback to increment the counter once
        # for each 5% progress of partial decryption
        def partial_decryption_callback(tm):
            partialDecryptionCounter.increment()

        task_monitor.add_on_progress_percent_callback(
            partial_decryption_callback, percent_span=5.0)

        # Generate a partial decryption passing the task_monitor object

        tprk = self.tSetUp.generate_private_key(0,
                                                self.trustees[0].private_key)
        text_to_encrypt_dir = os.path.join(
            os.path.dirname(__file__), "TestThresholdPrivateKey.resources")
        text_to_encrypt = os.path.join(text_to_encrypt_dir, "text_to_encrypt")
        text_encrypted = self.tpkey.encrypt_text(text_to_encrypt)
        tprk.generate_partial_decryption(text_encrypted, task_monitor)

        # Check that the counter has been incremented 100/5 = 20 times
        self.assertEqual(partialDecryptionCounter.value, 20)
예제 #2
0
    def test_cryptosystem_new_with_task_monitor(self):
        """
        Test that EGCryptoSystem.new(...) correctly reports progress using 
        task monitor.
        """
        # Get new counter and logger objects
        counter = Counter()
        logger = Logger()

        # Create a task monitor
        task_monitor = TaskMonitor()

        # Register callbacks for:

        # 1) logging subtask creation,
        def task_start_cb(tm):
            tm_p = tm.parent
            msg = "New task started: \"%s\" " \
                  "(Subtask #%d of %d for task \"%s\")\n" % \
                  (tm.task_name, tm_p.current_subtask_num, \
                   tm_p.num_subtasks, tm_p.task_name)
            logger.log(msg)

        task_monitor.add_on_task_start_callback(task_start_cb)

        # 2) logging subtask completion,
        def task_end_cb(tm):
            msg = "Task completed: \"%s\"\n" % tm.task_name
            logger.log(msg)

        task_monitor.add_on_task_end_callback(task_end_cb)

        # 3) counting the number of ticks of progress
        task_monitor.add_on_tick_callback(lambda tm: counter.increment(),
                                          num_ticks=1)

        # Note:
        # EGCryptoSystem.new(...) does not provide progress percent monitoring

        # We call EGCryptoSystem.new(...) with our task monitor object
        # We use the *insecure* size of 256bits for performance reasons
        EGCryptoSystem.new(nbits=256, task_monitor=task_monitor)

        # Check that the logged match the expected output of our callbacks:
        expected_log = \
"""New task started: \"Generate safe prime\" (Subtask #1 of 1 for task \"Root\")
Task completed: \"Generate safe prime\"
New task started: \"Obtain a generator for the cyclic group\" (Subtask #2 of 2 for task \"Root\")
Task completed: \"Obtain a generator for the cyclic group\"
"""
        self.assertEqual(str(logger), expected_log)

        # Also, each of the two subtask produces a progress tick before testing
        # each safe prime or generator candidate (respectively). So counter
        # must have registered at least two ticks (likely more)
        self.assertTrue(counter.value >= 2)
예제 #3
0
 def test_encryption_decryption_w_task_monitor(self):
     """
     Test that encryption and decryption can be monitored using a 
     TaskMonitor object.
     """
     # Get a new task monitor and two counters, one for encryption and one 
     # for decryption
     task_monitor = TaskMonitor()
     encryptionCounter = Counter()
     decryptionCounter = Counter()
     
     # Register a task monitor callback to increment encryptionCounter once 
     # for each 5% progress of encryption
     def encryption_callback(tm):
         encryptionCounter.increment()
     
     task_monitor.add_on_progress_percent_callback(encryption_callback, 
                                                   percent_span = 5.0)
     
     # Encrypt the test message, passing the task monitor
     ciphertext = self.public_key.encrypt_text(self.message, 
                                               task_monitor=task_monitor)
     
     # Unregister the encryption callback from the monitor and register 
     # a callback to increment decryptionCounter once for each 5% progress 
     # of decryption.
     task_monitor.remove_callback(encryption_callback)
     
     def decryption_callback(tm):
         decryptionCounter.increment()
     
     task_monitor.add_on_progress_percent_callback(decryption_callback, 
                                                   percent_span = 5.0)
     
     # Decrypt the message, passing the task monitor:
     self.private_key.decrypt_to_text(ciphertext, task_monitor=task_monitor)
     
     # Check that both counters have been incremented 100/5 = 20 times
     self.assertEqual(encryptionCounter.value, 20)
     self.assertEqual(decryptionCounter.value, 20)
예제 #4
0
def run_tool(nbits, filename, name, description):
    """
	Runs the plonevote.gen_cryptosys tool and generates a new cryptosystem.
	"""

    # Define callbacks for the TaskMonitor for progress monitoring
    def cb_task_start(task):
        print task.task_name + ":"

    def cb_task_progress(task):
        sys.stdout.write(".")
        sys.stdout.flush()

    def cb_task_end(task):
        print ""

    # Create new TaskMonitor and register the callbacks
    taskmon = TaskMonitor()
    taskmon.add_on_task_start_callback(cb_task_start)
    taskmon.add_on_tick_callback(cb_task_progress)
    taskmon.add_on_task_end_callback(cb_task_end)

    # Generate a new cryptosystem of the requested size
    try:
        cryptosys = EGCryptoSystem.new(nbits, task_monitor=taskmon)
    except KeyLengthTooLowError:
        print "ERROR: The given bit size does not meet PloneVoteCryptoLib "\
           "minimum security requirements (too short)."
    except KeyLengthNonBytableError:
        print "ERROR: The given bit size must be a multiple of 8."

    # Save the cryptosystem to file
    print "\nSaving cryptosystem to %s..." % filename,

    cryptosys.to_file(name, description, filename)

    print "SAVED.\n"
예제 #5
0
    # Define callbacks for the TaskMonitor for monitoring the encryption process
    if (len(in_file) <= 50):
        short_in_filename = in_file
    else:
        short_in_filename = os.path.split(in_file)[-1]
        if (len(short_in_filename) > 50):
            # Do ellipsis shortening
            short_in_filename = short_in_filename[0,20] + "..." + \
                 short_in_filename[-20,-1]

    def cb_task_percent_progress(task):
        print "  %.2f%% of %s encrypted..." % \
          (task.get_percent_completed(), short_in_filename)

    # Create new TaskMonitor and register the callbacks
    taskmon = TaskMonitor()
    taskmon.add_on_progress_percent_callback(cb_task_percent_progress, \
               percent_span = 5)

    # Encrypt bitstream
    print "Encrypting..."
    ciphertext = public_key.encrypt_bitstream(bitstream, task_monitor=taskmon)

    # Save the ciphertext to the output file
    try:
        ciphertext.to_file(out_file)
    except Exception, e:
        print "Problem while saving the output file %s: %s" % (in_file, e.msg)


def main():
예제 #6
0
def run_tool(key_file, in_file, out_file):
    """
	Runs the plonevote.encrypt tool and encrypts in_file into out_file.
	"""
    # Load the public key
    print("Loading public key...")
    try:
        public_key = PublicKey.from_file(key_file)
    except InvalidPloneVoteCryptoFileError as e:
        print("Invalid public key file (%s): %s" % (key_file, e.msg))
        sys.exit(2)

    # Open the input file
    print("Reading input file...")
    try:
        in_f = open(in_file, 'rb')
    except Exception as e:
        print("Problem while opening input file %s: %s" % (in_file, e))

    # Read the whole file into a bitstream
    bitstream = BitStream()
    try:
        read_quantum = 1024  # KB at a time
        bytes = in_f.read(read_quantum)
        while (bytes):
            for byte in bytes:
                bitstream.put_byte(ord(byte))
            bytes = in_f.read(read_quantum)
    except Exception as e:
        print("Problem while reading from input file %s: %s" % (in_file, e))

    in_f.close()

    # Define callbacks for the TaskMonitor for monitoring the encryption process
    if (len(in_file) <= 50):
        short_in_filename = in_file
    else:
        short_in_filename = os.path.split(in_file)[-1]
        if (len(short_in_filename) > 50):
            # Do ellipsis shortening
            short_in_filename = short_in_filename[0,20] + "..." + \
                 short_in_filename[-20,-1]

    def cb_task_percent_progress(task):
        print("  %.2f%% of %s encrypted..." % \
          (task.get_percent_completed(), short_in_filename))

    # Create new TaskMonitor and register the callbacks
    taskmon = TaskMonitor()
    taskmon.add_on_progress_percent_callback(cb_task_percent_progress, \
               percent_span = 5)

    # Encrypt bitstream
    print("Encrypting...")
    ciphertext = public_key.encrypt_bitstream(bitstream, task_monitor=taskmon)

    # Save the ciphertext to the output file
    try:
        ciphertext.to_file(out_file)
    except Exception as e:
        print("Problem while saving the output file %s: %s" % (in_file, e.msg))
예제 #7
0
 def setUp(self):
     """
     Unit test setup method.
     """
     self.task_monitor = TaskMonitor()