[Tutor] How do I save the output of the rotor module?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Nov 6 22:04:06 EST 2003



On Thu, 6 Nov 2003, Danny Yoo wrote:

> These two facts interact in a funny way: since you're doing the encoding,
> line by line:
>
> > rt = rotor.newrotor('606')
> > for item in contents:
> >      encon.append(rt.encrypt(item))
> > print encon
>
> is very likely that the encoded file won't have the same number of
> newlines as the original input.
>
>
> This, combined with the knowledge that:
>
>     r.encrypt(a) + r.encrypt(b) != r.encrypt(a + b)
>
> should be enough to see that we're in trouble as soon as we try decoding
> the string.  *grin*
>
>
> Does this make sense so far?


Hi Mike,


I pressed "Send" too quickly!  *grin*


I mean to talk about two ways to solve the problem.  One way to avoid the
issue with rotor's behavior is to encode and decode the whole thing at
once instead of in parts.



So instead of:

###
contents = ["This is a line of text\n",
            "including newlines\n",
            "for rotor testing."]
print contents   # shows a list of three strings
encon = []
rt = rotor.newrotor('606')
for item in contents:
     encon.append(rt.encrypt(item))
print encon
###



We can do this:

###
contents = ["This is a line of text\n",
            "including newlines\n",
            "for rotor testing."]
text = ''.join(contents)
rt = rotor.newrotor('606')
encon = rt.encrypt(text)
###


What we end up with is a single string that we can write to disk.  When we
read from disk, we again read the whole file as a single string:


###
fh = open('text.txt', 'r')
incoming = fh.read()     # read from a file
fh.close()
print incoming
###


and call decrypt() on that single string.




But the simpler approach is to use rotor's rotor.encryptmore() and
rotor.decryptmore()  methods instead:

###
>>> import rotor
>>> rt = rotor.newrotor("foo")
>>> rt.encryptmore("hello") + rt.encryptmore("world")
'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6'
>>>
>>>
>>> rt = rotor.newrotor("foo")
>>> rt.encryptmore("helloworld")
'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6'
###


encryptmore() and decryptmore() preserve the property that

    rt.encryptmore(a + b)

and

    rt.encryptmore(a) + rt.encryptmore(b)

are equivalent, so if you just use these methods instead, you should get
good results.  But when decrypting, be sure to reset the rotor to the
initial state, so that the gears are in the right positions... *grin*



Hope this helps!




More information about the Tutor mailing list