1

I'm trying to write an app that needs large numbers of cryptographic strength pseudorandom bytes.

The RC4 cipher would be ideal for this; it's lightweight and simple to understand conceptually. So, I got the spec and wrote an RC4 algorithm in Python.

It works exactly as expected, but, it's slow as molasses. On my Core i7 2.2GHz, I can only get about 1MB/sec out of the algorithm.

Clearly the interpreted nature of Python is not the best suited for this sort of task. My problem is I'm not well versed in C coding - the best I've done with C is some Hello World stuff and some experiments with file reading and writing. Either way, I certainly am not good enough with C to use the Python-C APIs.

I do know .NET/C#, and I wrote the same algorithm in Windows on C#, and I Was able to easily get over 60MB/sec out of it. So .NET's CLR is a lot more optimized. But, the target platform for the Python app is Unix/Linux.

Ideally, I don't want to have to go through tons of middle-layers just to get an optimized RC4 cipher into a Python app.

Since RC4 depends on state, ideally I'd do this with a class (That's how I did it with my Python-only implementation.) So, here's a small snippet of what I want to be able to do:

rc4 = RC4Encrypter()
rc4.seed(myKey) # seed the RC4 algorithm with bytes from string myKey
rc4.getRC4Bytes(1048576) # get the next 1MB of RC4 cryptostream bytes as a binary string
rc4.encryptWithRC4(myString) # encrypt myString's bytes with RC4 bytes using xor and return

Any advice? I'd love to learn C but it's a big learning curve right now for just this simple project.

fdmillion
  • 4,823
  • 7
  • 45
  • 82
  • 1
    Why don't you find an RC4 cipher already written in C, and call it from Python? http://www.governmentsecurity.org/forum/topic/28052-rc4-file-encryption-utility/ – Robert Harvey May 14 '13 at 21:40
  • Would be a nice idea, except I don't know enough C to write the necessary glue code to wrap the RC4 stuff inside a Python module. I actually do know just enough C to write an RC4 stream cipher - I wrote one that simply seeds itself from /dev/urandom with a certain number of bytes then starts spitting out pseudorandom bits to stdout. But I don't know how to wrap that in C. I'll need to spend more time on C before I'll be good enough to do that. ;-) – fdmillion May 16 '13 at 07:57

1 Answers1

7

I believe PyCrypto has an RC4 implementation, check it out here

sbrichards
  • 2,169
  • 2
  • 19
  • 32
  • 2
    Just mind that PyCrypto's RC4 does not throw away any of the initial bytes of the RC4 keystream, which is a security weakness. In practice, the first 3000 bytes should be removed. – SquareRootOfTwentyThree May 15 '13 at 05:32
  • I could solve that by simply grabbing 3000 bytes then tossing them out... I was confused at first but then figured out ARC4 is what I'm looking for... Thanks! – fdmillion May 16 '13 at 07:58