dsfdsf48652 2017-10-14 11:48
浏览 720

在Go中解析X509证书

I am having the following function, which reads an X509 certificate.

certCerFile,err := os.Open("certificate.pem")
if err != nil {
    log.Fatal(err)
}

derBytes := make([]byte,1000)

count,err:=certCerFile.Read(derBytes)
if err != nil {
    log.Fatal(err)
}

certCerFile.Close()

// trim the bytes to actual length in call
cert,err := x509.ParseCertificate(derBytes[0:count])
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Name %s
", cert.Subject.CommonName)
fmt.Printf("Not before %s
", cert.NotBefore.String())
fmt.Printf("Not after %s
", cert.NotAfter.String())

I face the following error:

asn1: structure error: tags don't match (16 vs {class:0 tag:13 length:45 isCompound:true}) {optional:false explicit:false application:false defaultValue: tag: stringType:0 timeType:0 set:false omitEmpty:false} certificate @2

That's how I generate X509:

random := rand.Reader

var key rsa.PrivateKey
loadKey("private.key",&key)

now:= time.Now()
then := now.Add(60 * 60 * 24 * 365 * 1000 * 1000 * 1000)

template:= x509.Certificate{
    SerialNumber: big.NewInt(1),
    Subject: pkix.Name{
        CommonName: "borscht.com",
        Organization: []string{"Borscht Systems AG"},
    },
    NotBefore:now,
    NotAfter:then,
    SubjectKeyId: []byte{1,2,3,4},
    KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
    BasicConstraintsValid:true,
    IsCA:true,
    DNSNames:[]string{"borscht.com","localhost"},
}

derBytes,err:=x509.CreateCertificate(random, &template, &template,&key.PublicKey,&key)
if err != nil {
    log.Fatal(err)
}

certCerFile,err :=os.Create("certificate.cer")
if err != nil {
    log.Fatal(err)
}

certCerFile.Write(derBytes)
certCerFile.Close()

certPemFile, err := os.Create("certificate.pem")
if err != nil {
    log.Fatal(err)
}

I just don't understand what might be wrong.

  • 写回答

1条回答 默认 最新

  • dsstjqsr631426 2017-10-14 15:04
    关注

    I made a mistake myself. Parse pem instead of cer file. Replaced and everything is fine

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置