Question

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!

Was it helpful?

Solution

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?

OTHER TIPS

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.

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

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

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top