Skip to content

Instantly share code, notes, and snippets.

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))
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.";
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);
return Convert.ToBase64String(envelope.Encode());
public static string DecryptText(string cipherText)
var content = Convert.FromBase64String(cipherText);
var envelope = new EnvelopedCms();
return Encoding.Unicode.GetString(envelope.ContentInfo.Content);

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.