python的一些加密方法及python 加密模块

yizhihongxing

Python的一些加密方法及Python加密模块

在Python编程语言中,有多种加密方式和方法可以对数据和信息进行加密,保护信息安全。本文将讲解Python中一些常用的加密方法和加密模块。

常用的加密方法

哈希

哈希是将明文数据转换为一串由数字和字母组成的固定长度的代码,也称为摘要。哈希算法是不可逆的,也就是说,无法从哈希值中还原出原始明文数据。Python中常用的哈希算法模块是hashlib

import hashlib

def md5_encode(s: str) -> str:
    """
    使用MD5哈希算法对字符串s进行加密
    """
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()

if __name__ == '__main__':
    s = "Hello, World!"
    print(f"明文: {s}")
    print(f"MD5加密后: {md5_encode(s)}")

对称加密

对称加密是指使用相同密钥进行加密和解密的加密方式。Python中常用的对称加密模块是cryptography

from cryptography.fernet import Fernet

def encrypt(s: str, key: bytes) -> bytes:
    """
    使用Fernet对称加密算法对字符串s进行加密,key是密钥
    """
    f = Fernet(key)
    return f.encrypt(s.encode('utf-8'))

def decrypt(ciphertext: bytes, key: bytes) -> str:
    """
    使用Fernet对称加密算法对密文进行解密,key是密钥
    """
    f = Fernet(key)
    return f.decrypt(ciphertext).decode('utf-8')

if __name__ == '__main__':
    key = Fernet.generate_key()
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, key)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, key)
    print(f"解密后的明文: {plaintext}")

非对称加密

非对称加密是指使用私钥进行加密,使用公钥进行解密,或者使用公钥进行加密,使用私钥进行解密的加密方式。Python中常用的非对称加密模块是pycryptodome

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def generate_key() -> RSA.RsaKey:
    """
    生成公私钥对
    """
    key = RSA.generate(2048)
    return key

def encrypt(s: str, key: RSA.RsaKey) -> bytes:
    """
    使用公钥key进行RSA非对称加密
    """
    cipher = PKCS1_OAEP.new(key)
    return cipher.encrypt(s.encode('utf-8'))

def decrypt(ciphertext: bytes, key: RSA.RsaKey) -> str:
    """
    使用私钥key进行RSA非对称解密
    """
    cipher = PKCS1_OAEP.new(key)
    return cipher.decrypt(ciphertext).decode('utf-8')

if __name__ == '__main__':
    private_key = generate_key()
    public_key = private_key.publickey()
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, public_key)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, private_key)
    print(f"解密后的明文: {plaintext}")

常用的加密模块

cryptography

cryptography是Python中一个常用的加密模块。它支持多种对称和非对称加密算法,包括AES、Blowfish、RSA和DSA等。cryptography还支持密码学安全伪随机数生成器、密码哈希函数和密码学证书等。使用该模块可以快速实现各种加密需求。

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

def encrypt(s: str, key: bytes, iv: bytes) -> bytes:
    """
    使用AES对称加密算法对字符串s进行加密,key是密钥,iv是初始化向量
    """
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    return encryptor.update(s.encode('utf-8')) + encryptor.finalize()

def decrypt(ciphertext: bytes, key: bytes, iv: bytes) -> str:
    """
    使用AES对称加密算法对密文进行解密,key是密钥,iv是初始化向量
    """
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    return decryptor.update(ciphertext) + decryptor.finalize()

if __name__ == '__main__':
    key = b'0123456789abcdef'
    iv = b'0123456789abcdef'
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, key, iv)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, key, iv)
    print(f"解密后的明文: {plaintext}")

hashlib

hashlib模块是Python中一个常用的哈希算法模块,支持多种哈希算法,如MD5、SHA1、SHA224、SHA256、SHA384和SHA512等。使用该模块可以方便地实现哈希运算。

import hashlib

def sha256_encode(s: str) -> str:
    """
    使用SHA256哈希算法对字符串s进行加密
    """
    m = hashlib.sha256()
    m.update(s.encode('utf-8'))
    return m.hexdigest()

if __name__ == '__main__':
    s = "Hello, World!"
    print(f"明文: {s}")
    print(f"SHA256加密后: {sha256_encode(s)}")

pycryptodome

pycryptodome是Python中一个常用的加密模块。它是Cryptography及PyCrypto项目的继承者,可以支持多种对称和非对称加密算法,包括AES、Blowfish、RSA和DSA等。pycryptodome同样支持密码学安全伪随机数生成器、密码哈希函数和密码学证书等。使用该模块可以快速实现各种加密需求。

from Crypto.Cipher import AES

def encrypt(s: str, key: bytes, iv: bytes) -> bytes:
    """
    使用AES对称加密算法对字符串s进行加密,key是密钥,iv是初始化向量
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_data = s.encode() + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
    ciphertext = cipher.encrypt(padded_data.encode())
    return ciphertext

def decrypt(ciphertext: bytes, key: bytes, iv: bytes) -> str:
    """
    使用AES对称加密算法对密文进行解密,key是密钥,iv是初始化向量
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_data = cipher.decrypt(ciphertext)
    return padded_data.decode().rstrip(chr(AES.block_size - len(padded_data) % AES.block_size))

if __name__ == '__main__':
    key = b'0123456789abcdef'
    iv = b'0123456789abcdef'
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, key, iv)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, key, iv)
    print(f"解密后的明文: {plaintext}")

示例说明

哈希

在示例代码中,我们使用了hashlib模块中的md5()函数对字符串进行哈希运算,返回哈希值的16进制表示形式。

import hashlib

def md5_encode(s: str) -> str:
    """
    使用MD5哈希算法对字符串s进行加密
    """
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()

if __name__ == '__main__':
    s = "Hello, World!"
    print(f"明文: {s}")
    print(f"MD5加密后: {md5_encode(s)}")

非对称加密

在示例代码中,我们使用了pycryptodome模块中的RSAPKCS1_OAEP类实现RSA非对称加密和解密。

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

def generate_key() -> RSA.RsaKey:
    """
    生成公私钥对
    """
    key = RSA.generate(2048)
    return key

def encrypt(s: str, key: RSA.RsaKey) -> bytes:
    """
    使用公钥key进行RSA非对称加密
    """
    cipher = PKCS1_OAEP.new(key)
    return cipher.encrypt(s.encode('utf-8'))

def decrypt(ciphertext: bytes, key: RSA.RsaKey) -> str:
    """
    使用私钥key进行RSA非对称解密
    """
    cipher = PKCS1_OAEP.new(key)
    return cipher.decrypt(ciphertext).decode('utf-8')

if __name__ == '__main__':
    private_key = generate_key()
    public_key = private_key.publickey()
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, public_key)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, private_key)
    print(f"解密后的明文: {plaintext}")

对称加密

在示例代码中,我们使用了cryptography模块中的Fernet类实现AES对称加密和解密。

from cryptography.fernet import Fernet

def encrypt(s: str, key: bytes) -> bytes:
    """
    使用Fernet对称加密算法对字符串s进行加密,key是密钥
    """
    f = Fernet(key)
    return f.encrypt(s.encode('utf-8'))

def decrypt(ciphertext: bytes, key: bytes) -> str:
    """
    使用Fernet对称加密算法对密文进行解密,key是密钥
    """
    f = Fernet(key)
    return f.decrypt(ciphertext).decode('utf-8')

if __name__ == '__main__':
    key = Fernet.generate_key()
    s = "Hello, World!"
    print(f"明文: {s}")
    ciphertext = encrypt(s, key)
    print(f"加密后的密文: {ciphertext}")
    plaintext = decrypt(ciphertext, key)
    print(f"解密后的明文: {plaintext}")

总结

Python中有多种加密方法和模块可以用于对数据和信息进行加密,保护信息安全。在选择使用加密方法和模块时,应根据实际需求和情况选择合适的方法和模块,确保加密效率和安全性,同时注意保护密钥的安全性。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python的一些加密方法及python 加密模块 - Python技术站

(0)
上一篇 2023年5月31日
下一篇 2023年5月31日

相关文章

  • python自动化操作之动态验证码、滑动验证码的降噪和识别

    Python自动化操作之动态验证码、滑动验证码的降噪和识别 什么是动态验证码和滑动验证码? 动态验证码和滑动验证码是常见的防止自动化操作的方式。动态验证码是指,验证码在输入之前会动态地改变,比如验证码的旋转角度、字体颜色等。滑动验证码是指,用户需要将图片中的某一个小块通过拖动的方式移动到正确的位置才能够通过验证。 如何降噪和识别动态验证码和滑动验证码? 1.…

    python 2023年6月6日
    00
  • 用Python逐行分析文件方法

    当需要分析一个大文件时,通常我们无法一次加载到内存中进行处理。而逐行分析文件则可以解决这个问题。在Python中,逐行读取文件有多种方法。本文将着重介绍用Python逐行分析文件的完整攻略。 1. 逐行读取文件 Python的文件对象提供了一个readline()方法,通过它可以逐行读取文件,直到文件末尾。以下是示例: with open(‘file.txt…

    python 2023年6月5日
    00
  • Python调用Windows API函数编写录音机和音乐播放器功能

    Python调用Windows API函数编写录音机和音乐播放器功能 1. 介绍 Python是一门简单易学且功能强大的编程语言,能够编写各种任务的应用程序,包括录音机和音乐播放器。通过调用Windows API函数,Python可以与Windows操作系统进行交互,实现更高级别的功能。 2. 录音机功能实现 录音机功能需要调用Windows API函数来打…

    python 2023年5月23日
    00
  • python实现淘宝秒杀聚划算抢购自动提醒源码

    首先,需要说明的是,自动抢购和自动提醒都是违反淘宝规定的行为,可能会对账号造成风险,请谨慎操作。 该攻略的主要思路是:模拟网页的请求,通过解析网页内容来获取商品信息,再通过自动化操作模拟人类的点击操作,达到抢购或提醒的效果。 具体步骤如下: 1.分析目标网页的结构和请求方式,获取必要的参数。 2.通过Python编写程序,模拟网页的请求获取网页内容。 3.解…

    python 2023年5月19日
    00
  • Python文件和目录操作详解

    下面是对“Python文件和目录操作详解”的完整攻略: Python文件和目录操作详解 一、文件操作 1.1 打开文件 在 Python 中,我们可以使用内置的 open 函数来操作文件。其语法形式为: f = open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=Non…

    python 2023年6月2日
    00
  • 有关Python的22个编程技巧

    有关 Python 的 22 个编程技巧 Python 是一种非常流行的编程语言,拥有丰富的库和工具包,可以应用于各种领域的开发工作。在本文中,我将为大家介绍一些 Python 编程技巧,帮助你更高效地编写代码。 技巧1:使用列表推导式 列表推导式是一种简单而强大的 Python 特性。通过使用列表推导式,可以快速创建列表。以下是一个简单的例子: numbe…

    python 2023年5月14日
    00
  • python实现门限回归方式

    门限回归(threshold regression)是一种分类回归技术,可以将数据集分成两个或多个不同组。门限回归可以用于分类问题或者将数据分成不同的组,在每个组中建立不同的回归模型。本文将讲解如何使用Python实现门限回归。 准备工作 在开始实现门限回归之前,需要在Python中安装相关的库,其中最重要的是statsmodels库。下面是安装statsm…

    python 2023年5月19日
    00
  • python机器学习基础线性回归与岭回归算法详解

    Python机器学习基础:线性回归与岭回归算法详解 线性回归 线性回归是一种基本的机器学习算法,它的目的是在给定的数据集上拟合一条直线,以便预测新的数据点。在Python中,我们可以使用scikit-learn库来实现线性回归算法。 线性回归的原理 线性回归的原理是通过最小化预测值与真实值之间的差距来拟合一条直线。这个差距可以用平方误差来表示,即: $$\t…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部