This article mainly introduces the Python encryption module md5, sha, and crypt instances. This article provides the MD5 and crypt module code examples, for more information, see the MD5 (Message-Digest Algorithm 5) module to calculate information ciphertext (Information Digest) and obtain a 128-bit ciphertext. The sha module is similar to md5, but generates a 160-bit signature. The usage is the same.
The following example uses md5:
The code is as follows:
#/Usr/bin/python
#-*-Coding: UTF-8 -*-
Import base64
Try:
Import hashlib
Hash = hashlib. md5 ()
Failed T ImportError:
# For Python </2.5
Import md5
Hash = md5.new ()
Hash. update ('spam, spam, and egges ')
Value = hash. digest ()
Print repr (value) # returns a binary string.
Print hash. hexdigest () # obtain a hexadecimal value.
Print base64.encodestring (value) # obtain the base64 value.
The code is as follows:
#/Usr/bin/python
#-*-Coding: UTF-8 -*-
# Verification of client-to-server communication information
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 ()
Failed T 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"
The crypt module (only used for Unix) implements one-way DES encryption. Unix systems use this encryption algorithm to store passwords. this module is actually only useful when checking such passwords.
The following example shows how to use crypt. crypt is used to encrypt a password, combine the password and salt, and then pass it to the function. the salt here contains two random characters. now you can discard the original password and only save the encrypted string.
The code is as follows:
#/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 ('banas', salt)
PS: This site also provides the following encryption tools for your reference:
MD5 online encryption tool:Http://tools.jb51.net/password/CreateMD5Password
Escape encryption/decryption tool:Http://tools.jb51.net/password/escapepwd
Online SHA1 encryption tool:Http://tools.jb51.net/password/sha1encode
Short chain (short URL) online generation tool:Http://tools.jb51.net/password/dwzcreate
Short chain online restoration tool:Http://tools.jb51.net/password/unshorturl
High-strength password generator:Http://tools.jb51.net/password/CreateStrongPassword