Using Base64 encoded Public Key to verify RSA signature

江枫思渺然 提交于 2019-11-27 22:05:27
Rasmus Faber

Your string is the base64 encoding of a SubjectPublicKeyInfo. You can use Bouncycastle.net to decode it like this:

byte[] publicKeyBytes = Convert.FromBase64String(publicKeyString);
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(publicKeyBytes);
RsaKeyParameters rsaKeyParameters = (RsaKeyParameters) asymmetricKeyParameter;
RSAParameters rsaParameters = new RSAParameters();
rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);

First base64 is only an encoding of some binary data. There's more than one way to encode, in binary, an RSA public key. However if you got this from OpenSSL it's likely a DER-encoded RSAPublicKey structure.

 RSAPublicKey ::= SEQUENCE {
     modulus            INTEGER,    -- n
     publicExponent     INTEGER  }  -- e

In general you would need a ASN.1 decoder, Mono.Security.dll provides one, but for such a simple structure you might want to do it by hand since ASN.1 is basically a Tag, Length and a Value.

If your partner also uses .NET, he/she can derive from Mono's makecert https://github.com/mono/mono/blob/bf55818da11240bd108dc51b374fae3d3b5482ce/mcs/tools/security/makecert.cs to generate certificate files and send to you directly.

In that case, you can easily load certificates instead of raw bytes,

http://www.lextm.com/2012/02/simple-publicprivate-key-signing-sample-code/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!