我有一个经过编码的x509证书,我想更新CommonName(又名Subject或主机名)。
这里是我到目前为止(简化)的代码:
import (
"crypto/tls",
"crypto/x509"
)
...
// parses a public/private key pair from a pair of PEM encoded data
c, _ := tls.X509KeyPair(certPEMBlock, keyPEMBlock)
// parse into a x509 cert object
cert, _ := x509.ParseCertificate(c.Certificate[0])
// I want to modify the Subject here
// I want to encode it back to PEM encoded data of type []bytes
...
任何想法如何更新主题并将其编码回[] bytes类型的PEM编码数据?
您可以使用如下代码创建新证书。您需要为此使用CA私钥:
func GenerateCertificate(ca *x509.Certificate, caKey crypto.PrivateKey, req x509.CertificateRequest, durYear, durMonth int, keyUsage x509.KeyUsage, extKeyUsage []x509.ExtKeyUsage, rsaKeySize int) (certificate, key *pem.Block, err error) {
cert := &x509.Certificate{
Version: req.Version,
SerialNumber: RandomBigInt(),
Subject: req.Subject,
Extensions: req.Extensions,
ExtraExtensions: req.ExtraExtensions,
DNSNames: req.DNSNames,
EmailAddresses: req.EmailAddresses,
IPAddresses: req.IPAddresses,
URIs: req.URIs,
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(durYear, durMonth, 0),
ExtKeyUsage: extKeyUsage,
KeyUsage: keyUsage,
}
priv, _ := rsa.GenerateKey(rand.Reader, rsaKeySize)
pub := &priv.PublicKey
var data []byte
data, err = x509.CreateCertificate(rand.Reader, cert, ca, pub, caKey)
if err != nil {
return
}
// Public key
certificate = &pem.Block{Type: "CERTIFICATE", Bytes: data}
// Private key
key = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}
return
}
用作:
subject := pkix.Name{CommonName:"name"}
cert, certKey, err := GenerateCertificate(caCert, key, x509.CertificateRequest{Subject: subject}, 1, 0, x509.KeyUsageDigitalSignature,
[]x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 2048)
您需要找出密钥用法,外部密钥用法等,或从旧证书中复制它们。您可以初始化从您拥有的旧证书传递到GenerateCertificate中的证书请求。