将公钥整理为OpenSSH格式以进行显示

将公钥整理为OpenSSH格式以进行显示

问题描述:

I have an rsa.PublicKey object (retrieved from an rsa.PrivateKey). And I'm trying to export it into the OpenSSH format, to display it in a web page.

I've noticed the go.crypto/ssh library, which seems to be doing this.
And there's the discussion about it's implementation (it's actually exactly what I need to do)

Unfortunately, I'm getting a bit stuck, as the byte array returned is in an unknown encoding and I can't just transform it to a string to display it.

func PublicKey(rsaKey rsa.PublicKey) string {
  key, _ := ssh.NewPublicKey(&rsaKey)
  marshalled := ssh.MarshalPublicKey(key)
  return string(marshalled)
}

This seems to work as it adds the ssh-rsa at the beginning of the string. However, most characters aren't recognized.

Here's the bytes array I'm retrieving for a lambda public key:

[0 0 0 7 115 115 104 45 114 115 97 0 0 0 3 1 0 1 0 0 0 65 0 178 153 15 73 196 125 250 140 212 0 174 106 77 27 138 59 106 19 100 43 35 242 139 0 59 251 151 121 10 222 154 76 200 43 139 42 129 116 125 222 192 139 98 150 229 58 8 195 49 104 126 242 92 75 244 147 107 161 192 230 4 30 157 21]

Any hint on properly displaying this bytes array as a string?

Marshaling a key is for the wire format. You just need to base64 encode the bytes:

base64.StdEncoding.EncodeToString(marshalled) + "
"