欢迎访问宙启技术站
智能推送

python中的加密解密函数 - 包括加密、解密、哈希等操作

发布时间:2023-06-29 06:43:44

在Python中,有许多加密解密函数和库可供使用。以下是一些常用的加密解密函数和库的简介和用法。

1. hashlib

hashlib是Python中用于提供各种哈希函数的库。它包括了许多常用的哈希算法,如MD5、SHA1、SHA256等。使用该库可以很方便地对数据进行哈希运算。

示例代码:

import hashlib

# 使用MD5进行哈希运算
hash_object = hashlib.md5(b'Hello World')
hash_result = hash_object.hexdigest()
print(hash_result)

# 使用SHA256进行哈希运算
hash_object = hashlib.sha256(b'Hello World')
hash_result = hash_object.hexdigest()
print(hash_result)

2. base64

base64是一种用64个可打印字符来表示二进制数据的方法。Python的base64模块提供了base64编码和解码的函数,可以对数据进行简单的加密和解密。

示例代码:

import base64

# 对字符串进行base64编码
encoded_string = base64.b64encode(b'Hello World')
print(encoded_string)

# 对base64编码的字符串进行解码
decoded_string = base64.b64decode(encoded_string)
print(decoded_string)

3. cryptography

cryptography是Python中一个功能强大的密码学库,提供了许多加密解密算法和功能,如AES、RSA、HMAC等。

示例代码(使用AES进行加密解密):

from cryptography.fernet import Fernet

# 生成一个密钥
key = Fernet.generate_key()

# 创建一个Fernet对象
cipher_suite = Fernet(key)

# 加密数据
cipher_text = cipher_suite.encrypt(b'Hello World')
print(cipher_text)

# 解密数据
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text)

4. pyDes

pyDes是一个纯Python实现的DES加密算法库。它提供了DES加密和解密的功能。

示例代码:

from pyDes import des, PAD_PKCS5

# 创建一个DES对象
des_cipher = des(b'12345678', PAD_PKCS5)

# 加密数据
cipher_text = des_cipher.encrypt(b'Hello World')
print(cipher_text)

# 解密数据
plain_text = des_cipher.decrypt(cipher_text)
print(plain_text)

5. PyCryptoDome

PyCryptoDome是Python中一个强大的加密解密库,提供了许多密码学算法,如AES、RSA、DES等。

示例代码(使用AES进行加密解密):

from Crypto.Cipher import AES

# 创建一个AES对象
key = b'1234567890123456'
cipher = AES.new(key, AES.MODE_ECB)

# 加密数据
cipher_text = cipher.encrypt(b'Hello World')
print(cipher_text)

# 解密数据
plain_text = cipher.decrypt(cipher_text)
print(plain_text)

以上是Python中一些常用的加密解密函数和库的简介和用法。根据具体需求选择合适的库和算法进行加密解密操作。