如何自签ssl证书py
时间: 2024-10-03 17:02:18 浏览: 27
在Python中自签名SSL证书通常用于测试环境或开发阶段,因为正式环境中通常需要从受信任的证书颁发机构(CA)获取证书。以下是使用`cryptography`库创建自签名证书的基本步骤:
1. 安装所需库:
```bash
pip install cryptography certifi
```
2. 导入必要的模块并生成密钥对:
```python
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509 import CertificateBuilder
# 生成2048位RSA密钥
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
```
3. 创建证书信息:
```python
public_key = key.public_key()
builder = CertificateBuilder().subject_name(
# 可替换为实际的CN (Common Name) 或者其他相关信息
name = issuer = x509.Name([
x509.NameAttribute(x509.OrganizationalUnitName, "Your Organization"),
x509.NameAttribute(x509.CountryName, "US"), # 国家名
x509.NameAttribute(x509.LocalityName, "City"),
x509.NameAttribute(x509.CommonName, "localhost")
])
).issuer_name(issuer).public_key(public_key)
# 设置有效期
now = datetime.datetime.utcnow()
not_before = now - datetime.timedelta(days=30)
not_after = now + datetime.timedelta(days=365)
# 添加自签名声明
builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
certificate = builder.sign(key, hashes.SHA256(), default_backend())
```
4. 将证书保存到文件:
```python
with open('server.crt', 'wb') as f:
f.write(certificate.public_bytes(serialization.Encoding.PEM))
with open('server.key', 'wb') as f:
f.write(key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
))
```
现在,你有了名为`server.crt`的公钥证书和`server.key`的私钥文件。
阅读全文