How to 3DES encrypt in Python using the M2Crypto wrapper?
I have a working test of a hardware device that uses RSA encryption, in Python using M2Crypto. Now I need to test a similar device that uses 3DES encryption开发者_如何学C. But I can't figure out how to use M2Crypto to do triple DES encryption.
I know it should be possible from this chart. But unfortunately the documentation of M2Crypto I've found is sketchy. (The homepage at http://chandlerproject.org/ seems to be gone, along with Chandler.)
I've searched for 3DES and "OpenSSL API" and found some hard to grok C code for decrypting which makes it look like I need to use M2Crypto.EVP.Cipher. But I haven't found any examples of using it for DES. The closest I've found is this blog post on using it for AES encryption. It looks like I just need to figure out the correct arguments to M2Crypto.EVP.Cipher.__init__()
. I'll keep digging, but I thought it worth posting this question.
See here. There is reference for the following DES ciphers : 'des_ede_ecb', 'des_ede_cbc', 'des_ede_cfb', 'des_ede_ofb', 'des_ede3_ecb', 'des_ede3_cbc', 'des_ede3_cfb', 'des_ede3_ofb'.
The homepage seems to be here now.
The following code worked for me:
with open(keyfile, 'rb') as f:
key = f.read()
encrypt = 1
cipher = Cipher(alg='des_ede3_ecb', key=key, op=encrypt, iv='\0'*16)
ciphertext = cipher.update(plaintext)
ciphertext += cipher.final()
Note the keyfile is a 24-byte (binary) file with parity set as sometimes required for DES.
Note also that the iv argument is (I believe) ignored when using 'des_ede3_ecb', but I couldn't pass None
.)
精彩评论