Rizwan Kassim
Rizwan Kassim

Reputation: 8121

What's the most pythonic way of access C libraries - for example, OpenSSL?

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!

Upvotes: 3

Views: 1262

Answers (6)

joeforker
joeforker

Reputation: 41757

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

Upvotes: 5

Heikki Toivonen
Heikki Toivonen

Reputation: 31140

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.

Upvotes: 0

Brian Clapper
Brian Clapper

Reputation: 26210

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

Upvotes: 0

Benjamin Peterson
Benjamin Peterson

Reputation: 20530

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?

Upvotes: 5

Charlie Martin
Charlie Martin

Reputation: 112376

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

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375674

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.

Upvotes: 5

Related Questions