Question

This is simply driving me crazy.

This is what happenned:

Inside the python shell:

>>> from Crypto.Cipher import ARC4
>>> a = ARC4.new('0123456789123456')
>>> b = ARC4.new('0123456789123456')
>>> de = b.decrypt
>>> en = a.encrypt
>>> en('abcd')
'\x18\x07\x8a\xdc'
>>> en('abcd')
'\x89>\xa0T'
>>> en('abcd')
'y\xe1-\xfe'
>>> en('abcd')
'\xc7\xf6\x19\xfc'
>>> 

I encrypted abcd 4 times with the same key. And all the four times I got different encrypted strings.

And when I did the following thing(Maybe I would get the same decrypted message on decrypting all the above different encrypted messages).

>>> al  = []
>>> for i in range(10):
    al.append(en('abcd'))


>>> al
['\x81\x05h\x06', '\x11;\x88\xc7', '\xb6\xb9g\x10', '\x1e$\x8c\xca', '\xbdh\xc2\xf0', 'ruiO', '7\xec\x7f\xdf', '\x08\xf3\x90\x8a', '\x1c\x95\xf3(', '\xbd@-\x11']

>>> gl = []
>>> for i in range(10):
    gl.append(de(al[i]))


>>> gl
['\xc8\x0f6\xb7', '\x18y`A', 'tm\x12\t', '\x9c\xf65M', '\xd6\xe8\x02\xa3', 'M\xa5sc', '\x1b\x82|\x08', '\x87\xbd \xd7', '\xd3:f\xd7', '\x05\x81?\xc5']
>>> 

So not even once did I get the original message abcd..!

Why is this happening??

How do I overcome this??

Please help me solve this issue.

I am using the pyCrypto library on a Linux Mint machine.

Was it helpful?

Solution

ACR4 is a stream cipher. It does not encrypt the way you think it does. Try this:

en("abcd" * 16)

and see what happens. The result will not be 16 times the same bytes but similar to what you tried in your question.

If you want to encrypt to the same bytes, you must use a new instance of ACR4:

e1 = ACR4.new('0123456789123456').encrypt
e2 = ACR4.new('0123456789123456').encrypt

assert e1("abcd") == e2("abcd")

OTHER TIPS

RC4 is a stream cipher, so the encrypted form of some plaintext depends on what the cipher has already encrypted.

>>> encrypted = [en('abcd') for i in range(4)]
>>> encrypted
['(h=\xd5', 'h \x8b\xe2', '\xa3\xb6\x16}', '\xe3\xb0\xda\xe3']
>>> decrypted = [de(x) for x in encrypted]
>>> decrypted
['abcd', 'abcd', 'abcd', 'abcd']

Create new RC4 objects before doing the encryption/decryption and you'll get the result you expect:

>>> a = ARC4.new('0123456789123456')
>>> b = ARC4.new('0123456789123456')
>>> de = b.decrypt
>>> en = a.encrypt
>>> al  = []
>>> for i in range(10):
...   al.append(en('abcd'))
... 
>>> gl = []
>>> for i in range(10):
...   gl.append(de(al[i]))
... 
>>> gl
['abcd', 'abcd', 'abcd', 'abcd', 'abcd', 'abcd', 'abcd', 'abcd', 'abcd', 'abcd']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top