您当前的位置: 首页 >  Python

庄小焱

暂无认证

  • 3浏览

    0关注

    805博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python——hashlib模块(MD5校验)

庄小焱 发布时间:2021-09-26 00:09:29 ,浏览量:3

摘要

主要是在python中使用MD5对下载后的文件是否完整进行校验。

hashlib的基本概念

hash是一种算法,不同hash算法只是复杂度不一样。在python 3.x里代替了md5模块和sha模块,同时的算法在hashlib包中,其中该包主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法),该算法接受传入的内容,经过运算得到一串hash码。一样的文件或者是数据经过的相同的hash算法,最后的得到的值必然相同。

hash算法的作用

1 文件下载一致性的校验

2 用户密码进行加密

  • 1只要传入的内容一样,得到的hash值必然一样,主要要用明文传输密码文件完整性校验。
  • 2不能由hash值返解成内容,主要作用是把密码做成hash值,不应该在网络传输明文密码(只能有内容返回hash值)
  • 3 只要使用的hash算法不变,无论校验的内容有多大,得到的hash值长度是固定的(如从网上下载文件要进行hash校验,保证网络传输没有丢包)
如何产生hash值之三个阶段
#1创建一个hash对象
hash = hashlib.sha256('898oaFs09f'.encode('utf8')) 

#2对信息进行算法运算
String content='alvin'
hash.update(content.encode('utf8'))
                  
#获取hash结果
print(hash.hexdigest())  
# e79e68f070cdedcfe63eaf1a2e92c83b4cfb1b5c6bc452d214c1b7e77cdfd1c7
利用Hash算法校验文件一致性

(如何保证下载的文件过程中不丢包,保证下载数据的完整性)

#! /usr/bin/python3

# Copyright message
# Copyright message

import hashlib
import logging
import os
import sys
from optparse import OptionParser

sys.path.append('/usr/lib/python3.6/site-packages')
# Due to this script will be copied to /tmp and execute, this is a workaround for it
sys.path.append('/usr/lib/vmware-marvin/marvind/webapps/ROOT/WEB-INF/classes/scripts')

handler = logging.StreamHandler()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)


def file_md5(path):
    logger.info('calculate file loacalpth {0}'.format(path))
    try:
        file_md5 = hashlib.md5()
        size = os.path.getsize(path)
        with open(path, mode='rb') as f:
            while size > 0:
                if size > 1024:
                    read_size = 1024
                else:
                    read_size = size
                file_md5.update(f.read(read_size))
                size -= read_size
        print(file_md5.hexdigest())
        logger.info('calculate file md value is {0}'.format(file_md5.hexdigest()))
    except:
        logger.info('calculate loacalpth file md value fail')
        sys.exit(1)
    sys.exit(0)


def run(options):
    return file_md5(options.localFilePath)


def create_option_parser():
    parser = OptionParser()
    parser.add_option('-p', '--localFilePath', dest='localFilePath', action='store', help='check localFile md5 value ')
    return parser


def main():
    parser = create_option_parser()
    options, args = parser.parse_args()
    if (not options.localFilePath):
        parser.print_help()
        logger.info("arguments localFilePath is invalid")
        sys.exit(-1)
    else:
        run(options)


if __name__ == '__main__':
    main()
对明文密码进行加密
应用:对明文密码进行加密(暴力破解-------用明文密码用一种算法算出一个hash值,与截取的hash值进行比对,比对成功说明明文密码一致,就可以破解用户的密码)
import hashlib

password=input('Xhajfhfaliqwr258daa').strip()

hash=hashlib.md5()

hash.update(password.encode('utf-8'))

print(hash.hexdigest())

#00dcbdaede875d5e23f1f9f64c7849ef

import hashlib

# 对密码进行加盐(暗号)----------进一步加强密码的安全性
password=input('JIaadaigfa58963!fda').strip()

hash=hashlib.md5()

hash.update('一行白鹭上青天'.encode('utf-8'))#对密码加盐

hash.update(password.encode('utf-8'))

print(m.hexdigest())
破解用户注册的密码
'''模拟撞库破解密码'''
import hashlib

passwds=[                      #可以通过random实现对passwds中的内容
    'alex3714',
    'alex1313',
    'alex94139413',
    'alex123456',
    '123456alex',
    'a123lex',
    ]

def make_passwd_dic(passwds):                      #通过明文密码列表,造出与之对应的hash值得字典
    dic={}
    for passwd in passwds:
        m=hashlib.md5()                            #使用md5算法,造了一个工厂
        m.update(passwd.encode('utf-8'))           #给工厂运送原材料(即我们要加密的内容)
        dic[passwd]=m.hexdigest()                  #产出hash值(即最终的产品),将其加入到我们事先造好的空字典中,字典形式:{密码:hash值}
    return dic

def break_code(cryptograph,passwd_dic):            #判断拦截的hash值是否与字典中事先造好的hash值相等,相等则说明成功进行破解
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print('密码是===>\033[46m%s\033[0m' %k)

cryptograph='aee949757a2e698417463d47acac93df'     #我们拦截拿到的密码,经过加密的hash值
break_code(cryptograph,make_passwd_dic(passwds))   #将要破解的密码hash值,和事先造好的hash的字典当做函数的实参传给对应的形参
hmac模块的加密方式,与hashlib类似
'''
    python 还有一个 hmac 模块,
    它内部对我们创建key和内容进行进一步的处理然后再加密:
'''

import hmac
h = hmac.new('天王盖地虎'.encode('utf8'))      #hmac必须要加盐
h.update('hello'.encode('utf8'))
print(h.hexdigest())                          #1abaae8f65f68f2695a8545c5bc8e738

#要想保证hmac最终结果一致,必须保证:
#1:hmac.new括号内指定的初始key一样
#2:无论update多少次,校验的内容累加到一起是一样的内容

# 下面单重方式得到的结果是一样的
import hmac
h1=hmac.new(b'tom')                           #初始值必须保证一致,最终得到的结果就会不一样
h1.update(b'hello')
h1.update(b'world')
print(h1.hexdigest())

h2=hmac.new(b'tom')                           #初始值必须保证一致,最终得到的结果就会不一样
h2.update(b'helloworld')
print(h2.hexdigest())

h3=hmac.new(b'tomhelloworld')                 #初始值不一样,所以与上面两种的结果不一样
print(h3.hexdigest())

'''
0426ccec3b134e8c18fdcefee841ef25
0426ccec3b134e8c18fdcefee841ef25
ff1214d895bbaf5f1847db4ebae8212e
'''
博文参考

Python值hashlib详解 - 迎风而来 - 博客园

关注
打赏
1657692713
查看更多评论
立即登录/注册

微信扫码登录

0.0382s