gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:26:14 26 4
gpt4 key购买 nike

如果我在 x509.Certificate 初始化期间省略属性 NotAfter,它会导致到期日期设置为“0001-01-01”,从而使证书过期。

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

RFC 5280状态:

4.1.2.5. Validity To indicate that a certificate has no well-defined expiration date, the notAfter SHOULD be assigned the GeneralizedTime value of 99991231235959Z.

我如何在 Go 中执行此操作?

最佳答案

TL;DR:NotBefore 和 NotAfter 都不是可选的。您一定搞错了 Python PHP 脚本。如果您不指定它,我会假设它对 NotAfter 使用某种默认值。

加密/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,解析将按预期失败

unable to load certificate

139990566643520:error:0D078079:asn1 encoding routines:asn1_item_embed_d2i:field missing:crypto/asn1/tasn_dec.c:389:Field=notAfter, Type=X509_VAL

关于go - 如何创建未定义有效期的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com