Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using DES/3DES with python

what is the best module /package in python to use des /3des for encryption /decryption. could someone provide example to encrypt data with des/3des on python.

like image 233
ron Avatar asked Mar 12 '10 19:03

ron


People also ask

Is 3DES deprecated?

The Triple Data Encryption Algorithm (TDEA or 3DES) is being officially decommissioned, according to draught guidelines provided by NIST on July 19, 2018. According to the standards, 3DES will be deprecated for all new applications following a period of public deliberation, and its use will be prohibited after 2023.

Can 3DES be cracked?

Triple DES's key length does make it more secure against brute force attacks, but as mentioned in a previous post by relying on sequential encryption operations, it was vulnerable to meet-in-the-middle attacks.


2 Answers

pyDes can be used for both, DES and 3DES. Sample usage:

from pyDes import *

data = "Please encrypt my data"
k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
assert k.decrypt(d, padmode=PAD_PKCS5) == data

An alternative is the Chillkat Python Encryption Library which supports a lot of encryption algorithms (including DES & 3DES), but it is not free. Sample usage:

crypt.put_CryptAlgorithm("des")
crypt.put_CipherMode("cbc")
crypt.put_KeyLength(64)
crypt.put_PaddingScheme(0)
crypt.put_EncodingMode("hex")
ivHex = "0001020304050607"
crypt.SetEncodedIV(ivHex,"hex")
keyHex = "0001020304050607"
crypt.SetEncodedKey(keyHex,"hex")
encStr = crypt.encryptStringENC("The quick brown fox jumps over the lazy dog.")
print encStr
decStr = crypt.decryptStringENC(encStr)
print decStr

Anyway, I hope that you are aware that neither DES nor 3DES are considered paritcularly safe nowadays, there are many better alternatives (AES in the first place if you want to stick to standards, or Twofish, Blowfish, etc...)

like image 94
Leo Avatar answered Oct 01 '22 19:10

Leo


You can use the M2Crypto Python wrapper for OpenSSL. It has the advantage of being fast (as fast as OpenSSL), but the disadvantage of the documentation being limited.

Here is the example from my answer to "How to 3DES encrypt in Python using the M2Crypto wrapper?"

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()
like image 7
Daryl Spitzer Avatar answered Oct 05 '22 19:10

Daryl Spitzer