python模块介绍- pyDesDES加密解密
2013-05-14 磁针石
#承接软件自动化实施与培训等gtalk:ouyangchongwu#gmail.com qq 37391319 博客:http://blog.csdn.net/oychw
#版权所有,转载刊登请来函联系
# 深圳测试自动化python项目接单群113938272深圳会计软件测试兼职 6089740
#深圳地摊群 66250781武冈洞口城步新宁乡情群49494279
#参考资料:《ThePython Standard Library by Example 2011》
# http://docs.python.org/2/howto/sockets.html
这是一个纯Python实现的DES加密算法,可移植性好,其他的DES算法出于性能原因用C实现,可移植性相对较差。
同时基于DES实现了三重DES。三重DES或者是24字节密钥的DES-EDE3,或16字节密钥的DES-EDE2。
本模块不适合那些需要速度和性能的DES,它在AMD2000+只能对每秒2.5千字节进行加密或解密。
三重DES是用指定的键将数据用DES算法进行3次加密。提供的密钥被分成3个部分,每部分为8个字节长。
提供24字节的密钥时,三重DES算法使用DES-EDE3方法。这意味着有三个DES操作encrypt-decrypt-encrypt使用3个不同的密钥。
提供16个字节的密钥,三重DES方法将使用DES-EDE2。encrypt-decrypt-encrypt的第1和第3步骤使用相同的密钥。
pyDes Usage
Classinitialization
--------------------
pyDes.des(key,[mode], [IV], [pad], [padmode])
pyDes.triple_des(key,[mode], [IV], [pad], [padmode])
key -> Bytes containing the encryption key.8 bytes for DES, 16 or 24 bytes
for Triple DES
mode -> Optional argument for encryptiontype, can be either
pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining)。默认值ECB。
IV -> Optional Initial Value bytes, mustbe supplied if using CBC mode.
Length must be 8 bytes. 默认值:None。
pad -> Optional argument, set the padcharacter (PAD_NORMAL) to use during
all encrypt/decrpt operations done with this instance. 默认值:None。
padmode ->Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5)
to use duringall encrypt/decrpt operations done with this instance. 默认值:PAD_NORMAL。
I recommendto use PAD_PKCS5 padding, as then you never need to worry about any
paddingissues, as the padding can be removed unambiguously upon decrypting
data that wasencrypted using PAD_PKCS5 padmode.
Commonmethods
--------------
encrypt(data,[pad], [padmode])
decrypt(data,[pad], [padmode])
data -> Bytes to be encrypted/decrypted
pad -> Optional argument. Only when usingpadmode of PAD_NORMAL. For
encryption, adds this characters to the end of the data block when
data is not a multiple of 8 bytes. For decryption, will remove the
trailing characters that match this pad character from the last 8
bytes of the unencrypted data block.
padmode ->Optional argument, set the padding mode, must be one of PAD_NORMAL
or PAD_PKCS5). Defaults to PAD_NORMAL.
实例:
import pyDes
import binascii
data = "Pleaseencrypt my data"
k = pyDes.des("DESCRYPT",pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None,
padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted:%r" % binascii.hexlify(d)
print "Decrypted:%r" % k.decrypt(d)
assert k.decrypt(d) ==data
执行结果:
Encrypted:'6fce536566e6a68f8298c756d049dc031e97e49926079c49'
Decrypted: 'Pleaseencrypt my data'
原文链接:http://blog.csdn.net/oychw/article/details/8924859