.net core PersistKeysToFileSystem RRS feed

  • Question

  • Hi,

    I am working on .net core 2.1 and i have the private key generated by Microsoft application block and it's in G:/MyCompany.key.

    I wanted to use this key for all the data protection. below is my sample code

    public static void Main(string[] args)
                var keysFolder = @"G:\MyCompany.key";
                using (var services = new ServiceCollection()
                    .AddLogging(o => o.AddConsole().SetMinimumLevel(LogLevel.Debug))
                    .PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
                    .UseXmlEncryptor(s => new CustomXmlEncryptor(s))
                    var protector = services.GetDataProtector("TestPurpose");
                    // protect the payload
                    var protectedPayload = protector.Protect("Test!");
                    Console.WriteLine($"Protect returned: {protectedPayload}");
                    // unprotect the payload
                    var unprotectedPayload = protector.Unprotect(protectedPayload);
                    Console.WriteLine($"Unprotect returned: {unprotectedPayload}");

    The issue what am facing is, it's not taking the key file(which is an xml). Instead, it's generating the new key file. please suggest me how can i force the data protection to use the key that i already generated.

    loving dotnet

    Monday, November 5, 2018 2:09 PM

All replies

  • Maybe, you can get better support by posting to the .NET Core forum in the ASP.NET forums. Granted, you're not using ASP.NET,  but all forms of .NET Core are discussed in the forum.

    Monday, November 5, 2018 6:00 PM
  • Hi Born2Achieve,

    Please add the modify the extension name to .xml and put the xml file into a folder, like this:

    var keysFolder = @"G:\keyfolder";

    Change MyCompany.key  to MyCompany.xml and copy it into the folder into the folder named keyfolder.

    Best regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, November 6, 2018 6:14 AM