Load public key from DER encoded certificate

999 views
Skip to first unread message

0x7bc77a

unread,
Mar 6, 2017, 10:02:26 AM3/6/17
to golang-nuts
Hi,

I would like to load the public key from a DER encoded certificate

Here is my code

func ExampleParsePKIXPublicKey() {
raw, err := ioutil.ReadFile("/Path/To/DER/Encoded/Certificate")

if err != nil {
panic("failed to read certificate" + err.Error())
}

pub, err := x509.ParsePKIXPublicKey(raw)

if err != nil {
panic("failed to parse DER encoded public key: " + err.Error())
}

switch pub := pub.(type) {
case *rsa.PublicKey:
fmt.Println("Pub is of type RSA:", pub)
case *dsa.PublicKey:
fmt.Println("Pub is of type DSA:", pub)
case *ecdsa.PublicKey:
fmt.Println("Pub is of type ECDSA:", pub)
default:
panic("unknown type fo public key")
}
}

then I get errors like below:

panic: failed to parse DER encoded public key: asn1: structure error: tags don't match (6 vs {class:2 tag:0 length:3 isCompound:true}) {optional:false explicit:false application:f
alse defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} ObjectIdentifier @2

any ideas to solve this problem?

thanks in advance!

Janne Snabb

unread,
Mar 6, 2017, 11:50:12 AM3/6/17
to golan...@googlegroups.com
You are trying to read a certificate with a function intended for
reading a public key.

Use x509.ParseCertificates instead.


Janne Snabb
sn...@epipe.com
> --
> You received this message because you are subscribed to the Google
> Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to golang-nuts...@googlegroups.com
> <mailto:golang-nuts...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.

Simon Ritchie

unread,
Mar 7, 2017, 3:12:55 AM3/7/17
to golang-nuts
I've just put onto github a working example of an application that loads and uses a digital certificate.  It's not DER, but the code is probably a good guide as to what you need to do:  https://github.com/goblimey/grpc

I hope this helps.

Simon


Reply all
Reply to author
Forward
0 new messages