亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【2023年】第65天 python中的加密工具

標簽:
Python

一、hashlib包介绍

1. hashlib常用的加密方法

函数名 参数 介绍 举例 返回值
md5 byte Md5算法加密 hashlib.md5(b’ hello’) Hash对象
sha1 byte Sha1算法加密 hashlib.sha1(b’ hello’) Hash对象
sha256 byte Sha256算法加密 hashlib.sha256(b’ hello’) Hash 对象
sha512 byte Sha512算法加密 hashlib.sha512(b’ hello’) Hash 对象

以上列表中的方法,从上到下加密后,可以破解的概率越小,破解的难度越高。

2.例子

import hashlib
import time

base_sign = 'Jg'


def custom():
    # python的时间戳是一个浮点类型的
    a_timestamp = int(time.time())
    _token = '%s%s' % (base_sign, a_timestamp)

    hashobj = hashlib.sha1(_token.encode('utf-8'))
    a_token = hashobj.hexdigest()
    return a_token, a_timestamp


def b_service_check(token, timestamp):
    _token = '%s%s' % (base_sign, timestamp)
    b_token = hashlib.sha1(_token.encode('utf-8')).hexdigest()
    if token == b_token:
        return True
    else:
        return False


if __name__ == '__main__':
    need_help_token, timestamp = custom()
    time.sleep(1)
    result = b_service_check(need_help_token, int(time.time()))

    if result == True:
        print('a合法,b服务可以进行帮助')
    else:
        print('a不合法,b不可进行帮助')

3. base64包的常用方法

函数名 参数 介绍 举例 返回值
encodestring byte 进行base64加密 base64.encodestring(b’py’) byte
decodestring byte 对base64解密 base64.decodestring(b’eGlhb211\n’) byte
encodebytes byte 进行base64加密 base64.encodebytes(b’py’) byte
decodebytes byte 对base64解密 base64.decodebytes(b’eGlhb211\n’ byte

4.例子

import base64

replace_one = '%'
replace_two = '$'


def encode(data):
    if isinstance(data, str):
        data = data.encode('utf-8')
    elif isinstance(data, bytes):
        data = data
    else:
        raise TypeError('data need bytes or str')

    _data = base64.encodebytes(data).decode('utf-8')
    _data = _data.replace('a', replace_one).replace('=', replace_two)
    return _data


def decode(data):
    if not isinstance(data, bytes):
        raise TypeError('data need bytes')

    replace_one_b = replace_one.encode('utf-8')
    replace_two_b = replace_two.encode('utf-8')
    data = data.replace(replace_one_b, b'a').replace(replace_two_b, b'=')
    return base64.decodebytes(data).decode('utf-8')


if __name__ == '__main__':
    result = encode('hello xu')
    print(result)
    new_result = decode(result.encode('utf-8'))
    print(new_result)
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消