Get pem formatted block
If your document contains not only PEM formatted block than Decode
function from encoding/pem
package will be helpful:
Decode will find the next PEM formatted block (certificate, private key etc) in the input. It returns that block and the remainder of the input. If no PEM data is found, p is nil and the whole of the input is returned in rest.
Parse key and check for rsa conformity
Go contains package named crypto
to do such things like parsing keys and certifies. For purpose of parsing public keys provided function ParsePKIXPublicKey
:
Supported key types include RSA, DSA, and ECDSA. Unknown key types result in an error.
On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey, or *ecdsa.PublicKey.
On return you obtain concrete type which is easy to assert with type switch (idiomatic way to determine type of variable):
// There is a key
const pubPEM = `MIICIjANBgkqhkiG9...`
// Ignore the rest of document
block, _ := pem.Decode([]byte(pubPEM))
if block == nil {
log.Fatal("The document doesn't contain PEM blocks.")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
log.Fatal("The block is not a DER encoded public key.")
}
switch pub := pub.(type) {
case *rsa.PublicKey:
fmt.Println("pub is of type RSA:", pub)
default:
log.Fatal("The key is not RSA encripted.")
}