Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Decrypt String From Within ConfigureServices

$
0
0

I'm still (slowly) learning .NET and .NET Core, and have run into a scenario that I'm hoping someone can shed some light on for me...

My web app uses a password when authenticating with an external service in order to send out an email. So I'm looking to store the password in an encrypted format within a SQL database, and then have the app grab it and decrypt it when it needs it (using a Key previously stored in the server's environment variables).

I can get things to encrypt and decrypt just fine when tinkering around with calling a method. However, I can't figure out how to decrypt the previously encrypted password from within "ConfigureServices" in Startup.cs.

My goal is to be able to call the method from within ConfigureServices AND supply the Key. But I can't seem to figure out how to do that while using dependency injection since it looks like the constructor needs that info.

A snippet from my class that does the decryption:

namespace MyAppName.Services
{
    public interface ICipherService
    {
        string DecryptProtectedData(string encryptedText, string environmentVariableName);
    }

    public class CipherService : ICipherService
    {
        IDataProtector _protector;

        private const string Key = "722f0c22-f1fb-22ad-22c7-9f2264771b22";

        public CipherService(IDataProtectionProvider provider)
        {
            _protector = provider.CreateProtector(Key);
        }

        public string DecryptProtectedData(string encryptedText, string environmentVariableName)
        {
            string unprotectedPayload = _protector.Unprotect(encryptedText);
            return unprotectedPayload;
        }
    }
}

Snippet from my ConfigureServices:

services.AddDataProtection();
services.AddTransient<ICipherService, CipherService>();
string encryptedText = databaseRecordEntry.MyEncryptedPassword;
string variableName = databaseRecordEntry.EnvironmentVariableOnServerWhereKeyIsStored;
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
serviceCollection.AddTransient<ICipherService, CipherService>();
var servicesCredentials = ActivatorUtilities.CreateInstance<CipherService>(serviceProvider);
string decryptedCredentials = servicesCredentials.DecryptProtectedData(encryptedText, variableName);

Can anyone point me in the right direction of getting rid of the "private const string Key" line in my class, and get it to work when being called within ConfigureServices?

Thanks!


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>