Skip to content

Instantly share code, notes, and snippets.

@aelij
Created July 30, 2018 07:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aelij/4519c92a8ec3d8bcf5d923752fcccec4 to your computer and use it in GitHub Desktop.
Save aelij/4519c92a8ec3d8bcf5d923752fcccec4 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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