Skip to content

Instantly share code, notes, and snippets.

@Northern-Lights
Created September 5, 2017 01:27
Show Gist options
  • Save Northern-Lights/8685a823e5c5503511e89068d855994c to your computer and use it in GitHub Desktop.
Save Northern-Lights/8685a823e5c5503511e89068d855994c to your computer and use it in GitHub Desktop.
Go: get public/private key from id_rsa PEM file
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/Northern-Lights/going/file"
)
// LoadPrivate loads an (unencrypted) RSA private key from PEM data
func LoadPrivate(filepath string) (*rsa.PrivateKey, error) {
// Read the bytes of the PEM file, e.g. id_rsa
pemData, e := file.Read(filepath)
if e != nil {
return nil, e
}
// Use the PEM decoder and parse the private key
pemBlock, _ := pem.Decode(pemData)
priv, e := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
// Public key can be obtained through priv.PublicKey
return priv, e
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment