zoukankan      html  css  js  c++  java
  • Python3模块-random、hashlib和base64

    random模块

    random.random()用于生成一个浮点数x,范围为0 =< x < 1  

    import random
    >>>print(random.random())
    1.864001829819306

    random.uniform(a,b)用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。

    import random
    
    >>>print(random.uniform(1,10))
    7.559074479037658
    #其上限与下限参数位置可以改变,但生成的数值还是在范围之内
    >>>print(random.uniform(10,1))
    5.487835445265534

    random.randint(a,b),用于生成一个范围内的整数,其中a必须大于等于b。

    *
    print(random.randint(1,5))
    3
    print(random.randint(5,1)
    #引发一个ValueError

    random.randrange([start],stop[,step])从一个集合中随机取出一个数字

    import random
    
    >>>print(random.randrange(1,100))
    22
    >>>print(random.randrange(1,100,2))  #偶数集合在这里等效于random.choice(range(1,100,2))
    16

    random.choice(seq), seq是一个非空序列,如list、tuple、字符串等。如果为空,引发IndexError

    import random
    
    >>>print(random.choice('abcdefg'))
    c
    >>>print(random.choice('tom','jerry','lisa'))
    tom
    >>>print(random.choice(('a','b','c')))
    c

    random.shuffle(x[,random]),将一个list打乱重新组合,list还是原list,没有占用空间。

    import random
    
    >>>alist = [1,2,3,4,5]
    >>>random.shuffle(alist)
    >>>print(alist)
    [2, 5, 4, 3, 1]

    random.sample(seq,k),从指定序列中随机获取指定长度的片段

    import random
    
    a = [1,2,3,4,5]
    >>>print(random,sample(a,3))
    [3,1,5]

    random更多方法参见官方docs:random module

     

    hashlib模块

     这个模块实现了一个通用的接口来实现多个不同的安全哈希和消息摘要算法。包括FIPS安全散列算法SHA1,SHA224,SHA256,SHA384和SHA512(在FIPS 180-2中定义)以及RSA的MD5算法

    因为哈希在字节上工作,而不是字符,所以要使哈希工作在字符上,需要encode编码为utf-8,再以十六进制形式进行摘要计算

    import hashlib
    
    str = 'mzc19971103'
    md5 = hashlib.md5()
    md5.update(str[0:5].encode('utf-8'))
    md5.update(str[5:].encode('utf-8'))
    print(md5.hexdigest())
    
    sha1 = hashlib.sha1()
    sha1.update('mzc19971103'.encode('utf-8'))
    print(sha1.hexdigest())

    处理字符串时还可以加盐,只要加盐字符串不被泄露,无法根据md5解析出字符串

    import hashlib
    
    def calc_md5(password):
        md5 = hashlib.md5()
        md5.update(password.encode('utf-8'))
        a = md5.hexdigest()
        return a
    
    db = {}
    
    def writeindb(username, password):
        db[username] = calc_md5(password+'woaini1997')  #加盐
        print(db)
    def login(username, password):
        p = calc_md5(password+'woaini1997')
        if username in db and db[username] == p:
            print('login succ')
        else:
            print('username or passwd error')
    
    def register():
        username = input('input ur username:')
        password = input('input ur password:')
        if username in db:
            print('account exit!')
        else:
            writeindb(username, password)
    def logininput():
        username = input('plz input ur account:')
        password = input('plz input ur password:')
        if username != "" and password != "":
            login(username, password)
        else:
            print('uname or passwd not empty!')
    
    if __name__ == '__main__':
        while True:
            # username = input('plz input ur username:
    ')
            # password = input('plz input ur password:
    ')
            selec =input('register select:1  login select:2   quit plz select:3
    ')
            if selec == '1':
                register()
            elif selec == '2':
                logininput()
            elif selec == '3':
                break

     hashlib更多用法参见:Python-hashlib

     

     

     

    base64

    此模块提供将二进制数据编码为可打印ASCII字符并将此类编码解码回二进制数据的功能。它为在 RFC 3548中指定的编码提供编码和解码功能,该编码定义了Base16,Base32和Base64算法,以及事实上的标准Ascii85和Base85编码.

    base64可以直接编码

    import base64
    
    def safe_base64_encode(a): #base64编码函数
        s = base64.b64encode(a)
        print(s)
    
    safe_base64_encode(b'legend')
    #打印结果: b
    'bGVnZW5k'

    解码:

    import base64
    
    def safe_base64_decode(a):
        s = base64.b64decode(a)print(a)
    
    safe_base64_decode(b'bGVnZW5k')
    
    #打印结果:
    b'legend'

    base64.b64encode()和base64.b64decode()参数必须是类字节对象

     

    由于标准的Base64编码后可能出现字符+/,在URL中就不能直接作为参数,所以又有一种"url safe"的base64编码,其实就是把字符+/分别变成-_

    >>> base64.b64encode(b'ixb7x1dxfbxefxff')
    b'abcd++//'
    >>> base64.urlsafe_b64encode(b'ixb7x1dxfbxefxff')
    b'abcd--__'
    >>> base64.urlsafe_b64decode('abcd--__')
    b'ixb7x1dxfbxefxff'

    Base64编码原理与应用

  • 相关阅读:
    少用 if 进行普通意义上的参数验证
    到底差在了什么地方:Cs>MUTEX>Monitor>WaitHandle
    SQL Server 中的事务和锁(三)Range SU,XX 以及死锁
    练习:自己动手实现一个轻量级的信号量(二)
    让人崩溃的一上午
    我所犯的几个愚蠢错误(一)
    一个系列 之二
    练习:自己动手实现一个轻量级的信号量(一)
    Delphi的DirectShow开发概述
    xvid的中文简介
  • 原文地址:https://www.cnblogs.com/mzc1997/p/7756829.html
Copyright © 2011-2022 走看看