コード例 #1
0
    public void System_NoKeysDirectoryProvided_UsesDefaultKeysDirectory()
    {
        var mock     = new Mock <IDefaultKeyStorageDirectories>();
        var keysPath = Path.Combine(AppContext.BaseDirectory, Path.GetRandomFileName());

        mock.Setup(m => m.GetKeyStorageDirectory()).Returns(new DirectoryInfo(keysPath));

        // Step 1: Instantiate the system and round-trip a payload
        var provider = DataProtectionProvider.CreateProvider(
            keyDirectory: null,
            certificate: null,
            setupAction: builder =>
        {
            builder.SetApplicationName("TestApplication");
            builder.Services.AddSingleton <IKeyManager>(s =>
                                                        new XmlKeyManager(
                                                            s.GetRequiredService <IOptions <KeyManagementOptions> >(),
                                                            s.GetRequiredService <IActivator>(),
                                                            NullLoggerFactory.Instance,
                                                            mock.Object));
        });

        var protector = provider.CreateProtector("Protector");
        var plainText = "payload";

        Assert.Equal(plainText, protector.Unprotect(protector.Protect(plainText)));

        // Step 2: Validate that there's now a single key in the directory
        var newFileName = Assert.Single(Directory.GetFiles(keysPath));
        var file        = new FileInfo(newFileName);

        Assert.StartsWith("key-", file.Name, StringComparison.OrdinalIgnoreCase);
        var fileText = File.ReadAllText(file.FullName);

        // On Windows, validate that it's protected using Windows DPAPI.
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Assert.DoesNotContain("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
            Assert.Contains("This key is encrypted with Windows DPAPI.", fileText, StringComparison.Ordinal);
        }
        else
        {
            Assert.Contains("Warning: the key below is in an unencrypted form.", fileText, StringComparison.Ordinal);
        }
    }