帮我用python代码生成根证书,并用根证书签发加密证书
时间: 2023-05-18 08:07:07 浏览: 127
当然可以,以下是生成根证书的 Python 代码:
```python
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
# 生成 RSA 密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# 创建 X.509 证书
subject = issuer = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, "CN"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Beijing"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "Beijing"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "CSDN"),
x509.NameAttribute(NameOID.COMMON_NAME, "CSDN Root CA"),
])
cert = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
issuer
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=365)
).add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=True,
).sign(private_key, hashes.SHA256())
# 将证书和私钥保存到文件
with open("root_cert.pem", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
with open("root_key.pem", "wb") as f:
f.write(private_key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
))
```
接下来,使用根证书签发加密证书的 Python 代码如下:
```python
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
# 读取根证书和私钥
with open("root_cert.pem", "rb") as f:
root_cert = x509.load_pem_x509_certificate(f.read())
with open("root_key.pem", "rb") as f:
root_key = serialization.load_pem_private_key(
f.read(),
password=None,
)
# 生成 RSA 密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# 创建 X.509 证书
subject = x509.Name([
x509.NameAttribute(NameOID.COUNTRY_NAME, "CN"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Beijing"),
x509.NameAttribute(NameOID.LOCALITY_NAME, "Beijing"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "CSDN"),
x509.NameAttribute(NameOID.COMMON_NAME, "www.csdn.net"),
])
cert = x509.CertificateBuilder().subject_name(
subject
).issuer_name(
root_cert.subject
).public_key(
private_key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=365)
).add_extension(
x509.BasicConstraints(ca=False, path_length=None), critical=True,
).sign(root_key, hashes.SHA256())
# 将证书和私钥保存到文件
with open("cert.pem", "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
with open("key.pem", "wb") as f:
f.write(private_key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
))
```
希望这些代码能够帮助你生成根证书和加密证书。
阅读全文