Reputation: 238
I am create server side program in c++, program create RSA public and private key with openssl library and then public key distribute over the network for clients. in clients side i wrote c# program first get public key and then encrypt data. but i can not add public key to RSACryptoServiceProvider.
is there a way to import RSA public key to RSACryptoServiceProvider?
-----BEGIN RSA PUBLIC KEY----- MIIBCAKCAQEAsgVkBAQPdtRtICOqWdZ0ZiMAb9UvUX0BaxANN22bL5RzTJAL+PmG QKaA61B1m0NPOjdIIXMwkaAzXOmzuNwKm2Ugb8jO15B6ovAhe73jAoltFFdi10Te zCJgT8/xLAWt1mOXCAK9vD4Pv5LMN76BF+YjEVvylQ3l87255ElZrP4UluCGj0U3 uczW8+Cqao3QoL6xSxPU9jSK0FT/OhAL312cAXYbnaiJH+wAf1kkv4ez28XAlFId MlCmh2n8YSuxk1GdOXaps8IoluDzmHeQ8vk2quQMPpFXzfCayBoPm9lVPOjOQkAH 8ClJda0Uy052N5aE0BuyX1KRxOSdRRKk9wIBAw==
-----END RSA PUBLIC KEY-----
Upvotes: 1
Views: 2185
Reputation: 238
This is a sample code show how to add RSA public key to RSACryptoServiceProvider in c#
public Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
string publicKey = "-----BEGIN RSA PUBLIC KEY-----\nMIIBCAKCAQEAoNhWLaL11Zy4L6Cp2IDFv2JGnPkoRnFrKTy5b23uszzbSammdIwi\n6Wtr/7Zg3wmqlwt/yhH4F6rwSysB04xvMnWjuRsw2Kz4u7FHMPlgrIObGDFqcEms\nllNTA8xSWh/+TPfxWdAN5bpUwLYo6Mizl+VStL4CtVQFS8/mQSUnCju3csfxNGlk\nPQdbwZWB/5DdswrhkUcob8wl3bCCZCz3zWzMNJFTgTEiZQr+qTtuY7ST+fmpO33r\nDJoboysiGPKUkQixKcG2s1jJJkQircAHkmiQPS6PlUapNahFNaPa3rh1zR4l5NN6\nxWudPYQhZ8VvD4C8eT2bfrUlsikAyXIX4QIBAw==\n-----END RSA PUBLIC KEY-----\n"
using (Stream stream = GenerateStreamFromString(publicKey))
{
PemReader pemReader = new PemReader(new StreamReader(stream));
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pemReader.ReadObject();
pemReader.Reader.Close();
Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters rsaPub = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey;
RSAParameters RSAKeyInfo = Org.BouncyCastle.Security.DotNetUtilities.ToRSAParameters(rsaPub);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048);
RSA.ImportParameters(RSAKeyInfo);
byte[] encryptedData = RSA.Encrypt(plainText, true);
}
Upvotes: 1
Reputation: 9806
You can do this using BouncyCastle, which is, unfortunately, one of the only ways to solve this problem.
PemReader reader = new PemReader(new StreamReader(File.Open(file, FileMode.Open)));
AsymmetricCipherKeyPair = (AsymmetricCipherKeyPair)reader.ReadObject();
reader.Reader.Close();
This code isn't tested, so some of the method names might be a tad off. You can then use the static methods in the DotNetUtilities
class to convert to RSACryptoServiceProvider
.
Upvotes: 1