2017-10-14 13 views
0

X509証明書を読み取る次の機能があります。Goでの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) 
} 

私は間違っているかもしれないものを理解していない:私はX509を生成する方法を説明します

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

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()) 

は、私は次のようなエラーに直面しています。

+1

あなたの解析コードでは、あなたは 'certificate.pem'を読んでいます。これがpemファイルの場合は、 'ParseCertificate'を呼び出す前に[DERを最初にデコードする](https://golang.org/pkg/encoding/pem/#Decode)する必要があります。しかし、あなたの世代コードでは、DERバイトを直接含む 'certificate.cer'を作成しています。それが原因でない場合は、あなたの質問を修正する必要があります。 – matt

+0

私は実際にpemも作成します。 –

答えて

0

自分で間違いを犯しました。 cerファイルの代わりにpemを解析します。置き換えられて、すべてが問題ありません。

関連する問題