views:

582

answers:

6

I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)

In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of commands. What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?

Thanks!

+4  A: 

ctypes is the place to start. It lets you call into DLLs, using C-declared types, etc. I don't know if there are limitations that will keep you from doing everything you need, but it's very capable, and it's included in the standard library.

Ned Batchelder
A: 

SWIG is pretty much the canonical method. Works good, too.

Charlie Martin
+5  A: 

There's lots of ways to interface with C (and C++) in Python. ctypes is pretty nice for quick little extensions, but it has a habit of turning would be compile time errors into runtime segfaults. If you're looking to write your own extension, SIP is very nice. SWIG is very general, but has a larger following. Of course, the first thing you should be doing is seeing if you really need to interface. Have you looked at PyCrypto?

Benjamin Peterson
I had glanced at it, but I was concerned as to why someone had taken over the project, suggested that no one use the old version (it's buggy), nor suggest that anyone use the new one. Gonna try it now, then readdress with ctypes or swig or sip.Thanks
Rizwan Kassim
A: 

I've had good success with Cython, as well.

Brian Clapper
+3  A: 

I was happy with M2Crypto (an OpenSSL wrapper) for blowfish.

import M2Crypto
from M2Crypto import EVP
import base64
import struct

key = '0' * 16 # security FTW
iv = '' # initialization vector FTW
dummy_block =  ' ' * 8

encrypt = EVP.Cipher('bf_cbc', key, iv, M2Crypto.encrypt)
decrypt = EVP.Cipher('bf_cbc', key, iv, M2Crypto.decrypt)

binary = struct.pack(">Q", 42)
ciphertext = encrypt.update(binary)

decrypt.update(ciphertext) # output is delayed by one block
i = struct.unpack(">Q", decrypt.update(dummy_block))

print i
joeforker
Ended up using PyCrypto, but the basic question of how to access C libraries was still of interest. M2Crypto's interesting, thanks!
Rizwan Kassim
A: 

I would recommend M2Crypto as well, but if the code sample by joeforker looks a bit strange you might have an easier time understanding the M2Crypto cipher unit tests, which include Blowfish. Check out the CipherTestCase in test_evp.py.

Heikki Toivonen