Skip to content

Instantly share code, notes, and snippets.

@jordan-wright
Created August 11, 2020 02:56
Show Gist options
  • Save jordan-wright/a2d87797912922d5133dc4d0b90f62f3 to your computer and use it in GitHub Desktop.
Save jordan-wright/a2d87797912922d5133dc4d0b90f62f3 to your computer and use it in GitHub Desktop.
Converting an ssh.PublicKey to an *rsa.PublicKey in Go
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"golang.org/x/crypto/ssh"
)
func main() {
// First, generate the test RSA keypair in SSH format
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
log.Fatal(err)
}
rsaPub := priv.PublicKey
sshPub, err := ssh.NewPublicKey(&rsaPub)
if err != nil {
log.Fatal(err)
}
sshPubBytes := sshPub.Marshal()
// Now we can convert it back to PEM format
// Remember: if you're reading the public key from a file, you probably
// want ssh.ParseAuthorizedKey.
parsed, err := ssh.ParsePublicKey(sshPubBytes)
if err != nil {
log.Fatal(err)
}
// To get back to an *rsa.PublicKey, we need to first upgrade to the
// ssh.CryptoPublicKey interface
parsedCryptoKey := parsed.(ssh.CryptoPublicKey)
// Then, we can call CryptoPublicKey() to get the actual crypto.PublicKey
pubCrypto := parsedCryptoKey.CryptoPublicKey()
// Finally, we can convert back to an *rsa.PublicKey
pub := pubCrypto.(*rsa.PublicKey)
// After this, it's encoding to PEM - same as always
encoded := pem.EncodeToMemory(&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(pub),
})
fmt.Printf("%s", encoded)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment