Example #1
0
    def __init__(self,
                 url,
                 magic_phrase,
                 max_turns=10,
                 callback=None,
                 callback_params=1,
                 msg_q=False):
        print('starting service')
        self.start_proba = 1.0
        self.magic_phrase = magic_phrase
        self.url = replace_localhost(url)
        self.bot = Alice()
        self.max_turns = max_turns
        self.sending_message = False
        self._id = None
        self.use_msg_q = msg_q  # msg_q sets whether or not we are queueing messages
        self.websocket = 'ws://%s/websocket' % self.url
        self.client = MeteorClient(self.websocket)
        self.client.ddp_client.ddpsocket.extra_headers = [('Bot', 'true')]
        print(self.client.ddp_client.ddpsocket.handshake_headers)
        self.client.connect()

        self.idle_time = 3 * 60
        self.thread_time = 2
        self.max_retry = 3
Example #2
0
def main():
    # 使用するqubitを用意
    bit_count = int(input('Bit count : '))
    qubits = [cirq.LineQubit(i) for i in range(bit_count)]

    alice = Alice()
    bob = Bob()
    eve = Eve()

    # アリスはランダムなビット列を生成する
    alice.create_origin_bits(bit_count)

    circuit = cirq.Circuit.from_ops(
        # アリスはX基底またはH基底でランダムにエンコードする
        # alice.set_initial_qubits(qubits),
        alice.encode(qubits),
        # # イヴが盗聴した場合
        # eve.decode(qubits),
        # ボブはX基底またはH基底でランダムにデコードする
        bob.decode(qubits))
    print(circuit)
    # ボブは結果を測定する
    bob.measure_qubits(circuit)

    # アリスとボブは互いにどのビットをどの基底でエンコード・デコードしたかを教えあう
    # 基底が一致したビットを抽出し、秘密鍵とする
    alice.set_secret_key(bob.decode_gates)
    bob.set_secret_key(alice.encode_gates)
Example #3
0
def main():
    k = 2
    #RSA

    alice = Alice(k)
    bank = Bank()
    merchant = Merchant()

    return start_simulation(alice, bank, merchant)
Example #4
0
def main(username, password, site, category, update):

    alice = Alice()
    alice.setup(username, password, site, update)

    a, p = alice.send_message()
    print('\na value (or alpha^r mod p): {0}'.format(a))
    bob = Bob()
    bob.setup(a, p)

    b = bob.receive_message()
    print('\nb value (or a^k mod p): {0}'.format(b))
    print('\nalpha raised to k mod p: {0}'.format(pow(alice.alpha, bob.k, p)))
    alice.compute_rwd(b, category)
Example #5
0
def main():

    host_addr = '127.0.0.1'
    host_port = 8082
    server_sni_hostname = 'example.com'
    server_cert = 'server.crt'
    client_cert = 'client.crt'
    client_key = 'client.key'

    username = "******"
    password = "******"
    site = "apple.com"
    update = False
    category = 'complex'

    alice = Alice()
    alice.setup(username, password, site, update)
    a, p = alice.send_message()

    alice_tuple = (a, p)

    serialized_data = pickle.dumps(alice_tuple)

    context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
                                         cafile=server_cert)
    context.load_cert_chain(certfile=client_cert, keyfile=client_key)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn = context.wrap_socket(s,
                               server_side=False,
                               server_hostname=server_sni_hostname)
    conn.connect((host_addr, host_port))
    print("SSL established. Peer: {}".format(conn.getpeercert()))
    conn.sendall(serialized_data)

    # get b from server (bob)
    bob_data = conn.recv(4096)
    b = pickle.loads(bob_data)

    conn.close()

    alice.compute_rwd(b, category)
Example #6
0
def run_transcription_loop():
    bot = Alice()
    r = sr.Recognizer()
    r.energy_threshold = 4000
    with sr.Microphone(device_index=None, sample_rate=16000,
                       chunk_size=1024) as source:
        while True:
            print("Awaiting user input.")
            audio = r.listen(source)
            print("Attempting to transcribe user input.")
            try:
                result = r.recognize_google(
                    audio, key=GOOGLE_SPEECH_RECOGNITION_API_KEY)
                z = bot.handle_action(result)
                if (z == 0):
                    bot.speak("Have a nice day and thank you")
                    sys.exit("Error message")

            except sr.UnknownValueError:
                bot.speak("Sorry come again")
            except sr.RequestError:
                bot.speak("Internet connection error")
            except:
                print("")
Example #7
0
# O "canal" representa o ambiente inseguro onde haverá a comunicação entre Bob e Alice
canal = "canal.txt"

# O caminho_chave_privada serve para provar que seus números secretos podem ser diferentes e que resultam na mesma chave privada
# NÃO É UTILIZADO EM UM SISTEMA DH REAL
caminho_chave_privada_alice = "chave_privada_alice.txt"
caminho_chave_privada_bob = "chave_privada_bob.txt"

# Limpa os arquivos privados e o canal público
limpa_canais(canal, caminho_chave_privada_alice, caminho_chave_privada_bob)

# É selecionado aleatoriamente um número primo positivo até 1000 e calculado sua menor raiz primitiva
(g, p) = calcula_raiz_primitiva_e_primo()

# São criados Alice e Bob recebendo o gerador e o número primo pelo canal público
alice = Alice(canal, caminho_chave_privada_alice, g, p)
bob = Bob(canal, caminho_chave_privada_bob, g, p)
input()

# Ada e Bob vão armazenar localmente as variáveis g e p que eles escolheram pelo público
alice.calcula_e_grava_A()
bob.calcula_e_grava_B()
input()

# Ada e Bob vão ler os resultados das chaves intermediárias um do outro que foram passados pela rede pública
alice.ler_B()
bob.ler_A()

# Os números secretos são salvos para provar que mesmo podendo ser diferentes, a chave privada é idêntica
# Ada e Bob vão gravar localmente sua chave privada, que será usada para descriptografar as mensagens
alice.mostrar_chave_secreta()
Example #8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--point-permute", help="enable the point-and-permute optimization", action='store_true')
    parser.add_argument("--free-xor", help="enable the free-XOR optimization", action='store_true')
    parser.add_argument("--grr3", help="enable the GRR3 optimization", action='store_true')
    args = parser.parse_args()

    if args.grr3 and not args.point_permute:
        print("The GRR3 optimization requires the point-and-permute optimization to be enabled")
        exit(0)

    if args.free_xor:
        config.USE_FREE_XOR = True
        print("Optimization enabled: free-XOR")

    if args.point_permute:
        config.USE_POINT_PERMUTE = True
        print("Optimization enabled: point-and-permute")

    if args.grr3:
        config.USE_GRR3 = True
        print("Optimization enabled: GRR3")

    alice = Alice()
    bob = Bob()

    # In this implementation we store wires as strings, whose values are those supplied by the user. 
    # These strings uniquely identify the corresponding wire. Not to be confused with labels, for which there are 
    # two for every unique wire!
    print(
        "Welcome! Please define your circuit by entering a sequence of logic gate specifications of the form \"z = x "
        "OP y\", where:")
    print(" - x and y are identifiers that uniquely specify the gate's two input wires, ")
    print(" - z is an identifier that uniquely specifies the gate's output wire")
    print(" - OP is the gate operation, which is one of \"and\", \"or\", \"xor\"")
    print(
        "Please enter one logic gate per line. When you are finished defining gates and are ready to proceed, "
        "please enter a blank line.")
    wires = dict()
    out_wires = []
    in_wires = []
    while True:
        gate_info = input()
        if not gate_info:
            break
        gate_info = gate_info.split()
        gate = Gate()
        if gate_info[3] == "and":
            gate.op = 'AND'
        elif gate_info[3] == "or":
            gate.op = 'OR'
        elif gate_info[3] == "xor":
            gate.op = 'XOR'
        else:
            raise ValueError("Operation must be one of \"and\", \"or\", \"xor\"")

        gate.in1 = gate_info[2]
        gate.in2 = gate_info[4]
        gate.out = gate_info[0]

        gates[gate.out] = gate

        wires[gate.in1] = ""
        wires[gate.in2] = ""
        wires[gate.out] = ""

        in_wires.append(gate.in1)
        in_wires.append(gate.in2)
        out_wires.append(gate.out)

        wires[gate_info[0]] = ""
        wires[gate_info[2]] = ""
        wires[gate_info[4]] = ""

    input_wires = []
    output_wires = []

    for w in wires:  # select the wires that are ONLY input and ONLY output
        if w in in_wires and w not in out_wires:
            input_wires.append(w)
        if w in out_wires and w not in in_wires:
            output_wires.append(w)

    print("Detected the following INPUT wires:  " + str(input_wires))
    print("Detected the following OUTPUT wires: " + str(output_wires))

    alice_wires = []
    alice_wire_values = []
    bob_wires = []
    bob_wire_values = []

    print("Among the input wires " + str(
        input_wires) + ", which are supplied by Alice, the garbler? Please enter the wire identifiers seperated by commas.")
    alice_wires = input().split(",")

    if len(alice_wires) > 0:  # Alice has at least one input
        print(
            "What are Alice's boolean input values? Please enter a sequence of 0s and 1s corresponding to her input wires, separated by commas.")
        alice_wire_values = list(map(int, input().split(",")))

        # ...therefore, the remaining inputs must be owned by Bob
        for w in input_wires:
            if w not in alice_wires:
                bob_wires.append(w)

        if len(bob_wires) > 0:
            print("The remaining input wires, " + str(bob_wires),
                  " must be supplied by Bob. Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
            bob_wire_values = list(map(int, input().split(",")))
        else:
            print("Assuming all inputs are supplied by Alice, and Bob only evaluates.")

    else:  # Alice has no inputs; all inputs must be owned by Bob
        print(
            "Assuming all inputs are supplied by Bob, the evaluator. What are Bob's boolean input values? Please enter a sequence of 0s and 1s corresponding to his input wires, separated by commas.")
        bob_input_values = input().split(",")

    # TODO Instead of exiting, handle bad user input gracefully.
    assert (len(alice_wires) == len(alice_wire_values))
    assert (len(bob_wire_values) == len(bob_wire_values))

    alice.input_wires = dict(zip(alice_wires, alice_wire_values))
    bob.input_wires = dict(zip(bob_wires, bob_wire_values))

    print()
    print("Successfully generated the following circuit: ")
    circuit = Circuit()
    # at the moment, we only support one output wire; hence output_wires[0]
    # but the infrastructure is in place to change this, if we so desire
    # to do this, we would likely have to represent the circuit as a digraph instead of a tree
    # and reimplement our construction and evaluation algorithms accordingly 
    circuit.build(output_wires[0], gates)
    circuit.tree.show()

    # Give the circuit to Alice to garble
    alice.circuit = circuit

    # Instruct Alice to generate labels and garble garble gates using the generated labels
    print()
    print("Alice generates labels for the circuit, and garbles gates accordingly:")
    alice.garble_gates()

    # Instruct Alice to permute the garbled tables
    print()
    print("Alice permutes the entries in each garbled gate's garbled truth table:")
    alice.permute_entries()

    # Transfer the circuit to Bob
    print()
    print("Alice transfers the circuit to Bob.")
    bob.circuit = alice.circuit

    for wire in alice.input_wires:
        # Transfer the labels corresponding to Alice's input to Bob
        bob.known_labels[wire] = alice.wire_labels[wire][alice.input_wires[wire]]

    # Simulate OT between Alice and Bob so that Bob can acquire labels corresponding to his input
    print()
    print("Bob uses OT to request from Alice labels corresponding to his input bits:")
    bob.request_labels(alice)

    # Instruct Bob to evaluate the circuit
    print()
    print("Bob proceeds to evaluate the circuit:")
    result = bob.evaluate()

    print()
    print("Alice reveals the value of the label that Bob computed as the circuit's output:")
    # Instruct Alice to reveal the result of Bob's computation
    alice.reveal_result(result)
Example #9
0
# -*- coding: utf-8 -*-
"""
2019/1/10 NPYLM (文字n-gramの追加)
"""
import numpy as np
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import collections
from pyp import PYP, PYP_prior
from alice import Alice
import pickle
import math
alice = Alice()
char_n_global = 3
#seq = ["A","B","A","B","C","D","A","B","A","B","C","D","C","D","A","B","A","B","A","B","C","D","C","D","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","C","D","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","C","D","C","D","B","A","B","A","B","A","C","D","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B","A","B"]

#start_symbol = "<SOS>"
#start_symbol = alice.start_symbol
#end_symbol = "<EOS>"
#end_symbol = alice.end_symbol
#seq = ["A","A","A","B","A","A","A","A","B","A","A","A","A","B","A","A"]


class G0():  #一様分布
    def __init__(self, V):
        self.V = V
        self.num_customers = V
        self.context = ()
        self.n = 0
        self.context_restaurant = {}
Example #10
0
    def play(self, board, direction, **options):

        cols = len(board)
        rows = len(board[0])

        if direction == HORIZ:

            if not self.__left__:

                for x in range(cols):

                    col = board[x]

                    if self.__left__:
                        break

                    for y in range(rows):

                        if col[y] == direction:
                            self.__vide__ = False
                            self.__left__ = x == 0

                            if self.__left__:
                                break

                            elif 0 <= x - 1 and board[x - 1][y] == EMPTY:
                                return (x - 1, y)
                            elif 0 <= y - 1 and board[x][y - 1] == EMPTY:
                                return (x, y - 1)
                            elif 0 <= x - 1 and y + 1 < rows and board[x - 1][
                                    y + 1] == EMPTY:
                                return (x - 1, y + 1)

            if not self.__right__:

                for x in reversed(range(cols)):

                    col = board[x]

                    if self.__right__:
                        break

                    for y in range(rows):

                        if col[y] == direction:
                            self.__vide__ = False
                            self.__right__ = x == cols - 1

                            if self.__right__:
                                break

                            if x + 1 < cols and board[x + 1][y] == EMPTY:
                                return (x + 1, y)
                            elif y + 1 < rows and board[x][y + 1] == EMPTY:
                                return (x, y + 1)
                            elif x + 1 < cols and 0 <= y - 1 and board[x + 1][
                                    y - 1] == EMPTY:
                                return (x + 1, y - 1)

            if self.__vide__:
                x = cols // 2
                y = rows // 2
                return (x, y) if board[x][y] == EMPTY else (x - 1, y)
            else:
                return Alice().play(board, direction)

        elif direction == VERTI:

            if not self.__top__:

                for y in range(rows):

                    if self.__top__:
                        break

                    for x in range(cols):

                        if board[x][y] == direction:
                            self.__vide__ = False
                            self.__top__ = y == 0

                            if self.__top__:
                                break

                            elif 0 <= y - 1 and board[x][y - 1] == EMPTY:
                                return (x, y - 1)
                            elif x + 1 < cols and 0 <= y - 1 and board[x + 1][
                                    y - 1] == EMPTY:
                                return (x + 1, y - 1)

            if not self.__bottom__:

                for y in reversed(range(rows)):

                    if self.__bottom__:
                        break

                    for x in range(cols):

                        if board[x][y] == direction:
                            self.__vide__ = False
                            self.__bottom__ = y == rows - 1

                            if self.__bottom__:
                                break

                            elif 0 <= x - 1 and y + 1 < rows and board[x - 1][
                                    y + 1] == EMPTY:
                                return (x - 1, y + 1)
                            elif y + 1 < rows and board[x][y + 1] == EMPTY:
                                return (x, y + 1)

            if self.__vide__:
                x = cols // 2
                y = rows // 2
                return (x, y) if board[x][y] == EMPTY else (x, y + 1)
            else:
                return Alice().play(board, direction)
Example #11
0
from alice import Alice
from bob import Bob
import numpy as np
import datetime

alice_messages = np.arange(10000)
print("Alice's messages: " + str(alice_messages))
bob_messages = np.arange(5000, 15000)
print("Bob's messages: " + str(bob_messages))
file_path = '.'

alice = Alice(alice_messages, file_path)
bob = Bob(bob_messages, file_path)
t1 = datetime.datetime.now()
intersection = alice.evaluate_intersection()
t2 = datetime.datetime.now()
print('Actual intersection: ' + str(intersection))
print('Evaluating intersection took: ' + str(t2 - t1))
Example #12
0
def run_transcription_loop():
    bot = Alice()
    r = sr.Recognizer()
    r.energy_threshold = 4000
    with sr.Microphone(device_index=None, sample_rate=16000,
                       chunk_size=1024) as source:
        while True:
            print("Awaiting user input.")
            audio = r.listen(source)
            print("Attempting to transcribe user input.")
            try:
                result = r.recognize_google(
                    audio, key=GOOGLE_SPEECH_RECOGNITION_API_KEY)
                z = bot.handle_action(result)
                if (z == 0):
                    bot.speak("Have a nice day and thank you")
                    sys.exit("Error message")

            except sr.UnknownValueError:
                bot.speak("Sorry come again")
            except sr.RequestError:
                bot.speak("Internet connection error")
            except:
                print("")


if __name__ == '__main__':
    bot = Alice()
    bot.speak("Hello Sir")
    run_transcription_loop()
Example #13
0
def main_2():
    alice = Alice()
    bob = Bob()
    network = Network()