Example #1
0
class Affine(Cipher):
    """
    Affine cipher that uses a combination of Caesar and Multiplication cipher
    """

    def __init__(self):
        self.__caesar__ = Caesar()
        self.__multi__ = Multiplication()

    def encode(self, clear_text, key):
        """
        Encode message, first with multiplication then caesar.
        :param clear_text: clear text
        :param key: Tuple, (Multi_key, Caesar_key)
        :return: encoded message
        """
        encoded_multi = self.__multi__.encode(clear_text, key[0])
        encoded_caesar = self.__caesar__.encode(encoded_multi, key[1])
        return encoded_caesar

    def decode(self, encoded_text, key):
        """
        Decode message, first with caesar then multiplication
        :param encoded_text: encoded message
        :param key: Tuple, (Multi_key, Caesar_key)
        :return: decoded message
        """
        decoded_caesar = self.__caesar__.decode(encoded_text, key[1])
        decoded_multi = self.__multi__.decode(decoded_caesar, key[0])
        return decoded_multi

    def generate_keys(self):
        """
        Generates two keys for sender and receiver
        :return: keys with (Multiplication, Caesar) and inverse of that
        """

        key_1_1, key_2_1 = self.__multi__.generate_keys()
        key_1_2, key_2_2 = self.__caesar__.generate_keys()
        return (key_1_1, key_1_2), (key_2_1, key_2_2)

    def possible_keys(self):
        return self.__multi__.possible_keys() * self.__caesar__.possible_keys()
Example #2
0
 def create_expression(self, lhs, op, rhs):
     if op == '+':
         return Addition(lhs, rhs)
     elif op == '-':
         return Subtraction(lhs, rhs)
     elif op == '*':
         return Multiplication(lhs, rhs)
     elif op == '/':
         return Division(lhs, rhs)
     else:
         return Compare(lhs, op, rhs)
Example #3
0
from Addition import Addition
from MatrixMultiplication import MatrixMultiplication
from Activation import Activation
import numpy as np
import matplotlib.pyplot as plt


# Example : z = ax + b
g = Graph()
dGraph = g.set_as_default()

a = Variables(10, dGraph)
b = Variables(1, dGraph)
x = Placeholder(dGraph)

y = Multiplication(a, x, dGraph)
z = Addition(y, b, dGraph)

sess = Session()
result = sess.run(z, {x:12})

print("z = ax + b = 10*12 + 1 = ", result)


# Matrix multiplication process
g2 = Graph()
dGraph2 = g2.set_as_default()

a = Variables([[10,23], [23,1], [20,56]], dGraph2)
b = Variables([1,2], dGraph2)
x = Placeholder(dGraph2)
Example #4
0
from Caesar import Caesar
from Multiplication import Multiplication
from Sender import Sender
from Receiver import Receiver
from Hacker import Hacker
from Affine import Affine
from Unbreakable import Unbreakable
from RSA import RSA

cipher_list = {"Caesar": Caesar(), "Multiplication": Multiplication(),
               "Affine": Affine(), "Unbreakable": Unbreakable()}


def main():
    verify_ciphers()
    # verify_hacker()


def verify_hacker():
    for name, cipher in cipher_list.items():

        key_encrypt, key_decrypt = cipher.generate_keys()

        sender = Sender(cipher=cipher, key=key_encrypt)
        receiver = Receiver(cipher=cipher, key=key_decrypt)
        hacker = Hacker(cipher=cipher)

        clear_text = "Hello World"

        encrypted_message = sender.send_message(clear_text)
        decrypted_message = receiver.receive_message(encrypted_message)
Example #5
0
class Computer:

    opCodeTable = {
        1:
        lambda computer, programlocation: Addition(computer, programlocation,
                                                   3, True, True),
        2:
        lambda computer, programlocation: Multiplication(
            computer, programlocation, 3, True, True),
        3:
        lambda computer, programlocation: Input(computer, programlocation, 1,
                                                True, True),
        4:
        lambda computer, programlocation: Output(computer, programlocation, 1,
                                                 False, True),
        5:
        lambda computer, programlocation: JumpIfTrue(computer, programlocation,
                                                     2, False, False),
        6:
        lambda computer, programlocation: JumpIfFalse(
            computer, programlocation, 2, False, False),
        7:
        lambda computer, programlocation: LessThan(computer, programlocation,
                                                   3, True, True),
        8:
        lambda computer, programlocation: Equals(computer, programlocation, 3,
                                                 True, True),
        9:
        lambda computer, programlocation: AdjustRelativeBase(
            computer, programlocation, 1, False, True),
        99:
        lambda computer, programlocation: Halt(computer, programlocation, 1,
                                               False, False)
    }

    def GetOriginalProgram(self):
        return self._originalProgramData

    def LoadProgram(self, programData):
        self._programData = programData.copy()
        self._originalProgramData = self._programData.copy()
        moreMemory = [0] * 1024 * 10
        self._programData.extend(moreMemory)
        self._programIndex = 0
        self._programLine = 0
        return self

    def __init__(self):
        self._programData = None
        self._programIndex = None
        self._programLine = None
        self._relativeBase = 0
        self._input = None
        self._output = None
        self._halted = None

    def GetRelativeBase(self):
        return self._relativeBase

    def AdjustRelativeBase(self, val):
        self._relativeBase = self._relativeBase + val

    def SetInput(self, val):
        self._input = val

    def GetOutput(self):
        val = self._output
        self._output = None
        return val

    def GetInput(self):
        assert (self._input != None)
        val = self._input.pop(0)
        if (len(self._input) == 0):
            self._input = None
        return val

    def SetOutput(self, val):
        assert (self._output == None)
        self._output = val
        return self

    def ReadLocation(self, location):
        return self._programData[location]

    def MoveByOffset(self, amount):
        self._programIndex = self._programIndex + amount

    def MoveAbsolute(self, location):
        self._programIndex = location

    def WriteLocation(self, location, value):
        self._programData[location] = value

    def PeekAtOpCodeValue(self):
        opCodeValue = self.ReadLocation(self._programIndex)
        valueAsString = str(opCodeValue)
        if (len(valueAsString) > 2):
            opCodeValue = int(valueAsString[-2:])
        return opCodeValue

    def GetHalted(self):
        return self._halted is not None and self._halted == True

    def RunToNextIO(self):
        continueRun = True
        result = None
        inputNext = False
        while (continueRun and result is None and inputNext == False):
            oneResult, continueRun, inputNext = self.DoNext()
            if (oneResult is not None):
                result = oneResult
            if (self.PeekAtOpCodeValue() == 99):
                break
        return (result, continueRun, inputNext)

    def GetLine(self):
        continueRun = True
        inputNext = False
        output = []
        oneResult = 0
        while (continueRun and inputNext == False and oneResult != 10):
            oneResult, continueRun, inputNext = self.RunToNextIO()
            assert (inputNext == False)
            assert (continueRun == True)
            print(oneResult)
            output.append(oneResult)
        if (output[-1] == 10):
            output.pop()  #chop trailing newline
        #Rewrite in ascii
        output = "".join(list(map(lambda x: chr(x), output)))
        return output

    def SendLine(self):
        continueRun = True
        oneResult = None
        characterAboutToSend = 0
        while (continueRun and characterAboutToSend != 10):
            oneResult, continueRun, inputNext = self.RunToNextIO()
            assert (inputNext == True)
            assert (oneResult is None)
            characterAboutToSend = self._input[0]
            assert (self.PeekAtOpCodeValue() == 3)
            oneResult, continueRun, inputNext = self.DoNext()

    def DoNext(self):
        assert (self._halted is None or self._halted == False)
        self._halted = False
        opCodeValue = self.PeekAtOpCodeValue()
        opCodeConstructor = Computer.opCodeTable[opCodeValue]
        opCodeInstance = opCodeConstructor(self, self._programIndex)
        opCodeInstance.RunOpCode()
        returnValue = None
        if (opCodeValue == 4):
            returnValue = self.GetOutput()
        continueRun = True
        if (opCodeValue == 99):
            continueRun = False
            self._halted = True

        self._programLine = self._programLine + 1

        inputNext = False
        opCodeValue = self.PeekAtOpCodeValue()
        if (opCodeValue == 3):
            inputNext = True

        return (returnValue, continueRun, inputNext)
Example #6
0
#!/usr/bin/python
"Calculadora basica"

"Importar la clase Sum del archivo Sum.py"
from Sum import Sum
from Multiplication import Multiplication
from Subtract import Subtract
from Division import Division

print("Ingrese un numero:")
numeroUno = input()
print("Ingrese otro numero:")
numeroDos = input()

sumar = Sum()
print sumar.calculateSum(numeroUno, numeroDos)

restar = Subtract()
print restar.calculateSubtract(numeroUno, numeroDos)

dividir = Division()
print dividir.calculateDivision(numeroUno, numeroDos)

multiplicar = Multiplication()
print multiplicar.calculateMultiplication(numeroUno, numeroDos)
Example #7
0
from Addition import Addition
from Subtraction import Subtraction
from Multiplication import Multiplication
from Division import Division

my_add = Addition()
my_sub = Subtraction()
my_mult = Multiplication()
my_div = Division()


def main():
    while True:
        print("Welcome! Select operation:")
        print("1.Addition")
        print("2.Subtraction")
        print("3.Multiplication")
        print("4.Division")
        print("5.Exit")

        operation = int(input())

        if operation == 1:
            x = input("Enter value for x:")
            y = input("Enter value for y:")
            sum_ = my_add.sum(x, y)
            print(sum_)
        elif operation == 2:
            x = input("Enter value for x:")
            y = input("Enter value for y:")
            sub = my_sub.subtraction(x, y)
Example #8
0
import sys
from Addition import Addition
from Subtract import Subtract
from Multiplication import Multiplication

print("Menu")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")

i = sys.argv[1]  #input("Enter your option between 1-3 : ")

if (i == "1"):
    op = Addition()
elif (i == "2"):
    op = Subtract()
elif (i == "3"):
    op = Multiplication()
else:
    print("Wrong input given")
    sys.exit(0)

a = int(sys.argv[2])  #int(input("value for A :"))
b = int(sys.argv[3])  #int(input("value for B :"))
print(op.operation(a, b))
Example #9
0
class Computer:

    opCodeTable = {
        1:
        lambda computer, programlocation: Addition(computer, programlocation,
                                                   3, True, True),
        2:
        lambda computer, programlocation: Multiplication(
            computer, programlocation, 3, True, True),
        3:
        lambda computer, programlocation: Input(computer, programlocation, 1,
                                                True, True),
        4:
        lambda computer, programlocation: Output(computer, programlocation, 1,
                                                 False, True),
        5:
        lambda computer, programlocation: JumpIfTrue(computer, programlocation,
                                                     2, False, False),
        6:
        lambda computer, programlocation: JumpIfFalse(
            computer, programlocation, 2, False, False),
        7:
        lambda computer, programlocation: LessThan(computer, programlocation,
                                                   3, True, True),
        8:
        lambda computer, programlocation: Equals(computer, programlocation, 3,
                                                 True, True),
        9:
        lambda computer, programlocation: AdjustRelativeBase(
            computer, programlocation, 1, False, True),
        99:
        lambda computer, programlocation: Halt(computer, programlocation, 1,
                                               False, False)
    }

    def __init__(self,
                 programData,
                 unattended=False,
                 unattendedInputs=None,
                 inputOutputEvents=None,
                 programStart=0):
        self._programData = programData.copy()
        moreMemory = []
        for idx in range(0, 1024):
            moreMemory.append(0)
        self._programData.extend(moreMemory)
        self._programIndex = programStart
        self._programLine = 0
        self._unattended = unattended
        self._unattendedInputs = unattendedInputs
        self._currentUnattendedInput = 0
        self._outputs = []
        self._state = -1
        if (inputOutputEvents is not None):
            self._inputEvent = inputOutputEvents[0]
            self._outputEvent = inputOutputEvents[1]
        else:
            self._inputEvent = None
            self._outputEvent = None
        self._relativeBase = 0

    def GetRelativeBase(self):
        return self._relativeBase

    def AdjustRelativeBase(self, val):
        self._relativeBase = self._relativeBase + val

    def AddInput(self, inputValue):
        assert (self._unattended == True)
        self._unattendedInputs.append(inputValue)
        if (self._inputEvent is not None):
            self._inputEvent.set()

    def GetState(self):
        return self._state

    def GetAllOutputs(self):
        return self._outputs

    def GetLastOutput(self):
        assert (self.GetState() == 0)
        return self._outputs[-1]

    def GetHighestOutput(self):
        if (self._outputEvent is not None):
            self._outputEvent.wait()
            self._outputEvent.clear()
        return self._outputs[-1]

    def SetOutput(self, value):
        self._outputs.append(value)

    def GetUnattendedInput(self):
        if (self._unattendedInputs is None):
            return None
        assert (self._unattended == True)
        if (self._unattended == True):
            if (self._currentUnattendedInput == len(self._unattendedInputs)
                    and self._inputEvent != None):
                self._inputEvent.wait()
                self._inputEvent.clear()
            assert (self._currentUnattendedInput < len(self._unattendedInputs))
            val = self._unattendedInputs[self._currentUnattendedInput]
            self._currentUnattendedInput = self._currentUnattendedInput + 1
            return val
        else:
            return None

    def ReadLocation(self, location):
        return self._programData[location]

    def MoveByOffset(self, amount):
        self._programIndex = self._programIndex + amount

    def MoveAbsolute(self, location):
        self._programIndex = location

    def WriteLocation(self, location, value):
        self._programData[location] = value

    def Run(self):
        self._state = 1
        go = True
        while (True == go):
            opCodeValue = self.ReadLocation(self._programIndex)
            valueAsString = str(opCodeValue)
            if (len(valueAsString) > 2):
                opCodeValue = int(valueAsString[-2:])
            opCodeConstructor = self.opCodeTable[opCodeValue]
            opCodeInstance = opCodeConstructor(self, self._programIndex)

            if (isinstance(opCodeInstance, Halt)):
                go = False

            opCodeReturnValue = opCodeInstance.RunOpCode()

            if (isinstance(opCodeInstance, Output)):
                self._outputs.append(opCodeReturnValue)
                if (self._outputEvent is not None):
                    self._outputEvent.set()

            self._programLine = self._programLine + 1
        self._state = 0
        return self._outputs[-1]
Example #10
0
def calc_mult():
    my_test_calc = Multiplication()
    return my_test_calc
Example #11
0
        input("Enter your choice(1/2/3/4): "))  #Store the user operation

userFirstNumber = int(
    input("Enter first number: "))  #Store the first user entered number
userSecondNumber = int(
    input("Enter second number: "))  #Store the second user entered number

if userChoice == 1:  #If the menu choice is 1
    print("{0} + {1} = {2}".format(
        userFirstNumber, userSecondNumber,
        int(Addition(userFirstNumber,
                     userSecondNumber))))  #Print the sum of the user numbers
if userChoice == 2:  #If the menu choice is 2
    print("{0} - {1} = {2}".format(
        userFirstNumber, userSecondNumber,
        int(Subtraction(
            userFirstNumber,
            userSecondNumber))))  #Print the difference of the user numbers
if userChoice == 3:  #If the menu choice is 3
    print("{0} * {1} = {2}".format(
        userFirstNumber, userSecondNumber,
        int(Multiplication(
            userFirstNumber,
            userSecondNumber))))  #Print the product of the user numbers
if userChoice == 4:  #If the menu choice is 4
    print("{0} / {1} = {2}".format(
        userFirstNumber, userSecondNumber,
        int(Division(
            userFirstNumber,
            userSecondNumber))))  #Print the quotient of the user numbers
Example #12
0
 def __init__(self):
     self.__caesar__ = Caesar()
     self.__multi__ = Multiplication()