Beispiel #1
0
        public static void Main(string[] args)
        {
            var destDir = Path.Combine(
                Environment.GetEnvironmentVariable("LOCALAPPDATA"),
                "AppSecrets");
            var serviceColletion = new ServiceCollection();

            serviceColletion.AddDataProtection()
            // 設定儲存的位置
            .PersistKeysToFileSystem(new DirectoryInfo(destDir));
            var services = serviceColletion.BuildServiceProvider();
            // 取得 protector
            var protector = services.GetDataProtector("Persist.Protector.Sample");

            Write("Input: ");
            // 測試使用 byte[] (也可以使用 string)
            byte[] input         = Encoding.UTF8.GetBytes(ReadLine());
            var    protectedData = protector.Protect(input);

            WriteLine($"Protected payload: {Convert.ToBase64String(protectedData)}");
            var roundTripped = protector.Unprotect(protectedData);

            WriteLine($"Round-tripped payload: {Encoding.UTF8.GetString(roundTripped)}");

            // 取出 key manager 用來 revoke key
            var keyManager = services.GetService <IKeyManager>();

            WriteLine("Revoking all keys in the key rings...");
            keyManager.RevokeAllKeys(DateTimeOffset.Now, "For Testing.");

            WriteLine("Calling unprotect");
            try {
                var unprotectPayload = protector.Unprotect(protectedData);
                WriteLine($"un-protected payload: {Encoding.UTF8.GetString(unprotectPayload)}");
            } catch (Exception e) {
                WriteLine($"{e.GetType().Name}: {e.Message}");
            }

            Console.WriteLine("Calling DangerousUnprotect...");
            try {
                IPersistedDataProtector persistedProtector = protector as IPersistedDataProtector;
                if (persistedProtector == null)
                {
                    throw new Exception("無法呼叫 DangerousUnprotect");
                }

                bool requiredMigration, wasRevoked;
                var  unprotectPayload = persistedProtector.DangerousUnprotect(
                    protectedData: protectedData,
                    ignoreRevocationErrors: true,
                    requiresMigration: out requiredMigration,
                    wasRevoked: out wasRevoked
                    );

                WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectPayload)}");
                WriteLine($"Requires migration = {requiredMigration}, was Revoked = {wasRevoked}");
            } catch (Exception e) {
                WriteLine($"{e.GetType().Name}: {e.Message}");
            }
        }
Beispiel #2
0
        public static string PersistentProtect(
            this IPersistedDataProtector dp,
            string clearText)
        {
            byte[] clearBytes     = Encoding.UTF8.GetBytes(clearText);
            byte[] protectedBytes = dp.Protect(clearBytes);

            string result = Convert.ToBase64String(protectedBytes);

            return(result);
        }
Beispiel #3
0
    public EncryptingUserTokenStoreDecorator(
        IUserTokenStore decorated,
        IDataProtectionProvider dataProtectionProvider,
        ILogger <EncryptingUserTokenStoreDecorator> logger)
    {
        _decorated = decorated;
        _logger    = logger;

        _baseProtector = dataProtectionProvider.CreateProtector(nameof(EncryptingUserTokenStoreDecorator)) as IPersistedDataProtector ??
                         throw new Exception("Protection provider doesn't support persisted data protector");
    }
Beispiel #4
0
        public static string PersistentUnprotect(
            this IPersistedDataProtector dp,
            string protectedData,
            out bool requiresMigration,
            out bool wasRevoked)
        {
            bool ignoreRevocation = true;

            byte[] protectedBytes   = Convert.FromBase64String(protectedData);
            byte[] unprotectedBytes = dp.DangerousUnprotect(protectedBytes, ignoreRevocation, out requiresMigration, out wasRevoked);

            return(Encoding.UTF8.GetString(unprotectedBytes));
        }
        public void Post([FromBody] string value)
        {
            var endstring = _dataProtector.Protect(Encoding.UTF8.GetBytes("桂素伟"));
            IPersistedDataProtector persistedProtector = _dataProtector as IPersistedDataProtector;

            if (persistedProtector == null)
            {
                throw new Exception("Can't call DangerousUnprotect.");
            }
            bool requiresMigration, wasRevoked;
            var  unprotectedPayload = persistedProtector.DangerousUnprotect(
                protectedData: endstring,
                ignoreRevocationErrors: true,
                requiresMigration: out requiresMigration,
                wasRevoked: out wasRevoked);
            var str = $"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)},Requires migration = {requiresMigration}, was revoked = {wasRevoked}";
        }
Beispiel #6
0
        public string Unprotect(string protectedData)
        {
            if (string.IsNullOrEmpty(protectedData))
            {
                return(protectedData);
            }

            var bytes = Convert.FromBase64String(protectedData);

            try
            {
                var unprotectedData = _dataProtector.Unprotect(bytes);

                return(Encoding.UTF8.GetString(unprotectedData));
            }
            catch (Exception exUnprotect)
            {
                try
                {
                    IPersistedDataProtector persistedProtector = _dataProtector as IPersistedDataProtector;
                    if (persistedProtector == null)
                    {
                        throw new Exception("Can't call DangerousUnprotect.");
                    }

                    bool requiresMigration, wasRevoked;
                    var  unprotectedPayload = persistedProtector.DangerousUnprotect(
                        protectedData: bytes,
                        ignoreRevocationErrors: true,
                        requiresMigration: out requiresMigration,
                        wasRevoked: out wasRevoked);

                    Console.WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)}");
                    Console.WriteLine($"Requires migration = {requiresMigration}, was revoked = {wasRevoked}");

                    return(Encoding.UTF8.GetString(unprotectedPayload));
                }
                catch (Exception exUnprotectRevoked)
                {
                }
            }

            return(string.Empty);
        }
        private void Setup()
        {
            var services = new ServiceCollection();

            //http://docs.asp.net/en/latest/security/data-protection/configuration/overview.html
            //If you change the key persistence location, the system will no longer automatically encrypt keys 
            // at rest since it doesn’t know whether DPAPI is an appropriate encryption mechanism.
            //services.ConfigureDataProtection(configure =>
            //{
               
                //string pathToCryptoKeys = @"C:\_joe\__projects\__cloudscribe\_code\cloudscribe\src\example.WebApp\dp_keys\";

                // these keys are not encrypted at rest
                // since we have specified a non default location
                // that also makes the key portable so they will still work if we migrate to 
                // a new machine (will they work on different OS? I think so)
                // this is a similar server migration issue as the old machinekey
                // where we specified a machinekey in web.config so it would not change if we migrate to a new server
                //configure.PersistKeysToFileSystem(
                //    new DirectoryInfo(pathToCryptoKeys)
                //    );

                //configure.ProtectKeysWithCertificate("thumbprint");
                //configure.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
                ///configure.
            //});

            //IDataProtectionProvider dataProtectionProvider



            services.AddDataProtection();

            serviceProvider = services.BuildServiceProvider();

            dataProtectionProvider = serviceProvider.GetService<IDataProtectionProvider>();
            rawProtector = dataProtectionProvider.CreateProtector("sts.Licensing.Web.KeyPairManager");
            persistentProtector = rawProtector as IPersistedDataProtector;

            didSetup = true;
        }
        private void Setup()
        {
            var services = new ServiceCollection();

            //http://docs.asp.net/en/latest/security/data-protection/configuration/overview.html
            //If you change the key persistence location, the system will no longer automatically encrypt keys
            // at rest since it doesn’t know whether DPAPI is an appropriate encryption mechanism.
            //services.ConfigureDataProtection(configure =>
            //{

            //string pathToCryptoKeys = @"C:\_joe\__projects\__cloudscribe\_code\cloudscribe\src\example.WebApp\dp_keys\";

            // these keys are not encrypted at rest
            // since we have specified a non default location
            // that also makes the key portable so they will still work if we migrate to
            // a new machine (will they work on different OS? I think so)
            // this is a similar server migration issue as the old machinekey
            // where we specified a machinekey in web.config so it would not change if we migrate to a new server
            //configure.PersistKeysToFileSystem(
            //    new DirectoryInfo(pathToCryptoKeys)
            //    );

            //configure.ProtectKeysWithCertificate("thumbprint");
            //configure.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
            ///configure.
            //});

            //IDataProtectionProvider dataProtectionProvider



            services.AddDataProtection();

            serviceProvider = services.BuildServiceProvider();

            dataProtectionProvider = serviceProvider.GetService <IDataProtectionProvider>();
            rawProtector           = dataProtectionProvider.CreateProtector("sts.Licensing.Web.KeyPairManager");
            persistentProtector    = rawProtector as IPersistedDataProtector;

            didSetup = true;
        }
    public static void Main(string[] args)
    {
        var serviceCollection = new ServiceCollection();

        serviceCollection.AddDataProtection();
        serviceCollection.ConfigureDataProtection(configure =>
        {
            // point at a specific folder and use DPAPI to encrypt keys
            configure.PersistKeysToFileSystem(new DirectoryInfo(@"c:\temp-keys"));
            configure.ProtectKeysWithDpapi();
        });
        var services = serviceCollection.BuildServiceProvider();
         
        // get a protector and perform a protect operation
        var protector = services.GetDataProtector("Sample.DangerousUnprotect");

        Console.Write("Input: ");
        byte[] input         = Encoding.UTF8.GetBytes(Console.ReadLine());
        var    protectedData = protector.Protect(input);

        Console.WriteLine($"Protected payload: {Convert.ToBase64String(protectedData)}");
         
        // demonstrate that the payload round-trips properly
        var roundTripped = protector.Unprotect(protectedData);

        Console.WriteLine($"Round-tripped payload: {Encoding.UTF8.GetString(roundTripped)}");
         
        // get a reference to the key manager and revoke all keys in the key ring
        var keyManager = services.GetService <IKeyManager>();

        Console.WriteLine("Revoking all keys in the key ring...");
        keyManager.RevokeAllKeys(DateTimeOffset.Now, "Sample revocation.");
         
        // try calling Protect - this should throw
        Console.WriteLine("Calling Unprotect...");

        try
        {
            var unprotectedPayload = protector.Unprotect(protectedData);
            Console.WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
        }
         
        // try calling DangerousUnprotect
        Console.WriteLine("Calling DangerousUnprotect...");

        try
        {
            IPersistedDataProtector persistedProtector = protector as IPersistedDataProtector;
            if (persistedProtector == null)
            {
                throw new Exception("Can't call DangerousUnprotect.");
            }
             
            bool requiresMigration, wasRevoked;
            var  unprotectedPayload = persistedProtector.DangerousUnprotect(
                protectedData: protectedData,
                ignoreRevocationErrors: true,
                requiresMigration: out requiresMigration,
                wasRevoked: out wasRevoked);
            Console.WriteLine($"Unprotected payload: {Encoding.UTF8.GetString(unprotectedPayload)}");
            Console.WriteLine($"Requires migration = {requiresMigration}, was revoked = {wasRevoked}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
        }
    }