1

I have someone's public key as a string:

<RSAKeyValue>
  <Modulus>publickeyhere</Modulus>
  <Exponent>AAAA</Exponent>
</RSAKeyValue>

I also have an app.config file and I'm trying to encrypt the appSettings section of it using the public key. I'm doing it like this

var publicKeyXml = @"<RSAKeyValue><Modulus>publickeyhere</Modulus><Exponent>AAAA</Exponent></RSAKeyValue>";

var map = new ExeConfigurationFileMap
{
    ExeConfigFilename = "app.config"
};

var config = ConfigurationManager
    .OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

using (var rsa = new RSACryptoServiceProvider())
{
    try
    {
        rsa.FromXmlString(publicKeyXml);

        // Now use the public key to encrypt how?
        config.AppSettings.SectionInformation
            .ProtectSection("RSAProtectedConfigurationProvider");
        config.SaveAs($"app.encrypted.config");
    }
    finally
    {
        rsa.PersistKeyInCsp = false;
    }
}

How can I tell it that to do the encryption, it should use the public key and not one from the current machine it's running on?

Jamie Twells
  • 1,924
  • 4
  • 26
  • 56
  • Why do you want to encrypt public key? Should not it be by definition accessible for everyone? – Nick Feb 12 '19 at 14:59
  • 1
    Sorry, I've not been clear. In RSA (and I'm no expert) I believe you use a public key to encrypt data, then the owner of the key uses their private key to decrypt the data. That's what I want to do, I want to use it to encrypt the data, then give it to them. – Jamie Twells Feb 12 '19 at 15:08
  • Ok, you got it right. – Nick Feb 12 '19 at 15:16
  • You can also take a look here: https://stackoverflow.com/questions/15702718/public-key-encryption-with-rsacryptoserviceprovider – Nick Feb 12 '19 at 15:20
  • @Nick yes, thanks, I've read that page, but I'm not trying to rewrite all the encryption stuff myself. .NET Framework can already encrypt app.config files using `config.AppSettings.SectionInformation .ProtectSection("RSAProtectedConfigurationProvider");` but I just don't know how to specify the public key I want it to use. If the encryption is being done remotely to have the app deployed to a server I need to use the server's public key, not my machine's. – Jamie Twells Feb 12 '19 at 15:33
  • Have you seen [this](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.protectedconfigurationprovider?view=netframework-4.7.2)? It shows how to create and use keys. – Nick Feb 12 '19 at 15:47

0 Answers0