Saturday, March 23, 2013

Cypher which has probably been done before

I had an idea for a somewhat simple cypher a few weeks ago, and I finally got around to coding it up in Python. Basically, it takes a letter, finds the index of that letter within the cypher key, and then adds the index to a running offset value. The offset value is then modulous by the length of the cypher key, and the location within the cypher key associated with the new index is output. Optionally, a static value can be added to every offset.
If anybody actually sees this, let me know what you think.

 
'''
A module for creating and decoding a simple cypher-text
'''

from collections import OrderedDict

cyStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.;:"\'!@#$%^&*()[]{}-?/'

def rollingEncode(string, offset=0, cyString=cyStr):
 cyString = "".join(OrderedDict.fromkeys(cyString).keys())
 ncyStr = len(cyString)

 if ncyStr == 0:
  return string

 anslist = []
 cyPos = 0
 
 for a in string:
  index = cyString.find(a)
  if index != -1:
   cyPos += index + offset
   while cyPos < 0:
    cyPos += ncyStr
   cyPos = cyPos % ncyStr
   anslist.append(cyString[cyPos])
  else:
   anslist.append(a)
   
 return ''.join(anslist)
 
def rollingDecode(string, offset = 0, cyString=cyStr):
 cyString = "".join(OrderedDict.fromkeys(cyString).keys())
 ncyStr = len(cyString)

 if ncyStr == 0:
  return string

 anslist = []
 cyPos = offset
 
 for a in string:
  index = cyString.find(a)
  if index != -1:
   index -= cyPos
   while index < 0:
    index += ncyStr
    
   index = index % ncyStr
   
   anslist.append(cyString[index])
   cyPos += index + offset
   
   while cyPos < 0:
    cyPos += ncyStr
   
   cyPos = cyPos % ncyStr
  else:
   anslist.append(a)
   
 return ''.join(anslist)
   
if __name__ == '__main__':
 import sys
 if len(sys.argv) > 1:
  if len(sys.argv) > 2:
   cypher = sys.argv[2]
  else:
   cypher = cyStr
   
  print rollingEncode(sys.argv[1], cyString=cypher)
  sys.exit(0)
 
 cypher = 'The quick brown fox jumped over the lazy dog.!?'
 a = "This is a test. WHOOOO!"
 offsets = [-500, -50 -5, 0, 5, 50, 500]
 for o in offsets:
  b = rollingEncode(a, o, cypher)
  c = rollingDecode(b, o, cypher)
  print "offset =", o, "cypher = '" + cypher + "'"
  print "a =", a
  print "b =", b
  print "c =", c
  print ""
  
  b = rollingEncode(a, o)
  c = rollingDecode(b, o)
  print "offset =", o, "cypher = '" + cyStr + "'"
  print "a =", a
  print "b =", b
  print "c =", c
  print ""

No comments:

Post a Comment