Python's cryptographic modules md5 sha crypt use instances

  • 2020-04-02 14:10:13
  • OfStack

The MD5(message-digest Algorithm 5) module is used to calculate the 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:


# /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)   # You get a binary string
print hash.hexdigest()  # You get a hexadecimal value
print base64.encodestring(value) # get base64 The value of the


# /usr/bin/python
# -*- coding:utf-8 -*-
# Validation of information communicated between client and server 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"

The crypt module (unix-only) implements one-way DES encryption, which Unix systems use to store passwords, and is really only useful for checking such passwords.

The following example shows how to use crypt. Crypt to encrypt a password, combine the password with a salt and pass it to the function, where the salt contains two random characters.


# /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: about encryption technology, this site also provides the following encryption tools for your reference:

MD5 online encryption tool: (link: http://tools.jb51.net/password/CreateMD5Password)

Escape encryption/decryption tool: (link: http://tools.jb51.net/password/escapepwd)

Online SHA1 encryption tool: (link: http://tools.jb51.net/password/sha1encode)

Short chain (short url) online generation tool: (link: http://tools.jb51.net/password/dwzcreate)

Short chain (short url) online restore tool: (link: http://tools.jb51.net/password/unshorturl)

High-strength password generator: (link: http://tools.jb51.net/password/CreateStrongPassword)


Related articles: