怎么用RS256 (RSA-SHA256) 生成一个 公钥和私钥
时间: 2024-10-24 18:09:26 浏览: 60
RS256是基于RSA算法和SHA-256哈希函数的安全通信标准,常用于JSON Web Tokens (JWT) 的加密。以下是使用Python的cryptography库生成RSA公钥和私钥的基本步骤:
```python
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
# 生成密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
# 将公钥转换为PEM格式的字符串
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 将私钥转换为PEM格式的字符串,通常会存储在安全的地方或使用密码保护
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption() # 使用默认的无密码加密
)
print("Public Key (PEM):", public_pem)
print("Private Key (PEM):", private_pem)
```
阅读全文