forked from jawkh/gpgme-sharp-implementation-guide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecrpytStringWithASPNETCoreDataProtectionAPI.cs
47 lines (44 loc) · 2.03 KB
/
DecrpytStringWithASPNETCoreDataProtectionAPI.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
namespace ProtectSecretsWithASPNETCoreDataProtectionAPI
{
/// <summary>
/// This helper class uses ASP.NET Core Data Protection API to Decrypt Secrets.
/// This helper class supports Windows, Linus and macOS Systems!
/// Credits: https://simplecodesoftware.com/articles/how-to-encrypt-data-on-macos-without-dpapi
/// </summary>
public class SecretsDecryptor
{
/// <summary>
/// Decrypt String using ASP.NET Core Data Protection API
/// </summary>
/// <param name="secret"></param>
/// <returns></returns>
public static SecureString DecryptString(string secret)
{
string sEntropy = ConfigurationManager.AppSettings["entropy"];
string sslCertDistinguishedSubjectName = ConfigurationManager.AppSettings["SSLCertDistinguishedSubjectName"];
return DecryptString(secret, sEntropy, sslCertDistinguishedSubjectName);
}
/// <summary>
/// Decrypt String using ASP.NET Core Data Protection API
/// </summary>
/// <param name="secret"></param>
/// <returns></returns>
public static SecureString DecryptString(string secret, string entropy, string sslCertDistinguishedSubjectName)
{
var serviceCollection2 = new ServiceCollection();
SetupEnvironment.ConfigureServices(serviceCollection2, sslCertDistinguishedSubjectName);
IDataProtector dataProtector2 = serviceCollection2.BuildServiceProvider().GetDataProtector(purpose: entropy);
byte[] unprotectedSecretBytes = dataProtector2.Unprotect(Convert.FromBase64String(secret));
return Util.ToSecureString(System.Text.Encoding.Unicode.GetString(unprotectedSecretBytes, 0, unprotectedSecretBytes.Length));
}
}
}