Python写加密算法并给出解密算法
时间: 2023-03-19 12:23:39 浏览: 83
Python可以使用多种加密算法,例如对称加密算法和非对称加密算法。以下是一个简单的对称加密算法的Python示例代码:
```python
import base64
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
fernet = Fernet(key)
# 要加密的明文
message = b"Hello world"
# 加密
encrypted_message = fernet.encrypt(message)
# 将密钥和加密后的消息进行base64编码并输出
print(base64.urlsafe_b64encode(key).decode())
print(base64.urlsafe_b64encode(encrypted_message).decode())
# 解密
decrypted_message = fernet.decrypt(encrypted_message)
# 输出解密后的明文
print(decrypted_message.decode())
```
该代码生成一个随机密钥并使用Fernet算法进行加密和解密。可以将密钥和加密后的消息进行base64编码后输出,以便在不同的系统之间传输。要解密消息,只需使用相同的密钥和Fernet对象调用decrypt()方法即可。
需要注意的是,对称加密算法中使用的密钥必须安全地存储和传输,否则可能会被攻击者获取并使用。
相关问题
用Python3写RSA加密算法和解密算法
以下是一个简单的 Python3 RSA 加密和解密代码:
```python
import random
# 求最大公因数
def gcd(a, b):
while b:
a, b = b, a % b
return a
# 求模反元素
def modinv(a, m):
if gcd(a, m) != 1:
return None # 如果 a 和 m 不互质,则不存在模反元素
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (
u1 - q * v1, u2 - q * v2, u3 - q * v3, v1, v2, v3
)
return u1 % m
# 生成公钥和私钥
def generate_keypair(p, q):
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
while gcd(e, phi) != 1:
e = random.randrange(1, phi)
d = modinv(e, phi)
return (e, n), (d, n)
# 加密函数
def encrypt(public_key, plaintext):
e, n = public_key
ciphertext = [pow(ord(char), e, n) for char in plaintext]
return ciphertext
# 解密函数
def decrypt(private_key, ciphertext):
d, n = private_key
plaintext = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plaintext)
# 测试
p, q = 61, 53
public_key, private_key = generate_keypair(p, q)
plaintext = 'Hello World!'
ciphertext = encrypt(public_key, plaintext)
decrypted_text = decrypt(private_key, ciphertext)
print('加密前:', plaintext)
print('加密后:', ciphertext)
print('解密后:', decrypted_text)
```
这段代码中使用了两个大素数 p 和 q 生成了公钥和私钥,使用了欧拉函数 phi、模反元素和快速幂算法进行加密和解密。需要注意的是,这里加密和解密的文本都必须是 ASCII 码,如果需要加密中文等非 ASCII 码字符,可使用 Base64 等编码方式将其转换为 ASCII 码。
python写加密算法
### 回答1:
Python可以用于编写各种加密算法。以下是一些常见的加密算法和Python代码示例:
1. Caesar密码
Caesar密码是一种简单的替换密码,它通过将明文中的每个字母都向后移动固定数量的位置来加密消息。Python代码示例如下:
```python
def caesar_cipher(plain_text, shift):
cipher_text = ""
for char in plain_text:
if char.isalpha():
# Shift character by given amount
char_code = ord(char) + shift
# Handle wrap-around for letters
if char.isupper():
if char_code > ord('Z'):
char_code -= 26
elif char_code < ord('A'):
char_code += 26
else:
if char_code > ord('z'):
char_code -= 26
elif char_code < ord('a'):
char_code += 26
cipher_text += chr(char_code)
else:
cipher_text += char
return cipher_text
```
2. AES加密
AES是一种高级加密标准,它可以用于加密大块数据。Python标准库中的`cryptography`模块提供了实现AES加密的功能。以下是一个简单的AES加密示例:
```python
from cryptography.fernet import Fernet
# Generate a new AES key
key = Fernet.generate_key()
# Create a Fernet object with the key
cipher_suite = Fernet(key)
# Encrypt some data
plain_text = b"Hello, world!"
cipher_text = cipher_suite.encrypt(plain_text)
# Decrypt the data
decrypted_text = cipher_suite.decrypt(cipher_text)
print(decrypted_text) # b'Hello, world!'
```
3. RSA加密
RSA是一种非对称加密算法,它可以用于加密和解密数据。Python标准库中的`cryptography`模块提供了实现RSA加密的功能。以下是一个简单的RSA加密示例:
```python
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# Generate a new RSA key pair
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# Serialize the keys to PEM format
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# Encrypt some data with the public key
plain_text = b"Hello, world!"
cipher_text = public_key.encrypt(
plain_text,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Decrypt the data with the private key
decrypted_text = private_key.decrypt(
cipher_text,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(decrypted_text) # b'Hello, world!'
```
### 回答2:
Python是一种简单易学的编程语言,也非常适合用于编写加密算法。
在Python中,我们可以使用一些库来实现不同类型的加密算法,例如hashlib库用于实现hash函数,cryptography库用于实现对称和非对称加密算法。
对称加密算法是指使用同一个密钥(即加密密钥和解密密钥相同)进行加密和解密的算法,常见的对称加密算法有AES、DES等。我们可以使用cryptography库来实现对称加密算法,例如AES算法的实现代码如下:
```python
from cryptography.fernet import Fernet
# 生成密钥
key = Fernet.generate_key()
cipher_suite = Fernet(key)
# 要加密的明文
plaintext = b"Hello, world!"
# 加密
ciphertext = cipher_suite.encrypt(plaintext)
# 解密
decrypted_text = cipher_suite.decrypt(ciphertext)
print(decrypted_text) # 输出 b"Hello, world!"
```
非对称加密算法是指使用两个不同的密钥(即公钥和私钥)进行加密和解密的算法,常见的非对称加密算法有RSA、DSA等。我们同样可以使用cryptography库来实现非对称加密算法,例如RSA算法的实现代码如下:
```python
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
# 生成RSA密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# 要加密的明文
plaintext = b"Hello, world!"
# 加密
ciphertext = public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 解密
decrypted_text = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(decrypted_text) # 输出 b"Hello, world!"
```
以上是用Python实现对称和非对称加密算法的简单示例,实际应用中可能还需要考虑更多的安全性和性能方面的问题。请注意,在编写实际的加密算法时,需要遵循相关的密码学原则和最佳实践,以确保加密的安全性。
### 回答3:
Python可以使用不同的库和模块来实现加密算法,以下是一个使用pycrypto库实现加解密算法的示例:
首先,我们需要安装pycrypto库,通过运行以下命令来安装:
```
pip install pycrypto
```
然后,我们可以使用pycrypto库中的AES模块来实现AES加密算法。在下面的示例中,我们将使用CBC模式和256位密钥进行加密和解密:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
def encrypt(plain_text, key):
iv = get_random_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted_data = cipher.encrypt(plain_text.encode("utf-8"))
return iv + encrypted_data
def decrypt(cipher_text, key):
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_data = cipher.decrypt(cipher_text[AES.block_size:])
return decrypted_data.decode("utf-8")
# 使用示例
key = b'this is a 32-byte key for AES-256'
plain_text = 'Hello, World!'
cipher_text = encrypt(plain_text, key)
decrypted_text = decrypt(cipher_text, key)
print('加密前:', plain_text)
print('加密后:', cipher_text.hex())
print('解密后:', decrypted_text)
```
这个示例中,我们首先生成一个随机的初始化向量(iv),然后使用给定的密钥和iv创建一个AES加密器。将明文输入加密器,得到加密后的数据。解密函数接受密文和密钥作为输入,使用相同的iv和密钥创建AES解密器,并将密文输入解密器,得到解密后的明文。
这只是一个简单示例,并且可以根据实际需求进行更复杂的加密操作和算法选择。