简体   繁体   中英

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!

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.

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?

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.

我也在Cython上取得了很大的成功。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM