Python的加密模塊md5、sha、crypt使用實例
MD5(Message-Digest Algorithm 5) 模塊用于計算信息密文(信息摘要),得出一個128位的密文。sha模塊跟md5相似,但生成的是160位的簽名。使用方法是相同的。
如下實例是使用md5的:
# /usr/bin/python
# -*- coding:utf-8 -*-
import base64
try:
import hashlib
hash = hashlib.md5()
except ImportError:
# for Python << 2.5
import md5
hash = md5.new()
hash.update('spam,spam,and egges')
value = hash.digest()
print repr(value) #得到的是二進制的字符串
print hash.hexdigest() #得到的是一個十六進制的值
print base64.encodestring(value) #得到base64的值
# /usr/bin/python
# -*- coding:utf-8 -*-
# 客戶端與服務(wù)器端通信的信息的驗證
import string
import random
def getchallenge():
challenge = map(lambda i: chr(random.randint(0,255)),range(16))
return string.join(challenge,"")
def getresponse(password,challenge):
try:
import hashlib
hash = hashlib.md5()
except ImportError:
# for Python << 2.5
import md5
hash = md5.new()
hash.update(password)
hash.update(challenge)
return hash.digest()
print "client: ","connect"
challenge= getchallenge()
print "server: ",repr(challenge)
client_response = getresponse("trustno1",challenge)
print "client: ",repr(client_response)
server_response = getresponse("trustno1",challenge)
if client_response == server_response:
print "server:","login ok"
crypt 模塊(只用于 Unix)實現(xiàn)了單向的 DES 加密, Unix 系統(tǒng)使用這個加密算法來儲存密碼, 這個模塊真正也就只在檢查這樣的密碼時有用。
如下實例,展示了如何使用 crypt.crypt 來加密一個密碼, 將密碼和 salt組合起來然后傳遞給函數(shù), 這里的 salt 包含兩位隨機字符.現(xiàn)在你可以扔掉原密碼而只保存加密后的字符串了。
# /usr/bin/python
# -*- coding:utf-8 -*-
import crypt
import random,string
def getsalt(chars = string.letters+string.digits):
return random.choice(chars)+random.choice(chars)
salt = getsalt()
print salt
print crypt.crypt('bananas',salt)
PS:關(guān)于加密技術(shù),本站還提供了如下加密工具供大家參考使用:
MD5在線加密工具:http://tools.jb51.net/password/CreateMD5Password
Escape加密/解密工具:http://tools.jb51.net/password/escapepwd
在線SHA1加密工具:http://tools.jb51.net/password/sha1encode
短鏈(短網(wǎng)址)在線生成工具:http://tools.jb51.net/password/dwzcreate
短鏈(短網(wǎng)址)在線還原工具:http://tools.jb51.net/password/unshorturl
高強度密碼生成器:http://tools.jb51.net/password/CreateStrongPassword
相關(guān)文章
Python使用Pandas處理測試數(shù)據(jù)的方法
Pandas是一個功能極其強大的數(shù)據(jù)分析庫,可以高效地操作各種數(shù)據(jù)集,這篇文章主要介紹了Python自動化測試-使用Pandas來高效處理測試數(shù)據(jù),需要的朋友可以參考下2023-02-02Python入門之三角函數(shù)atan2()函數(shù)詳解
這篇文章主要介紹了Python入門之三角函數(shù)atan2()函數(shù)詳解,分享了其實例,具有一定參考價值,需要的朋友可以了解下。2017-11-11