[ Log On ]
  • Home
  • Tst
  • Cha
  • Enc
  • Code
  • IP
  • Fun
  • Sub
  • DigF
  • Cis
  • Com
  • Db
  • About
  • Netsim

Padding (DES)

[Back] Padding is used in a block cipher where we fill up the blocks with padding bytes. DES uses 64-bits with a 64-bit encryption key. The main padding methods are:

  • CMS. This pads with the same value as the number of padding bytes. Defined in RFC 5652, PKCS#5, PKCS#7 and RFC 1423 PEM.
  • Bit. This pads with 0x80 (10000000) followed by zero (null) bytes. Defined in ANSI X.923 and ISO/IEC 9797-1.
  • ZeroLength. This pads with zeros except for the last byte which is equal to the number (length) of padding bytes.
  • Null. This pads will NULL bytes. This is only used with ASCII text.
  • Space. This pads with spaces. This is only used with ASCII text.
  • Random. This pads with random bytes with the last byte defined by the number of padding bytes.

In the following code we use DES to encrypt and pad the input string. The key is generated by taking a SHA-256 hash of the password (and then taking the first 8 bytes to make 64-bits):

Message
Password

The results are then:

Result:

Presentation

Sample

If we use "hello", then we must pad to 5 bytes, this means there are 3 padding bytes (0x3) to give:

After padding (CMS): 68656c6c6f030303
Cipher (ECB): 8f770898ddb9fb38
  decrypt: hello

If we use "hello1", then we must pad to 6 bytes, this means there are 2 padding bytes (0x2) to give:

After padding (CMS): 68656c6c6f310202
Cipher (ECB): 602743be4d9c6f17
  decrypt: hello1

Code

The code generates a 64-bit key by taking the first 8 bytes of a SHA-256 hash value:

from Crypto.Cipher import DES
import hashlib
import sys
import binascii
import Padding

val='hello'
password='hello'

plaintext=val


def encrypt(plaintext,key, mode):
	encobj = DES.new(key,mode)
	return(encobj.encrypt(plaintext))

def decrypt(ciphertext,key, mode):
	encobj = DES.new(key,mode)
	return(encobj.decrypt(ciphertext))


print "\nDES"
key = hashlib.sha256(password).digest()[:8]

plaintext = Padding.appendPadding(plaintext,blocksize=Padding.DES_blocksize,mode='CMS')
print "After padding (CMS): "+binascii.hexlify(bytearray(plaintext))

ciphertext = encrypt(plaintext,key,DES.MODE_ECB)
print "Cipher (ECB): "+binascii.hexlify(bytearray(ciphertext))

plaintext = decrypt(ciphertext,key,DES.MODE_ECB)
plaintext = Padding.removePadding(plaintext,mode='CMS')
print "  decrypt: "+plaintext