python数据加密程序设计_python 数据清洗

python数据加密程序设计_python 数据清洗在 Python 中 加密数据可以通过多种方法实现 以下是几种常见的方法 对称加密 对称加密使用相同的密钥进行加密和解密 常用的对称加密算法包括 AES 和 DES 使用 cryptography 库进行 AES 加密 pythonfrom cryptography hazmat primitives ciphers import Cipher algorithms modesfrom

在Python中,加密数据可以通过多种方法实现,以下是几种常见的方法:

对称加密

对称加密使用相同的密钥进行加密和解密。常用的对称加密算法包括AES和DES。

使用`cryptography`库进行AES加密:

python

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from cryptography.hazmat.backends import default_backend

import os

key = os.urandom(32) 生成一个32字节的随机密钥

iv = os.urandom(16) 生成一个16字节的随机初始化向量

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())

encryptor = cipher.encryptor()

plaintext = b"Hello, World!"

ciphertext = encryptor.update(plaintext) + encryptor.finalize()

decryptor = cipher.decryptor()

decrypted_text = decryptor.update(ciphertext) + decryptor.finalize()

print(decrypted_text.decode()) 输出:Hello, World!

非对称加密

非对称加密使用一对密钥,包括公钥和私钥,公钥用于加密,私钥用于解密。常见的非对称加密算法包括RSA和DSA。

使用`cryptography`库进行RSA加密:

python

from cryptography.hazmat.primitives import serialization

from cryptography.hazmat.primitives.asymmetric import rsa, padding

private_key = rsa.generate_private_key(

public_exponent=65537,

key_size=2048,

backend=default_backend()

public_key = private_key.public_key()

data = b"Hello, World!"

encrypted_data = public_key.encrypt(

data,

padding.OAEP(

mgf=padding.MGF1(algorithm=hashes.SHA256()),

algorithm=hashes.SHA256(),

label=None

print(encrypted_data)

decrypted_data = private_key.decrypt(

encrypted_data,

padding.OAEP(

mgf=padding.MGF1(algorithm=hashes.SHA256()),

algorithm=hashes.SHA256(),

label=None

print(decrypted_data.decode()) 输出:Hello, World!

哈希加密

哈希加密是一种单向加密方法,将数据转换为固定长度的字符串,主要用于验证数据的完整性。

使用`hashlib`库进行SHA256哈希:

python

import hashlib

data = "Hello, World!"

hash_object = hashlib.sha256(data.encode())

encrypted_data = hash_object.hexdigest()

print(encrypted_data) 输出:加密后的哈希值

文件加密

Python也可以用来加密文件。以下是一个使用`cryptography`库对文件进行AES加密的例子:

python

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from cryptography.hazmat.backends import default_backend

import os

key = os.urandom(32) 生成一个32字节的随机密钥

iv = os.urandom(16) 生成一个16字节的随机初始化向量

cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())

encryptor = cipher.encryptor()

with open("plaintext.txt", "rb") as f:

data = f.read()

ciphertext = encryptor.update(data) + encryptor.finalize()

with open("ciphertext.bin", "wb") as f:

f.write(ciphertext)

选择合适的加密算法和模式对于确保数据的安全性至关重要。以上示例展示了如何使用Python的`cryptography`库进行AES加密和解密操作。

编程小号
上一篇 2026-05-19 13:43
下一篇 2026-05-19 13:39

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/39041.html