如何创建具有未定义有效期的证书

时间:2018-04-06 11:13:08

标签: go x509

如果我在初始化x509.Certificate期间省略了属性NotAfter,则会导致到期日期设置为&#34; 0001-01-01&#34;,从而使证书过期。< / p>

在PHP + phpseclib中,我可以跳过设置此字段,使发布的证书永不过期。是否可以在Go中执行此操作?

RFC 5280州:

  

4.1.2.5。有效性为了表明证书没有明确定义的到期日期,notAfter应该被赋予GeneralizedTime值99991231235959Z。

我怎样才能在Go中执行此操作?

1 个答案:

答案 0 :(得分:6)

TL; DR:NotBefore和NotAfter都不是可选的。你必须弄错你的 Python PHP脚本。如果你没有指定它,我会假设它使用NotAfter的某种默认值。

crypto / x509 defines the Validity as follows

type validity struct {
    NotBefore, NotAfter time.Time
}

由于两个字段都不是指针,因此无法定义它们。

如果要强制解决此问题,可以使用x509类型的修改副本对没有NotAfter字段的证书进行编码,但结果不可用。 Playground link

package main

import (
        "crypto/ecdsa"
        "crypto/elliptic"
        "crypto/rand"
        "crypto/x509"
        "crypto/x509/pkix"
        "encoding/asn1"
        "encoding/pem"
        "log"
        "math/big"
        "os"
        "time"
)

// copy of x509.certificate, with TBSCertificate.Validity.NotAfter omitted
type certificate struct {
        TBSCertificate struct {
                Version            int `asn1:"optional,explicit,default:0,tag:0"`
                SerialNumber       *big.Int
                SignatureAlgorithm pkix.AlgorithmIdentifier
                Issuer             asn1.RawValue
                Validity           struct {
                        NotBefore time.Time
                }
                Subject   asn1.RawValue
                PublicKey struct {
                        Raw       asn1.RawContent
                        Algorithm pkix.AlgorithmIdentifier
                        PublicKey asn1.BitString
                }
                UniqueId        asn1.BitString   `asn1:"optional,tag:1"`
                SubjectUniqueId asn1.BitString   `asn1:"optional,tag:2"`
                Extensions      []pkix.Extension `asn1:"optional,explicit,tag:3"`
        }
        SignatureAlgorithm pkix.AlgorithmIdentifier
        SignatureValue     asn1.BitString
}

func main() {
        derBytes := generateSelfSigned()

        // re-marshal to remove the NotAfter field
        var c certificate
        _, err := asn1.Unmarshal(derBytes, &c)
        check(err)

        derBytes, err = asn1.Marshal(c)
        check(err)

        pem.Encode(os.Stdout, &pem.Block{
                Type:  "CERTIFICATE",
                Bytes: derBytes,
        })
}

func generateSelfSigned() (derBytes []byte) {
        pk, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
        check(err)

        tpl := &x509.Certificate{SerialNumber: big.NewInt(1)}

        derBytes, err = x509.CreateCertificate(rand.Reader, tpl, tpl, &pk.PublicKey, pk)
        check(err)

        return derBytes
}

func check(err error) {
        if err != nil {
                log.Fatal(err)
        }
}

例如,如果您将其中一个证书交给openssl,则解析会按预期失败

  

无法加载证书

     

139990566643520:错误:0D078079:asn1编码例程:asn1_item_embed_d2i:字段缺失:crypto / asn1 / tasn_dec.c:389:Field = notAfter,Type = X509_VAL