convert PEM encoded RSA public key to AsymmetricKe

2019-07-08 21:35发布

问题:

I am trying o create a method that constructs an AsymmetricKeyParameter from a PEM encoded public key. Unfortunately, pemReader.ReadObject() return null.

Here's a working solution for a private key: convert PEM encoded RSA private key to AsymmetricKeyParameter

What is wrong with this method?

static AsymmetricKeyParameter ReadPublicKeyFromPemEncodedString(string pemEncodedKey)
{
    AsymmetricKeyParameter result = null;
    using (var stringReader = new StringReader(pemEncodedKey))
    {
        var pemReader = new PemReader(stringReader);
        var pemObject = pemReader.ReadObject(); // null!
        result = ((AsymmetricCipherKeyPair)pemObject).Public;
    }

    return result;
}

Here is the PEM-encoded public key I am testing with. I have tried without the comment and also removing SSH2.

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20170608"
AAAAB3NzaC1yc2EAAAABJQAAAQEAk0AmagKx285Ufbri/olc+f3WagL1Ho+DrYdD
SbuU7cJAq+uD9xGvvP9m2JavSP4wO9i9pB/cmCFMPoIj3oGJt1/cnLb/U2juneOw
6Uo0N3F8TXdyXfZNAIPhq/jw0YfIypTFTTvFkKXfTArIwW/bQBW8/dujFR8i5CxP
jRKRDOBEy0PPOLJDD0iUr9GX/h/EO4jQ7B/GszjhPiPx+gJCilaMY+jrSczjxpsK
OXzpZEdT1NqMrzgvIZPHYhQzAiw9vQzov3vezDwKgKcRrUixZ2B8uiEQNn7Wa2Qz
WF3vL+6CGflFNYQcc0leDQBe86baYhCollouP4jfaH9KcMkYYw==
---- END SSH2 PUBLIC KEY ----

回答1:

Bouncy castle just does not understand this format of public key (SSH2) (you can verify this by looking at source code of PemReader if you would like to). Unfortunately I don't know how to convert it to appropriate format in C#, but you can do that with many tools, for example with ssh-keygen (also available in gitbash for windows), or openssl. Your public key will look like this when converted to PEM:

-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAk0AmagKx285Ufbri/olc+f3WagL1Ho+DrYdDSbuU7cJAq+uD9xGv
vP9m2JavSP4wO9i9pB/cmCFMPoIj3oGJt1/cnLb/U2juneOw6Uo0N3F8TXdyXfZN
AIPhq/jw0YfIypTFTTvFkKXfTArIwW/bQBW8/dujFR8i5CxPjRKRDOBEy0PPOLJD
D0iUr9GX/h/EO4jQ7B/GszjhPiPx+gJCilaMY+jrSczjxpsKOXzpZEdT1NqMrzgv
IZPHYhQzAiw9vQzov3vezDwKgKcRrUixZ2B8uiEQNn7Wa2QzWF3vL+6CGflFNYQc
c0leDQBe86baYhCollouP4jfaH9KcMkYYwIBJQ==
-----END RSA PUBLIC KEY-----

And it will be correctly handled by your current code, with a little change:

var pemReader = new PemReader(stringReader);
var pemObject = pemReader.ReadObject(); // null!
// it's already AsymmetricKeyParameter
result = ((AsymmetricKeyParameter)pemObject);