2017-10-14 1076 views
0

我有以下函數,它讀取X509證書。在Go中解析X509證書

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\n", cert.Subject.CommonName) 
fmt.Printf("Not before %s\n", cert.NotBefore.String()) 
fmt.Printf("Not after %s\n", cert.NotAfter.String()) 

我面臨以下錯誤:

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

這就是我如何生成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) 
} 

我就是不明白,什麼可能是錯誤的。

+1

在您正在閱讀'certificate.pem'解析代碼。如果這是一個pem文件,在調用'ParseCertificate'之前,您需要[首先將其解碼爲DER](https://golang.org/pkg/encoding/pem/#Decode)。然而,在你的代碼中,你直接創建了包含DER字節的'certificate.cer',所以如果這不是你需要修復你的問題的原因。 – matt

+0

我其實也創建了pem。 –

回答

0

我自己犯了一個錯誤。解析pem而不是cer文件。替換,一切都很好