Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Encrypt/decrypt Service Fabric secrets without the Fabric runtime
// Add NuGet "System.Security.Cryptography.Pkcs"
using System;
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
namespace Security
{
public static class CryptoUtility
{
public static string EncryptText(string plainText, string thumbprint, StoreName storeName = StoreName.My, StoreLocation storeLocation = StoreLocation.LocalMachine)
{
using (var store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
if (certificates.Count == 0)
{
throw new ArgumentOutOfRangeException(nameof(thumbprint), "Unable to locate a certificate with the specified thumbprint");
}
using (var certificate = certificates[0])
{
return EncryptText(plainText, certificate);
}
}
}
public static string EncryptText(string plainText, X509Certificate2 certificate)
{
const string OID_NIST_AES256_CBC = "2.16.840.1.101.3.4.1.42";
var content = new ContentInfo(Encoding.Unicode.GetBytes(plainText));
var envelope = new EnvelopedCms(content, new AlgorithmIdentifier(new Oid(OID_NIST_AES256_CBC)));
var recepient = new CmsRecipient(certificate);
envelope.Encrypt(recepient);
return Convert.ToBase64String(envelope.Encode());
}
public static string DecryptText(string cipherText)
{
var content = Convert.FromBase64String(cipherText);
var envelope = new EnvelopedCms();
envelope.Decode(content);
envelope.Decrypt();
return Encoding.Unicode.GetString(envelope.ContentInfo.Content);
}
}
}
@aelij

This comment has been minimized.

Copy link
Owner Author

@aelij aelij commented Jul 30, 2018

Compatible with System.Fabric.Security.EncryptionUtility and the Invoke-ServiceFabricEncryptText / Invoke-ServiceFabricDecryptText cmdlets, but doesn't require the Fabric runtime (implemented as pure .NET Standard code).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.