python基于pyDes库实现des加密的⽅法
本⽂实例讲述了python基于pyDes库实现des加密的⽅法。分享给⼤家供⼤家参考,具体如下:
如需要在python中使⽤des加密,可以直接使⽤pyDes库加密,该库提供了CBC和ECB两种加密⽅式。
1、Windows下安装
下载后ip并解压后,⾥⾯有setup.py⽂件,使⽤命令setup.py --help可查看详细使⽤。
你可以使⽤命令python setup.py install命令安装,也可以直接将压缩包内的pyDes.py拷贝到本地的python lib库下直接开始使⽤2、使⽤
使⽤参数如下(拷贝⾃上述提供的地址):
Class initialization -------------------- pyDes.des(key, [mode], [IV], [pad], [padmode]) iple_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 encryption type, can be either    pyDes.ECB (Electronic Code Book) or pyDes.CBC (Cypher Block Chaining) IV      -> Optional Initial Value bytes, must be supplied if using CBC mode.    Length must be 8 bytes. pad    -> Optional argument, set the p
ad character (PAD_NORMAL) to use during    all encrypt/decrpt operations done with this instance. padmode -> Optional argument, set the padding mode (PAD_NORMAL or PAD_PKCS5)    to use during all encrypt/decrpt operations done with this instance. I recommend to use PAD_PKCS5 padding, as then you never need to worry about any padding issues, as the padding can be removed unambiguously upon decrypting data that was encrypted using PAD_PKCS5 padmode.
Common methods -------------- encrypt(data, [pad], [padmode]) decrypt(data, [pad], [padmode]) data    -> Bytes to be encrypted/decrypted pad    -> Optional argument. Only when using padmode 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 Example:
from pyDes import *
# For Python3, you'll need to use bytes, i.e.:
#  data = b"Please encrypt my data"
#  k = des(b"DESCRYPT", CBC, b"\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
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) == dat
以下是本⼈使⽤的例⼦,使⽤CBC加密的⽅式:
import base64
from pyDes import *
Des_Key = "BHC#@*UM" # Key
Des_IV = " 22 33 35 81 BC 38 5A E7" # ⾃定IV向量
def DesEncrypt(str):
k = des(Des_Key, CBC, Des_IV, pad=None, padmode=PAD_PKCS5)
EncryptStr = k.encrypt(str)
return base64.b64encode(EncryptStr) #转base64编码返回
python怎么读取dat文件PS:关于加密解密感兴趣的朋友还可以参考本站在线⼯具:
更多关于Python相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》
希望本⽂所述对⼤家Python程序设计有所帮助。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。