Exemplo n.º 1
0
    def garble(self):

        # Generate new wire labels
        self.wire_labels = {} # maps wire id to {"0":label0 ,"1": label1}

        # TODO: your code goes here
        for wire in self.wires:
            k0 = generate_key().hex()
            k1 = generate_key().hex()
            self.wire_labels[wire] = [k0, k1]

        # Generate garble tables
        self.garble_table = {}

        # TODO: your code goes here
        for gid in self.sorted_gates:
            gate = self.gates[gid]
            in0 = gate["inp"][0]
            in1 = gate["inp"][1]
            out = gate["out"][0]
            table = gate["table"]
            garble_table = []
            for i in range(len(table)):
                in0_value = (i >> 1) & 1
                in1_value = i & 1
                in0_key = bytes.fromhex(self.wire_labels[in0][in0_value])
                in1_key = bytes.fromhex(self.wire_labels[in1][in1_value])
                out_key = bytes.fromhex(self.wire_labels[out][table[i]])
                cip_inner = specialEncryption(in1_key, out_key)
                cip_outer = specialEncryption(in0_key, cip_inner)
                garble_table.append(cip_outer.hex())

            shuffle(garble_table)
            self.garble_table[gid] = garble_table
Exemplo n.º 2
0
    def garble(self):

        # Generate new wire labels
        self.wire_labels = {}  # maps wire id to {"0":label0 ,"1": label1}

        # TODO: your code goes here
        for wid in self.wires:
            key_0 = generate_key().encode('hex')
            key_1 = generate_key().encode('hex')
            self.wire_labels[wid] = [key_0, key_1]

        # Generate garble tables
        self.garble_table = {}

        # TODO: your code goes here
        index = [[0, 0], [0, 1], [1, 0], [1, 1]]
        for gid in self.gates:
            gate = self.gates[gid]
            inp = gate["inp"]
            wid = gate["out"][0]
            table = gate["table"]
            garble_table = []
            for i in range(4):
                key_0 = self.wire_labels[inp[0]]
                key_1 = self.wire_labels[inp[1]]
                label_0 = key_0[index[i][0]].decode('hex')
                label_1 = key_1[index[i][1]].decode('hex')
                msg = self.wire_labels[wid][table[i]].decode('hex')
                cipher = specialEncryption(label_0,
                                           specialEncryption(
                                               label_1, msg)).encode('hex')
                garble_table.append(cipher)
                shuffle(garble_table)
            self.garble_table[gid] = garble_table
Exemplo n.º 3
0
def create_account():
        if request.method == 'POST':
            data = request.get_json()
            new_account = Accounts(pk=None, email =data["email"], password =data["password"],first_name =data["first_name"],last_name =data["last_name"], api_key = "", balance = 0, equity = 0)
            new_account.api_key = generate_key()
            db.session.add(new_account)
            db.session.commit()
            print(new_account.api_key)
            return user_schema.jsonify(new_account)
Exemplo n.º 4
0
def post_user(firstname, lastname, email, password):
    data = request.get_json()
    user = User(firstname=data['firstname'],
                lastname=data['lastname'],
                email=data['email'],
                password=data['password'])
    user.token = generate_key()
    user.password = hash_pass(user.password)
    db.session.add(user)
    db.session.commit()
    return "<h1> Success </h1>"
Exemplo n.º 5
0
    def garble(self):

        # Generate new wire labels
        self.wire_labels = {}  # maps wire id to {"0":label0 ,"1": label1}

        # TODO: your code goes here
        #gates = from_json["gates"]
        wires = set()
        for gid in self.gates:
            gate = self.gates[gid]
            inp = gate["inp"]
            wires.update(inp)
            out = gate["out"]
            wires.update(gate["out"])

        for wid in wires:
            label0 = generate_key()
            label1 = generate_key()
            self.wire_labels[wid] = [label0.hex(), label1.hex()]

        # Generate garble tables
        self.garble_table = {}

        # TODO: your code goes here
        labels = self.wire_labels
        for gid in self.gates:
            gate = self.gates[gid]
            inp = gate["inp"]
            out = gate["out"]
            table = gate["table"]
            temp = []
            for i in range(len(table)):
                temp.append(
                    specialEncryption(
                        bytes.fromhex(labels[inp[0]][int(i / 2)]),
                        specialEncryption(
                            bytes.fromhex(labels[inp[1]][int(i % 2)]),
                            bytes.fromhex(labels[out[0]][table[i]]))).hex())
            shuffle(temp)
            self.garble_table[gid] = temp
Exemplo n.º 6
0
 def testCriacao(self):
     usuario=Usuario();
     usuario.usuario = criaUsuario();
     usuario.registro = criaRegistro_Egresso()
     convite = Convite();
     convite.de=usuario
     convite.para=usuario.registro
     convite.email="*****@*****.**"
     convite.id=1
     convite.chave=util.generate_key(convite.id)
     self.assertFalse(convite.is_ok(), "Verificação do status")
     convite.status=Convite.ok
     self.assertTrue(convite.is_ok(), "Verificação do status")
Exemplo n.º 7
0
def userinvite(request, registro_id):
    """
        Envia um convite para o usuário com Registro_egresso.id = registro_id. Caso o usuário já esteja registro, encaminha para a página do profile
    """
    message = ""
    try:
        registro = Registro_Egresso.objects.get(id=registro_id)
        if registro.usuario:
            return HttpResponseRedirect("/profile/"+str(registro.usuario.id)+"/")
#     except ObjectDoesNotExist:
#             return HttpResponseRedirect("/profileNotFound/"+registro_id+"/")
    except:
        pass
      
    if request.GET:
        print "enviou o email"
        email = request.GET.get("email")
        
        if not email_re.match(email):
            message = "email invalido"
        else:
#             warnings.filterwarnings("ignore", "Field 'id' doesn't have a default value")
            u_id = request.user.usuario.id
            r_id = registro_id
            email = request.GET.get("email")
            u = Usuario.objects.get(id=u_id)
            r = Registro_Egresso.objects.get(id=r_id)
            
            convites = Convite.objects.filter(de=u)
            convites = convites.filter(para=r)
            convites = convites.filter(email=email)
            if len(convites) == 0:
                c = Convite()
                c.de = u
                c.para = r
                c.email = email
                c.status = "pendente"
                print c
                c.save()
                c.chave = util.generate_key(c.id)
                c.save()
                context = {"link":('http://alumni.dsc.ufcg.edu.br/invite/'+c.chave)}
                send_mail(emailconf.assunto.replace("{{ de }}", request.user.usuario.registro.nome), render_to_string('template_email.html', context), emailconf.email, [c.email], fail_silently=False)
                message = "Convite enviado com sucesso para: "
                clean_emails = [email]
                return render_to_response("sent.html", {"user":request.user, "message":message, "clean":clean_emails })
            else:
                message = "Voce ja enviou convite para esse e-mail"
        
    return render(request, "user_invite.html", {"user":request.user, "registro":registro, "message":message })
Exemplo n.º 8
0
	def garble(self):
		# Generate new wire labels
		self.wire_labels = {} # maps wire id to {"0":label0 ,"1": label1}

		# Encode all bucket wires
		for wid in self.wires:
			key_0 = generate_key().encode('hex')
			key_1 = xor_hex(key_0, DELTA)
			self.wire_labels[wid] = [key_0, key_1] # Based on XOR-free structure

		B = 10
		T = len(self.gates) * B
		pool = []
		self.pool = fill_pool(pool, T+100)
Exemplo n.º 9
0
def multipleinvite(request):
    """
    Envia convite para egressos
    """
    e = ""
    clean_emails = []
    message = ""
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/")
        print "not loged in"
    
    #Lê a lista de e-mail, caso exista
    emails = []
    if request.POST:
        emails = request.POST["emails"].split(",")
        for i in range(len(emails)):
            emails[i] = emails[i].rstrip().lstrip()
            if not email_re.match(emails[i]):
                message = emails[i]+": email invalido"
                break
            
    #Caso um usuário logado que não possua um registro, o mesmo será criado
    try:
        usuario = request.user.usuario
    except:
        # User não tem usuário e registro associados
        usuario = createRegistro(request.user)
#         return render_to_response("multiple_invite.html", {"user":request.user, "message":message, "clean":clean_emails, "emails":e }, context_instance=RequestContext(request))

    #Caso existam endereços informados, envia e-mail para os mesmos.
    if len(emails) > 0:
        message = "Convite enviado com sucesso para os emails:"
        for e in emails:
            c = Convite()
            c.de = usuario
            # quando eh anonimo ele manda convite pra ele mesmo
            c.para = c.de.registro
            c.email = e
            c.status = c.pendente
            c.save()
            c.chave = util.generate_key(c.id)
            c.save()
            context = {"link":('http://alumni.dsc.ufcg.edu.br/invite/'+c.chave)}
            send_mail(emailconf.assunto.replace("{{ de }}", request.user.usuario.registro.nome), render_to_string('template_email.html', context), emailconf.email, [c.email], fail_silently=False)
            clean_emails.append(e)
        return render_to_response("sent.html", {"user":request.user, "message":message, "clean":clean_emails, "emails":e, "pagina": "multiple_invites" }, context_instance=RequestContext(request))
    
    #Página para informar e-mails
    return render_to_response("multiple_invite.html", {"user":request.user, "message":message, "clean":clean_emails, "emails":e, "pagina": "multiple_invites" }, context_instance=RequestContext(request))
Exemplo n.º 10
0
def register():
    try:
        form = r.RegistrationForm(request.form)

        if request.method == "POST" and form.validate():

            email = form.email.data
            password = bcrypt.generate_password_hash(str(form.password.data), 10)
            name = form.name.data.capitalize()
            gender = form.gender.data
            year_of_birth = util.get_year(form.age.data)
            tos_check_date = util.get_today()

            # check username for duplicate
            try:
                result = users.insert_one(
                    {
                        "email":    email,
                        "password": password,
                        "name":     name,
                        "gender":   gender,
                        "yob":      year_of_birth,
                        "tos":      tos_check_date
                    }
                )
            except DuplicateKeyError, e:
                flash("That username is already taken, please choose another.", "error")
                return render_template('register.html', form=form)

            # No exception is good...
            flash("Thanks for registering!")

            session['logged_in'] = True
            session["token"] = util.generate_key()
            session['email'] = email
            session['name'] = name

            return redirect(url_for('index'))

    except Exception as e:
        flash(e.message, "error")
        logger.error("Issue with registering user.", exc_info=True)

    return render_template('register.html', form=form)
Exemplo n.º 11
0
def login():
    error = None
    if request.method == 'POST':
        try:
            # this_user = User.objects.get(email=request.form['username'])
            this_user = users.find_one({"email": request.form["email"]})
            if request.form["email"] != this_user["email"]:
                error = "Invalid username."
            elif bcrypt.check_password_hash(this_user["password"], request.form['password']) is False:
                error = 'Invalid password'
            else:
                session["logged_in"] = True
                session["token"] = util.generate_key()
                session["email"] = this_user["email"]
                session["name"] = this_user["name"]

                flash("Logged in!")
                return redirect(url_for('index'))
        except Exception as e:
            flash("That's not quite right. Try that username and password one more time?", "error")
            logger.warn("Could log in user.", exc_info=True)

    return render_template('login.html', error=error)