天天看點

python 加密解密子產品_python子產品介紹- pyDes DES加密解密

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