对称加密和非对称是什么,应用场景有哪些,并用python源码实现一下
时间: 2024-04-17 18:29:46 浏览: 10
对称加密和非对称加密是两种不同的加密算法。
对称加密算法使用相同的密钥进行加密和解密,加密速度快,适合大量数据的加密,但密钥需要安全地共享给解密方。
非对称加密算法使用成对的公钥和私钥进行加密和解密,公钥用于加密,私钥用于解密。公钥可以公开,而私钥必须保密。非对称加密算法通常用于安全通信、数字签名等场景。
以下是一个使用Python实现对称加密和非对称加密的示例:
```python
# 对称加密示例
from cryptography.fernet import Fernet
# 生成随机密钥
key = Fernet.generate_key()
cipher = Fernet(key)
# 加密明文
plaintext = b"Hello, World!"
ciphertext = cipher.encrypt(plaintext)
# 解密密文
decrypted_text = cipher.decrypt(ciphertext)
print("对称加密示例:")
print("明文:", plaintext)
print("密文:", ciphertext)
print("解密后的明文:", decrypted_text)
# 非对称加密示例
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
# 生成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("非对称加密示例:")
print("明文:", plaintext)
print("密文:", ciphertext)
print("解密后的明文:", decrypted_text)
```
请注意,这只是一个简单的示例,实际应用中需要考虑更多的安全性和错误处理。此外,需要安装 `cryptography` 库来运行上述代码。