Hola a todos!
Hice una GUI para cifrar y descifrar cadenas con el método de Caesar.
(me basé en el code de: https://d14m4nt3.wordpress.com/2012/01/08/cifrado-caesar-y-un-poco-de-python/ (https://d14m4nt3.wordpress.com/2012/01/08/cifrado-caesar-y-un-poco-de-python/) | Si quieren más detalles de este método, visiten la página o visiten wikipedia. xD)
Etimología:
CitarEl cifrado César recibe su nombre en honor a Julio César, que, según Suetonio, lo usó con un desplazamiento de tres espacios para proteger sus mensajes importantes de contenido militar.
El programa está dividido en 2:
- GUI
- libreria caesar.py (el que nos cifrará/descifrará la cadena)
gui.py :
# -*- coding:utf-8 -*-
__author__ = "Barlan"
from caesar import Caesar # Cifrado Cesar
from tkinter import *
class GUI(Tk):
def __init__(self):
Tk.__init__(self)
self.title("GUI | Cifrado Caesar")
self.resizable(0,0)
self.config(bg="black")
self.i = IntVar()
self.s = StringVar()
Label(self, text="Cadena: ", bg="black", fg="white").grid(row=0, column=0)
self.cadena = Entry(self, textvariable=self.s, width=30)
self.cadena.grid(row=0, column=1)
Label(self, text="Clave a usar: ", bg="black", fg="white").grid(row=1, column=0)
self.clave = Entry(self, width=20)
self.clave.grid(row=1, column=1)
self.rc = Radiobutton(self, text="Encriptar", variable=self.i, value=1, command=self.toCaesar, bg="black", fg="white")
self.rc.grid(row=2, column=0)
self.rd = Radiobutton(self, text="Desencriptar", variable=self.i, value=2, command=self.toCaesar, bg="black", fg="white")
self.rd.grid(row=2, column=1)
Label(self, text="Resultado:", bg="black", fg="red", relief=RIDGE).grid(row=3, column=0, columnspan=2)
def toCaesar(self):
if self.i.get() == 1:
cadena = self.cadena.get().upper()
clv = int(self.clave.get())
r = Caesar()
a = r.cifrar(cadena, clv)
Label(self, text=a, bg="black", fg="white", relief=RIDGE).grid(row=4, column=0, columnspan=2, sticky=NSEW)
elif self.i.get() == 2:
cadena = self.cadena.get().upper()
clv = int(self.clave.get())
r = Caesar()
a = r.descifrar(cadena, clv)
Label(self, text=a, bg="black", fg="white", relief=RIDGE).grid(row=4, column=0, columnspan=2, sticky=NSEW)
GUI().mainloop()
caesar.py :
# -*- coding: utf-8 -*-
class Caesar():
def __init__(self):
# Lista de caracteres a usar.
self.caract = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789"
def cifrar(self, cadena, clv):
'''
Función que cifrará nuestro mensaje, a partir de la cadena y clave proporcionada.
'''
resultado = ""
for letra in cadena:
if letra == " ":
resultado += " "
else:
op = self.caract.find(letra) + clv
modulada = int(op) % 37
resultado = resultado + str(self.caract[modulada])
return(resultado)
def descifrar(self, cadena, clv):
'''
Función que descifrará nuestro mensaje cifrado, a partir de una clave y cadena proporcionada.
'''
resultado = ""
for letra in cadena:
if letra == " ":
resultado += " "
else:
op = self.caract.find(letra) - clv
modulada = int(op) % 37
resultado = resultado + str(self.caract[modulada])
return(resultado)
Ejemplo de uso:(http://k30.kn3.net/C/5/0/D/3/7/988.gif)
Si vemos, cada letra nueva se encuentra a 2 letras distantes de la original.
B + 2 = D
A + 2 = C
R + 2 = T
L + 2 = N
A + 2 = C
N + 2 = O
Lo mismo sucede al descifrarla, solo que ahora "retrocedemos" de caracteres:
D - 2 = B
C - 2 = A
T - 2 = R
N - 2 = L
C - 2 = A
O 2 = N
Saludos!
Muy bueno Barlan! Muchas gracias por compartir tus trabajos con nosotros.
Aprovecho para dejar mi código hecho con kivy.
cesar.py#/usr/bin/env python
# -*- encoding: utf8 -*-
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
class Ui_Cesar(GridLayout):
textInputText = ObjectProperty()
textInputOffset = ObjectProperty()
def run(self, *args):
self.text = self.textInputText.text
self.offset = self.textInputOffset.text
op = args[0].text.lower()
error = self.check()
if error:
return self.notify(error, True)
if op == "code":
result = self.code()
else:
result = self.decode()
self.notify(result)
def check(self):
try:
text = self.text.lower()
offset = int(self.offset)
if offset < 0:
offset = -(offset)
while offset > 25:
offset -= 26
self.text = text
self.offset = offset
except TypeError as e:
return "It is not possible to perform the operation."
except ValueError:
return "Offset must be an integer."
def code(self):
result = ""
for char in self.text:
value = ord(char)
if 97 <= value <= 122:
offsetValue = value + self.offset
if offsetValue > 122:
offsetValue -= 26
offsetChar = chr(offsetValue)
result = result + offsetChar
else:
result = result + char
return result
def decode(self):
result = ""
for char in self.text:
value = ord(char)
if 97 <= value <= 122:
offsetValue = value - self.offset
if offsetValue < 97:
offsetValue += 26
offsetChar = chr(offsetValue)
result = result + offsetChar
else:
result = result + char
return result
def notify(self, data, *args):
box = GridLayout()
box.cols = 1
textInputResult = TextInput(text=data, size_hint=(1, 4))
labelError = Label(text=data, size_hint=(1, 4))
if args:
box.add_widget(labelError)
else:
box.add_widget(textInputResult)
buttonOk = Button(text="Ok", size_hint=(1, 1))
box.add_widget(buttonOk)
popup = Popup(title='Notification',
content=box,
auto_dismiss=False)
buttonOk.bind(on_press=popup.dismiss)
popup.open()
class Cesar(App):
def build(self):
return Ui_Cesar()
if __name__ == "__main__":
c = Cesar()
c.run()
cesar.kvUi_Cesar:
<Ui_Cesar>:
cols: 2
textInputText: text
textInputOffset: offset
Label:
text: "Text"
size_hint: (1, 3)
TextInput:
id: text
multiline: True
size_hint: (1, 3)
Label:
text: "Offset"
TextInput:
id: offset
password: False
multiline: False
Button:
text: "Code"
on_press: root.run(self)
Button:
text: "Decode"
on_press: root.run(self)
Y un gif para continuar con tu estilo xD
(http://i.imgur.com/xopwa7E.gif)
Saludos!
WhiZ
Muy buenos aportes los dos. @WhiZ, muy chulo quedan las UI con Kivy, además por lo que veo es un proyecto FOSS. Me viene muy bien ahora que estoy dándole a Python.
Saludos.
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta
Muy bueno Barlan! Muchas gracias por compartir tus trabajos con nosotros.
Aprovecho para dejar mi código hecho con kivy.
cesar.py
#/usr/bin/env python
# -*- encoding: utf8 -*-
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
class Ui_Cesar(GridLayout):
textInputText = ObjectProperty()
textInputOffset = ObjectProperty()
def run(self, *args):
self.text = self.textInputText.text
self.offset = self.textInputOffset.text
op = args[0].text.lower()
error = self.check()
if error:
return self.notify(error, True)
if op == "code":
result = self.code()
else:
result = self.decode()
self.notify(result)
def check(self):
try:
text = self.text.lower()
offset = int(self.offset)
if offset < 0:
offset = -(offset)
while offset > 25:
offset -= 26
self.text = text
self.offset = offset
except TypeError as e:
return "It is not possible to perform the operation."
except ValueError:
return "Offset must be an integer."
def code(self):
result = ""
for char in self.text:
value = ord(char)
if 97 <= value <= 122:
offsetValue = value + self.offset
if offsetValue > 122:
offsetValue -= 26
offsetChar = chr(offsetValue)
result = result + offsetChar
else:
result = result + char
return result
def decode(self):
result = ""
for char in self.text:
value = ord(char)
if 97 <= value <= 122:
offsetValue = value - self.offset
if offsetValue < 97:
offsetValue += 26
offsetChar = chr(offsetValue)
result = result + offsetChar
else:
result = result + char
return result
def notify(self, data, *args):
box = GridLayout()
box.cols = 1
textInputResult = TextInput(text=data, size_hint=(1, 4))
labelError = Label(text=data, size_hint=(1, 4))
if args:
box.add_widget(labelError)
else:
box.add_widget(textInputResult)
buttonOk = Button(text="Ok", size_hint=(1, 1))
box.add_widget(buttonOk)
popup = Popup(title='Notification',
content=box,
auto_dismiss=False)
buttonOk.bind(on_press=popup.dismiss)
popup.open()
class Cesar(App):
def build(self):
return Ui_Cesar()
if __name__ == "__main__":
c = Cesar()
c.run()
cesar.kv
Ui_Cesar:
<Ui_Cesar>:
cols: 2
textInputText: text
textInputOffset: offset
Label:
text: "Text"
size_hint: (1, 3)
TextInput:
id: text
multiline: True
size_hint: (1, 3)
Label:
text: "Offset"
TextInput:
id: offset
password: False
multiline: False
Button:
text: "Code"
on_press: root.run(self)
Button:
text: "Decode"
on_press: root.run(self)
Y un gif para continuar con tu estilo xD
(http://i.imgur.com/xopwa7E.gif)
Saludos!
WhiZ
"Un GIF vale más que mil imágenes" (xD)
Muy completo code el tuyo.
Kivy me recuerda al chocolate, y me dan ganas de lanzarme hacia el.
¿No tienes algo con qué empezar? En estos momentos no estoy en "condiciones" para estar buscando en Google (tarea xD)
Saludos!
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta
@WhiZ, muy chulo quedan las UI con Kivy, además por lo que veo es un proyecto FOSS. Me viene muy bien ahora que estoy dándole a Python.
Sí. Pero eso no es lo mejor que tiene kivy. Es un framework muy organizado y que, además, permite portar tus apps a android.
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta¿No tienes algo con qué empezar? En estos momentos no estoy en "condiciones" para estar buscando en Google (tarea xD)
Si les interesa, les dejo dos buenos libros para que lean:
- Kivy Programming Guide (http://kivy.org/docs/pdf/Kivy-latest.pdf) --> Documentación
- Creating apps in Kivy (http://www.mediafire.com/view/2atmm2gzlnwcz0v/Creating_Apps_in_Kivy.pdf)
Más libros de Python por aquí (https://underc0de.org/foro/python/material-de-python/)
Saludos!
WhiZ
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta
Muy buenos aportes los dos. @WhiZ, muy chulo quedan las UI con Kivy, además por lo que veo es un proyecto FOSS. Me viene muy bien ahora que estoy dándole a Python.
Saludos.
tkinter deja mucho que desear. Pero claro, está mas orientado a proyectos pequeños y personales.
Y por lo que veo, Kivy (cada vez que lo pronuncio me recuerda a una barra de chocolate xD) está más orientado a proyectos de mayor envergadura, al igual que PyQT. Y checando un poco algunas imagenes, puedes hacer cosas bastante hermosas con el :'( .
Sinceramente recién me entero de kivy xD Le voy a dar una mirada.
Gracias BarlanV por el aporte y a ti WhiZ por la bibliografia.
Saludos
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta
No tienes permitido ver enlaces.
Registrate o Entra a tu cuenta
Muy buenos aportes los dos. @WhiZ (https://underc0de.org/foro/index.php?action=profile;u=21214), muy chulo quedan las UI con Kivy, además por lo que veo es un proyecto FOSS. Me viene muy bien ahora que estoy dándole a Python.
Saludos.
tkinter deja mucho que desear. Pero claro, está mas orientado a proyectos pequeños y personales.
Y por lo que veo, Kivy (cada vez que lo pronuncio me recuerda a una barra de chocolate xD) está más orientado a proyectos de mayor envergadura, al igual que PyQT. Y checando un poco algunas imagenes, puedes hacer cosas bastante hermosas con el :'( .
Barlan, no solo es multiplataforma sino que es muy sencillo y relativamente potente. Si lo combinas con PyGame se pueden hacer juegos para Android :)