Created
July 30, 2018 07:06
-
-
Save aelij/4519c92a8ec3d8bcf5d923752fcccec4 to your computer and use it in GitHub Desktop.
Encrypt/decrypt Service Fabric secrets without the Fabric runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compatible with
System.Fabric.Security.EncryptionUtility
and theInvoke-ServiceFabricEncryptText
/Invoke-ServiceFabricDecryptText
cmdlets, but doesn't require the Fabric runtime (implemented as pure .NET Standard code).