Snippets

Kunzhipeng 使用pyDes进行DES加解密

Created by Qi Peng
# coding: utf-8
# pyDes is required
# http://twhiteman.netfirms.com/des.html

import time
import binascii
import md5
import pyDes

# IV, must be 8 bytes's hex
IV = '0000000000000000'
# KEY, 8 bytes
KEY = '0011223344556677'

def encrypt(iv, key, data):
    """Calculate DES value for data using key
    Use DES rather than 3DES
    """
    iv = binascii.unhexlify(iv)
    key = binascii.unhexlify(key)
    k = pyDes.des(key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
    d = k.encrypt(data)
    return binascii.b2a_hex(d)

def decrypt(iv, key, data):
    """Decrypt DES value for data using key
    Use DES rather than 3DES
    """
    iv = binascii.unhexlify(iv)
    key = binascii.unhexlify(key)
    k = pyDes.des(key, pyDes.CBC, iv, pad=None, padmode=pyDes.PAD_PKCS5)
    data = binascii.a2b_hex(data)
    d = k.decrypt(data)
    return d

if __name__ == '__main__':
    # Test
    encryptdata = encrypt(IV, KEY, 'redice')
    print encryptdata
    decryptdata = decrypt(IV, KEY, encryptdata)
    print decryptdata

Comments (0)