Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created October 20, 2012 03:29
Show Gist options
  • Select an option

  • Save kurtbrose/3921909 to your computer and use it in GitHub Desktop.

Select an option

Save kurtbrose/3921909 to your computer and use it in GitHub Desktop.
implementing DES-X (mode CBC) using PyCrypto
'''
This code implements DES-X mode CBC efficiently using PyCrypto
'''
from Crypto.Cipher import DES
def des_x(plaintext, key, iv='\0'*8):
'key must be 24 bytes, plaintext must be multiple of 8 bytes'
pre_whiten = XOR.new(key[ 8:16]).encrypt #XOR -- encrypt/decrypt are the same
post_whiten = XOR.new(key[16:24]).encrypt
encrypt = DES.new(key[:8], mode=DES.MODE_ECB).encrypt
out = []
prev_xor = XOR.new(iv).encrypt
for i in xrange(len(key)/8):
cur_plain = plaintext[i*8:i*8+8]
cur_cipher = post_whiten(encrypt(pre_whiten(prev_xor(cur_plain))))
out.append(cur_cipher)
prev_xor = XOR.new(cur_cipher).encrypt
return b"".join(out)
def un_des_x(ciphertext, key, iv='\0'*8):
'key must be 24 bytes, plaintext must be multiple of 8 bytes'
pre_whiten = XOR.new(key[ 8:16]).decrypt
post_whiten = XOR.new(key[16:24]).decrypt
decrypt = DES.new(key[:8], mode=DES.MODE_ECB).decrypt
out = []
prev_xor = XOR.new(iv).decrypt
for i in xrange(len(ciphertext)/8):
cur_cipher = ciphertext[i*8:i*8+8]
cur_plain = prev_xor(pre_whiten(decrypt(post_whiten(cur_cipher))))
out.append(cur_plain)
prev_xor = XOR.new(cur_cipher).decrypt
return b"".join(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment