Reputation: 20906
Is it possible to generate RSACryptoServiceProvider from public cert key which is string.
I try like:
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
var publicKey = PublicKey.GetPublicKey();
provider.FromXmlString("<RSAKeyValue><Modulus>" + publicKey + "</Modulus></RSAKeyValue>");
but i get exception that is not valid base64
at Caused by: md52ce486a14f4bcd95899665e9d932190b.JavaProxyThrowable: System.Security.Cryptography.CryptographicException: Couldn't decode XML ---> System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
what can I do?
Upvotes: 0
Views: 1893
Reputation: 874
In .NET Core 3.0 and above you can do the following:
//create a RSACryptoServiceProvinder, sample use
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(ConvertPublicKeyFromBase64(base64publicKey));
//rest of the code
...
}
public string ConvertPublicKeyFromBase64(string publicKeyBase64)
{
// Decode the Base64 public key into a byte array
byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64);
// Create an RSA object to import the public key
using (var rsa = RSA.Create())
{
// Import the public key bytes
rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
// Export the public key as an XML string
string publicKeyXml = rsa.ToXmlString(false);
return publicKeyXml;
}
}
For .NET Framework, there is no ImportSubjectPublicKeyInfo() method so you can use this RSAExtensions Class that provides the ImportSubjectPublicKeyInfo() for it, and then use the code above.
GitHub code for RSAExtensions
RSAExtensions for .NET Framework article
Upvotes: 1
Reputation: 1802
Two things.
First: Your closing tags are backwards...
</RSAKeyValue></Modulus>
should read
</Modulus></RSAKeyValue>
Second: You're missing the exponent parameter.
See this working code:
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
//var publicKey = PublicKey.GetPublicKey();
provider.FromXmlString(
"<RSAKeyValue>"+
"<Modulus>CmZ5HcaYgWjeerd0Gbt/sMABxicQJwB1FClC4ZqNjFHQU7PjeCod5dxa9OvplGgXARSh3+Z83Jqa9V1lViC7qw==</Modulus>"+
"<Exponent>AQAB</Exponent>"+
"</RSAKeyValue>");
Upvotes: 2