跳至页脚内容
PYTHON 帮助

hashlib Python(如何运作:开发人员指南)

Python中的hashlib模块是用于处理安全哈希和消息摘要算法的强大工具。 该模块为众多安全哈希算法提供了标准接口,使其成为需要确保数据完整性和安全性的开发人员的多功能选择。 Later in the article, we will also look into a versatile PDF generation Library from IronSoftware called IronPDF and write a script using both libraries to demonstrate their usage.

hashlib模块是Python标准库的一部分,因此无需单独安装。 它包括各种加密哈希函数,如MD5、SHA-1、SHA-224、SHA-256、SHA-384、SHA-512以及SHA-3系列。 这些函数用于创建哈希对象,随后可以用于生成数据的哈希值。

主要功能

  1. 广泛的算法支持hashlib支持多种哈希算法,包括较旧的MD5和SHA-1以及更现代的SHA-256和SHA-3。
  2. 简单的接口:每个哈希算法都有一个构造方法,可以返回哈希对象。 该对象可以使用update方法输入数据,并使用digest或hexdigest方法生成哈希值。
  3. 安全性:虽然某些算法如MD5和SHA-1存在已知漏洞,hashlib包含更安全的选项,如SHA-256和SHA-3。

安装

hashlib是一个内置模块,不需要显式安装。

基本用法

这是一个简单例子,展示了如何使用hashlib通过哈希构造器生成SHA-256哈希:

import hashlib

# Creating hash objects with SHA-256
hash_object = hashlib.sha256()
# Update the hash object with data
hash_object.update(b'IronPDF from Iron Software is Awesome')
# Get the hexadecimal representation of the hash
hash_hex = hash_object.hexdigest()  # hash_hex is the hexadecimal digest
print(hash_hex)  # Output the hash
# Output: 6fc0c7d6af8eb51f0cd89281db55c6a6b76b5310226fa5af2272a8eb42cc1bfe
import hashlib

# Creating hash objects with SHA-256
hash_object = hashlib.sha256()
# Update the hash object with data
hash_object.update(b'IronPDF from Iron Software is Awesome')
# Get the hexadecimal representation of the hash
hash_hex = hash_object.hexdigest()  # hash_hex is the hexadecimal digest
print(hash_hex)  # Output the hash
# Output: 6fc0c7d6af8eb51f0cd89281db55c6a6b76b5310226fa5af2272a8eb42cc1bfe
PYTHON

高级功能

  • 多线程支持:与加密哈希函数一起,如果一次提供超过2047字节的数据,hashlib会在计算哈希时释放全局解释器锁(GIL),从而提高多线程应用的性能。
  • 自定义哈希算法:如果你的Python发行版的hashlib链接到提供其他算法的OpenSSL构建,可以通过new()方法访问这些算法。

使用HashLib模块的各种哈希类型

1. 简单哈希

import hashlib

# Simple hashing example
data = b'Hello, World!'
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print("SHA-256 Hash:", hex_dig)
# Output: SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
import hashlib

# Simple hashing example
data = b'Hello, World!'
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print("SHA-256 Hash:", hex_dig)
# Output: SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
PYTHON

此代码为输入数据生成SHA-256哈希。

2. 使用不同的摘要大小

import hashlib

# Hashing with different digest sizes
data = b'Hello, World!'

# MD5, SHA-256, and SHA-512 hash generation
hash_md5 = hashlib.md5(data).hexdigest()
hash_sha256 = hashlib.sha256(data).hexdigest()
hash_sha512 = hashlib.sha512(data).hexdigest()

# Print each hash
print("MD5 Hash (hex):", hash_md5)
print("SHA-256 Hash (hex):", hash_sha256)
print("SHA-512 Hash (hex):", hash_sha512)
# Output:
# MD5 Hash (hex): 65a8e27d8879283831b664bd8b7f0ad4
# SHA-256 Hash (hex): dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
# SHA-512 Hash (hex): 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387
import hashlib

# Hashing with different digest sizes
data = b'Hello, World!'

# MD5, SHA-256, and SHA-512 hash generation
hash_md5 = hashlib.md5(data).hexdigest()
hash_sha256 = hashlib.sha256(data).hexdigest()
hash_sha512 = hashlib.sha512(data).hexdigest()

# Print each hash
print("MD5 Hash (hex):", hash_md5)
print("SHA-256 Hash (hex):", hash_sha256)
print("SHA-512 Hash (hex):", hash_sha512)
# Output:
# MD5 Hash (hex): 65a8e27d8879283831b664bd8b7f0ad4
# SHA-256 Hash (hex): dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
# SHA-512 Hash (hex): 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6cc69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387
PYTHON

此代码使用提供的数据生成MD5、SHA-256和SHA-512的哈希。

3. 带键哈希

import hashlib
from hashlib import blake2b

# Keyed hashing example
h = blake2b(key=b'pseudorandom key', digest_size=16)
h.update(b'message data')
print(h.hexdigest())
# Output: 3d363ff7401e02026f4a4687d4863ced
import hashlib
from hashlib import blake2b

# Keyed hashing example
h = blake2b(key=b'pseudorandom key', digest_size=16)
h.update(b'message data')
print(h.hexdigest())
# Output: 3d363ff7401e02026f4a4687d4863ced
PYTHON

此代码演示如何使用Blake2b算法创建带键哈希。

4. 随机哈希

import hashlib
import os

# Randomized hashing example using PBKDF2-HMAC
data = b'Hello, World!'
salt = os.urandom(16)  # Generate a random salt
hash_object = hashlib.pbkdf2_hmac('sha256', data, salt, 100000)
hex_dig = hash_object.hex()
print("Randomized Hash (SHA-256):", hex_dig)
# Output: Randomized Hash (SHA-256): a2a3c1a30a2add1867d55eac97fd9c84dc679691c0f15ae09c01e1bcc63ba47a
import hashlib
import os

# Randomized hashing example using PBKDF2-HMAC
data = b'Hello, World!'
salt = os.urandom(16)  # Generate a random salt
hash_object = hashlib.pbkdf2_hmac('sha256', data, salt, 100000)
hex_dig = hash_object.hex()
print("Randomized Hash (SHA-256):", hex_dig)
# Output: Randomized Hash (SHA-256): a2a3c1a30a2add1867d55eac97fd9c84dc679691c0f15ae09c01e1bcc63ba47a
PYTHON

这些示例涵盖了使用不同摘要大小的基本哈希。 可以根据具体需求或偏好进行调整,比如使用不同的算法或参数。

实用应用

  1. 数据完整性:哈希函数通常用于确认记录的完整性。 通过比较原始数据的哈希与接收到的数据的哈希,可以确保数据未被更改。
  2. 密码存储:哈希函数常用于安全存储密码。 系统存储密码的哈希而不是实际的密码。 当用户登录时,输入密码的哈希与存储的哈希进行比较。
  3. 数字签名:哈希函数通常用于创建数字签名,以验证消息的真实性和完整性。

IronPDF 简介

hashlib Python ((如何工作:开发者指南)):图1 - IronPDF for Python:Python PDF库

IronPDF 是一个强大的Python库,用于使用HTML、CSS、图像和JavaScript创建、编辑和签署PDF。 它提供高性能的能力,内存使用最小。 Users can generate PDFs from HTML, merge or split PDF documents, extract text and images from PDFs, apply watermarks, rasterize a PDF to image formats like JPEG and PNG, encrypt PDF files, and more. IronPDF提供多种PDF操作。

IronPDF的关键特性

HTML 至 PDF 转换

用户可以将HTML文件、HTML字符串和URL转换为PDF。 例如,使用IronPDF的 Chrome PDF 渲染器渲染网页为PDF

跨平台支持

IronPDF为Python 3+版本设计,并在Windows、Mac、Linux或云平台上运行。

IronPDF is also available in .NET, Java, Python, and Node.js.

编辑和签名

The user can set properties, add security with passwords and permissions, and apply digital signatures to PDFs using IronPDF.

页面模板和设置

IronPDF允许您使用页眉、页脚、页码和可调边距自定义PDF文档。 它还支持响应式布局和自定义纸张尺寸。

标准合规性

IronPDF包也符合PDF标准,如PDF/A和PDF/UA。 它支持UTF-8字符编码,处理图像、CSS和字体等资源。

使用IronPDF和HashLib模块生成PDF文档

IronPDF先决条件

  1. IronPDF使用.NET 6.0作为其底层技术。 因此,确保.NET 6.0运行时已安装。
  2. Python 3.0+:您需要安装Python版本3或更高版本。
  3. Pip:安装Python包安装器pip来安装IronPDF包。

首先,让我们创建一个Python文件来添加我们的脚本。在本例中,我们使用Visual Studio Code作为代码编辑器。

打开Visual Studio Code,创建一个文件hashlibDemo.py。

安装IronPDF库:

 pip install ironpdf

然后添加以下代码来演示IronPDF和Hashlib Python包的使用

import hashlib
import os
from hashlib import blake2b
from ironpdf import *

# Apply your license key
License.LicenseKey = "your key"

# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with hashlib</h1>"
content += "<p>Data for all the below examples = IronPDF from Iron Software is Awesome</p>"
content += "<h2> Simple hashing example</h2>"

# Simple hashing example
data = b'IronPDF from Iron Software is Awesome'
content += "<p>hashlib.sha256(data)</p>"
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print("SHA-256 Hash:", hex_dig)
content += "<p>SHA-256 Hash:"+str(hex_dig)+"</p>"

content += "<h2> Hashing with different digest sizes</h2>"
# Hashing with different digest sizes
hash_md5 = hashlib.md5(data).hexdigest()
content += "<p>hashlib.md5(data).hexdigest()</p>"
hash_sha256 = hashlib.sha256(data).hexdigest()
content += "<p>hashlib.sha256(data).hexdigest()</p>"
hash_sha512 = hashlib.sha512(data).hexdigest()
content += "<p>hashlib.sha512(data).hexdigest()</p>"

print("MD5 Hash (hex):", hash_md5)
print("SHA-256 Hash (hex):", hash_sha256)
print("SHA-512 Hash (hex):", hash_sha512)
content += "<p>MD5 Hash (hex):"+str(hash_md5)+"</p>"
content += "<p>SHA-256 Hash (hex):"+str(hash_sha256)+"</p>"
content += "<p>SHA-512 Hash (hex):"+str(hash_sha512)+"</p>"

# Keyed hashing example
content += "<h2> Keyed hashing example</h2>"
h = blake2b(key=b'pseudorandom key', digest_size=16)
content += "<p></p>"
h.update(data)
print(h.hexdigest())
content += "<p>Keyed Hash (hex):"+str(h.hexdigest())+"</p>"

# Randomized hashing example 
content += "<h2> Randomized hashing example </h2>"
salt = os.urandom(16)  # Generate a random salt
hash_object = hashlib.pbkdf2_hmac('sha256', data, salt, 100000)
content += "<p>hashlib.pbkdf2_hmac('sha256', data, salt, 100000)</p>"
hex_dig = hash_object.hex()
print("Randomized Hash (SHA-256):", hex_dig)
content += "<p>Randomized Hash (SHA-256):"+str(hex_dig)+"</p>"

# Generate PDF using IronPDF
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("Demo-hashlib.pdf")
import hashlib
import os
from hashlib import blake2b
from ironpdf import *

# Apply your license key
License.LicenseKey = "your key"

# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with hashlib</h1>"
content += "<p>Data for all the below examples = IronPDF from Iron Software is Awesome</p>"
content += "<h2> Simple hashing example</h2>"

# Simple hashing example
data = b'IronPDF from Iron Software is Awesome'
content += "<p>hashlib.sha256(data)</p>"
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print("SHA-256 Hash:", hex_dig)
content += "<p>SHA-256 Hash:"+str(hex_dig)+"</p>"

content += "<h2> Hashing with different digest sizes</h2>"
# Hashing with different digest sizes
hash_md5 = hashlib.md5(data).hexdigest()
content += "<p>hashlib.md5(data).hexdigest()</p>"
hash_sha256 = hashlib.sha256(data).hexdigest()
content += "<p>hashlib.sha256(data).hexdigest()</p>"
hash_sha512 = hashlib.sha512(data).hexdigest()
content += "<p>hashlib.sha512(data).hexdigest()</p>"

print("MD5 Hash (hex):", hash_md5)
print("SHA-256 Hash (hex):", hash_sha256)
print("SHA-512 Hash (hex):", hash_sha512)
content += "<p>MD5 Hash (hex):"+str(hash_md5)+"</p>"
content += "<p>SHA-256 Hash (hex):"+str(hash_sha256)+"</p>"
content += "<p>SHA-512 Hash (hex):"+str(hash_sha512)+"</p>"

# Keyed hashing example
content += "<h2> Keyed hashing example</h2>"
h = blake2b(key=b'pseudorandom key', digest_size=16)
content += "<p></p>"
h.update(data)
print(h.hexdigest())
content += "<p>Keyed Hash (hex):"+str(h.hexdigest())+"</p>"

# Randomized hashing example 
content += "<h2> Randomized hashing example </h2>"
salt = os.urandom(16)  # Generate a random salt
hash_object = hashlib.pbkdf2_hmac('sha256', data, salt, 100000)
content += "<p>hashlib.pbkdf2_hmac('sha256', data, salt, 100000)</p>"
hex_dig = hash_object.hex()
print("Randomized Hash (SHA-256):", hex_dig)
content += "<p>Randomized Hash (SHA-256):"+str(hex_dig)+"</p>"

# Generate PDF using IronPDF
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("Demo-hashlib.pdf")
PYTHON

代码解释

提提供的代码展示了使用Python的hashlib库的各种哈希技术:

  1. 简单哈希示例:计算特定数据字符串(b'IronPDF from Iron Software is Awesome ')的SHA-256哈希。
  2. 使用不同的摘要大小进行哈希:此部分演示对相同数据字符串使用MD5、SHA-256和SHA-512算法进行哈希。
  3. 带键哈希示例:此示例使用指定的密钥(b'pseudorandom key ')的blake2b哈希函数对数据进行带键哈希。
  4. 随机哈希示例:利用PBKDF2-HMAC算法和SHA-256使用随机生成的盐生成随机哈希。
  5. PDF生成:在演示哈希示例之后,代码使用IronPDF生成一个包含展示哈希示例的HTML内容的PDF文档。

每个示例都展示了加密哈希的不同方面,如标准哈希、带键哈希和随机哈希技术。

输出

hashlib Python ((如何工作:开发者指南)):图2 - 示例控制台输出

PDF

hashlib Python ((如何工作:开发者指南)):图3 - 使用IronPDF的示例PDF输出

IronPDF 许可证

hashlib Python ((如何工作:开发者指南)):图4 - IronPDF许可页面

IronPDF 运行在Python许可证密钥上。 IronPDF for Python提供了一个免费试用许可证密钥,让用户在购买前测试其广泛功能。

在脚本开始之前放置许可证密钥,以便使用IronPDF包

from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
PYTHON

结论

hashlib模块是Python标准库的关键组成部分,为各种应用程序提供强大且安全的哈希函数。 无论您是确保数据完整性、安全存储密码,还是创建数字签名,hashlib都提供所需工具。 另一方面,IronPDF 是一个强大的PDF生成和PDF操作库。 通过这两个库,开发人员可以快速生成哈希并将其存储为PDF格式。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。