Advertisement
Guest User

Untitled

a guest
Mar 16th, 2011
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.73 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. # Written by kenkeiras
  4. ##############################################################################
  5. # Copyright (C) 2011 kenkeiras
  6. #
  7. # This program is free software. It comes without any warranty, to
  8. # the extent permitted by applicable law. You can redistribute it
  9. # and/or modify it under the terms of the Do What The Fuck You Want
  10. # To Public License, Version 2, as published by Sam Hocevar.
  11. #
  12. # See http://sam.zoy.org/wtfpl/COPYING for more details.
  13. ##############################################################################
  14. # Cifrado usando Game 3-4
  15.  
  16. import sys,time
  17.  
  18. if len(sys.argv) in [2,3]:
  19.     print sys.argv[0]," [<key> <input> <output>]"
  20.     exit(0)
  21.  
  22. dibujos = len(sys.argv) > 4
  23.  
  24. # Genera un campo
  25. def genf(h,w,val=False):
  26.   f=[]
  27.   for i in xrange(h):
  28.     r=[]
  29.     for j in xrange(w):
  30.       r.append(val)
  31.     f.append(r)
  32.   return f
  33.  
  34. # Mantiene n entre 0 y d
  35. def rmd(n,d):
  36.   if n < 0:
  37.     n = d + n
  38.   return n % d
  39.  
  40. # Dibuja las figuras iniciales
  41. #
  42. #   #
  43. #   #
  44. # #### #
  45. #   # ####
  46. #      #
  47. #      #
  48. #
  49. def drawpair(f, xo, yo):
  50.  
  51.   # First one
  52.  
  53.   f[yo][xo+2]=True
  54.   f[yo+1][xo+2]=True
  55.   f[yo+2][xo+2]=True
  56.   f[yo+3][xo+2]=True
  57.  
  58.   f[yo+2][xo]=True
  59.   f[yo+2][xo+1]=True
  60.   f[yo+2][xo+2]=True
  61.   f[yo+2][xo+3]=True
  62.  
  63.   # Second one
  64.  
  65.   f[yo+2][xo+5]=True
  66.   f[yo+3][xo+5]=True
  67.   f[yo+4][xo+5]=True
  68.   f[yo+5][xo+5]=True
  69.  
  70.   f[yo+4][xo+4]=True
  71.   f[yo+4][xo+5]=True
  72.   f[yo+4][xo+6]=True
  73.   f[yo+4][xo+7]=True
  74.  
  75.   return f
  76.  
  77. # Hace XOR de la posición [i][j] del campo con un bit
  78. def bitFlip(f, i, j,b,n):
  79.   f[i][j] = f[i][j] ^ (b & (1<<n) > 0)
  80.   return f
  81.  
  82. # "Introduce" la clave [k] en el campo [f]
  83. def addkey(f, k ):
  84.   # Comprueba que la clave cabe en el campo
  85.   if (len(f) * len(f[0]))/8 < len(k):
  86.     print "Campo demasiado corto"
  87.     exit(1)
  88.  
  89.   i = 0
  90.   j = 0
  91.   # Para cada celda
  92.   for b in k:
  93.     for n in xrange(8):
  94.         # Hace XOR de la celda y el bit
  95.         # de la clave correspondiente
  96.         f=bitFlip(f,i,j,ord(b),n)
  97.  
  98.         j+=1
  99.         if j >= len(f[i]):
  100.             j = 0
  101.             i+=1
  102.  
  103.   return f
  104.  
  105. # Hace que el campo pase al siguiente estado
  106. def nextstep(f):
  107.   # Genera un nuevo campo
  108.   o = genf(len(f),len(f[0]))
  109.  
  110.   # Por cada celda
  111.   for y in xrange(len(f)):
  112.     for x in xrange(len(f[y])):
  113.       # Se comprueba el número de vecinos
  114.       c = 0
  115.       for i in [-1,0,1]:
  116.         for j in [-1,0,1]:
  117.           # Sin contarse a uno mismo!
  118.           if [i,j] == [0,0]:
  119.             continue
  120.           if (f[rmd( y+i, len(f) )] [rmd( x+j, len(f[0]) )]):
  121.             c+=1
  122.       # Activar si el número es 3 o 4
  123.       o[y][x]=c in [3,4]
  124.   return o
  125.  
  126. # Muestra el campo
  127. def fp(f):
  128.  
  129.   print "+"+"-"*len(f[0])+"+"
  130.  
  131.   # Por cada celda
  132.   for r in f:
  133.     sys.stdout.write("|")
  134.     for d in r:
  135.       # '0' si está encendida y ' ' en otro caso
  136.       x='O' if d else ' '
  137.       sys.stdout.write(x)
  138.     sys.stdout.write("|\n")
  139.  
  140.   print "+"+"-"*len(f[0])+"+"
  141.  
  142. # Convierte un campo en una cadena de Bytes
  143. def getBytes(f):
  144.   s = ""
  145.   i = 0
  146.   act = 0
  147.   # Para cada celda
  148.   for r in f:
  149.     for c in r:
  150.       # Añadimos el bit
  151.       act |= (c*(1<<i))
  152.       i+=1
  153.  
  154.       # Si rellenamos un byte, lo añadimos a la cadena
  155.       # y vuelta a empezar
  156.       if ( i > 7 ):
  157.         s+=chr(act)
  158.         act=0
  159.         i=0
  160.  
  161.   return s
  162.  
  163. h=25 # Anchura
  164. w=30 # Altura
  165.  
  166. # Generamos un campo
  167. f=genf(h,w)
  168.  
  169. # Dibujamos las figuras ( con un offset 1,1 por ejemplo )
  170. f=drawpair(f,1,1)
  171.  
  172. # Esperamos 200 generaciones
  173. for i in xrange(200):
  174.   print i
  175.   if dibujos:
  176.     fp(f)
  177.  
  178.   f=nextstep(f)
  179.  
  180. # Mostramos el campo
  181. if dibujos:
  182.   fp(f)
  183.  
  184. # Leemos la clave
  185. if (len(sys.argv)>3):
  186.   k=sys.argv[1]
  187. else:
  188.   k = raw_input("Clave:")
  189.  
  190. # La codificamos en el autómata
  191. addkey(f,k)
  192.  
  193. fp(f)
  194.  
  195. # Le damos 75 generaciones para que se mezcle bien
  196. for j in xrange(75):
  197.   i+=1
  198.   print i
  199.   if dibujos:
  200.     fp(f)
  201.  
  202.   f=nextstep(f)
  203.  
  204. # Leemos los nombres de los archivos
  205. fin = ""
  206. if (len(sys.argv)>3):
  207.   fin = sys.argv[2]
  208. else:
  209.   fin = raw_input("Archivo a cifrar/descifrar:")
  210.  
  211. fon = ""
  212. if (len(sys.argv)>3):
  213.   fon = sys.argv[3]
  214. else:
  215.   fon = raw_input("Archivo de salida:")
  216.  
  217. # Los abrimos
  218. fi = open(fin,"rb")
  219. fo = open(fon,"wb")
  220.  
  221. # Comprobamos el número de bytes que podemos recibir por cada estado
  222. avail = (len(f) * len(f[0]))/8
  223.  
  224. # Y [des]ciframos
  225. while True:
  226.  
  227.   if dibujos:
  228.     fp(f)
  229.  
  230.   c = fi.read(avail) # Leemos los bytes originales
  231.  
  232.   # Si ya acabamos, cerramos
  233.   if len(c) < 1:
  234.     break
  235.  
  236.   bt = getBytes(f) # Leemos los del autómata
  237.  
  238.   # Guardamos la mezcla
  239.   for i in xrange(len(c)):
  240.     fo.write(chr(ord(c[i])^ord(bt[i])))
  241.  
  242.   # Y pasamos a la siguiente generacion
  243.   f=nextstep(f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement