コード例 #1
0
        /// <summary>
        /// Encrypts and saves the state to persistent storage
        /// </summary>
        /// <returns></returns>
        public async Task SaveAsync()
        {
            try
            {
                var knownTypes = this.KnownTypes ?? Enumerable.Empty <Type>();
                var serializer = new DataContractSerializer(this._values.GetType(), knownTypes);

                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(this.Filename, CreationCollisionOption.ReplaceExisting);

                using (var sw = new MemoryStream())
                {
                    serializer.WriteObject(sw, this._values);
                    sw.Position = 0;
                    var provider = new DataProtectionProvider("LOCAL=user");

                    // Encrypt the session data and write it to disk.
                    using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await provider.ProtectStreamAsync(sw.AsInputStream(), fs);

                        await fs.FlushAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new StateManagerException("Failed to save state.", ex);
            }
        }
コード例 #2
0
        public static async void Encrypt(Stream input, Stream output)
        {
            var outputStream = output.AsOutputStream();
            DataProtectionProvider provider = new DataProtectionProvider(LocalUser);

            await provider.ProtectStreamAsync(input.AsInputStream(), outputStream);
        }
コード例 #3
0
        public static async Task <IRandomAccessStream> ProtectPDFStream(IRandomAccessStream source)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=user");

            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();
            IOutputStream dest = protectedData.GetOutputStreamAt(0);

            await Provider.ProtectStreamAsync(source.GetInputStreamAt(0), dest);

            await dest.FlushAsync();

            //Verify that the protected data does not match the original
            //DataReader reader1 = new DataReader(source.GetInputStreamAt(0));
            //DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0));
            //var size1 = await reader1.LoadAsync((uint)(source.Size < 10000 ? source.Size : 10000));
            //var size2 = await reader2.LoadAsync((uint)(protectedData.Size < 10000 ? protectedData.Size : 10000));
            //IBuffer buffOriginalData = reader1.ReadBuffer((uint)size1);
            //IBuffer buffProtectedData = reader2.ReadBuffer((uint)size2);

            //if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData))
            //{
            //    throw new Exception("ProtectPDFStream returned unprotected data");
            //}

            //protectedData.Seek(0);
            //await protectedData.FlushAsync();

            // Return the encrypted data.
            return(protectedData);
        }
コード例 #4
0
        /// <summary>
        /// Protect stream data with data protection provider.
        /// </summary>
        /// <param name="source">The source stream contains the unprotected data.</param>
        /// <param name="destination">The destination stream contains the protected data.</param>
        /// <param name="protectionDescriptor">The entity to which the data will be protected. Default is set to LOCAL=user.</param>
        /// <returns></returns>
        public async Task ProtectStreamAsync(IInputStream source, IOutputStream destination, string protectionDescriptor = "LOCAL=user")
        {
            var provider = new DataProtectionProvider(protectionDescriptor);

            await provider.ProtectStreamAsync(source, destination);

            await destination.FlushAsync();
        }
コード例 #5
0
        public async Task SaveAsync()
        {
            try
            {
                // Save the navigation state for all registered frames
                foreach (var weakFrameReference in _registeredFrames)
                {
                    IFrameFacade frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                JsonSerializer serializer = new JsonSerializer
                {
                    TypeNameHandling     = TypeNameHandling.All,
                    DateFormatHandling   = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                };

                // Serialize the session state synchronously to avoid asynchronous access to shared
                // state
                using (MemoryStream sessionData = new MemoryStream())
                    using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(sessionData)))
                    {
                        serializer.Serialize(jsonTextWriter, _sessionState);

                        // Flush to the underyling stream.
                        jsonTextWriter.Flush();

                        // Get an output stream for the SessionState file and write the state asynchronously
                        StorageFile file =
                            await
                            ApplicationData.Current.LocalFolder.CreateFileAsync(SessionStateFileName,
                                                                                CreationCollisionOption.ReplaceExisting);

                        using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            sessionData.Seek(0, SeekOrigin.Begin);
                            var provider = new DataProtectionProvider("LOCAL=user");

                            // Encrypt the session data and write it to disk.
                            await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);

                            await fileStream.FlushAsync();
                        }
                    }
            }
            catch (Exception e)
            {
                throw new SessionStateServiceException(e);
            }
        }
コード例 #6
0
        private async Task <IBuffer> SampleDataProtectionStream(
            String descriptor,
            String strMsg,
            BinaryStringEncoding encoding)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(descriptor);

            // Convert the input string to a buffer.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Create a random access stream to contain the plaintext message.
            InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream();

            // Create a random access stream to contain the encrypted message.
            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();

            // Retrieve an IOutputStream object and fill it with the input (plaintext) data.
            IOutputStream outputStream = inputData.GetOutputStreamAt(0);
            DataWriter    writer       = new DataWriter(outputStream);

            writer.WriteBuffer(buffMsg);
            await writer.StoreAsync();

            await outputStream.FlushAsync();

            // Retrieve an IInputStream object from which you can read the input data.
            IInputStream source = inputData.GetInputStreamAt(0);

            // Retrieve an IOutputStream object and fill it with encrypted data.
            IOutputStream dest = protectedData.GetOutputStreamAt(0);
            await Provider.ProtectStreamAsync(source, dest);

            await dest.FlushAsync();

            //Verify that the protected data does not match the original
            DataReader reader1 = new DataReader(inputData.GetInputStreamAt(0));
            DataReader reader2 = new DataReader(protectedData.GetInputStreamAt(0));
            await reader1.LoadAsync((uint)inputData.Size);

            await reader2.LoadAsync((uint)protectedData.Size);

            IBuffer buffOriginalData  = reader1.ReadBuffer((uint)inputData.Size);
            IBuffer buffProtectedData = reader2.ReadBuffer((uint)protectedData.Size);

            if (CryptographicBuffer.Compare(buffOriginalData, buffProtectedData))
            {
                throw new Exception("ProtectStreamAsync returned unprotected data");
            }

            // Return the encrypted data.
            return(buffProtectedData);
        }
コード例 #7
0
        private async void onProtect(object sender, RoutedEventArgs e)
        {
            if (inputFile == null || outputFile == null)
            {
                return;
            }
            IRandomAccessStream inputstr = await inputFile.OpenAsync(FileAccessMode.Read);

            IRandomAccessStream outputstr = await outputFile.OpenAsync(FileAccessMode.ReadWrite); DataProtectionProvider dp = new DataProtectionProvider("LOCAL=user");
            await dp.ProtectStreamAsync(inputstr, outputstr);

            this.msgLabel.Text = "完成数据加密。"; inputFile = null;
            outputFile         = null;
            ClearDisplay();
        }
        public async Task <byte[]> Encrypt(byte[] data)
        {
            var provider = new DataProtectionProvider(UseForAllUsers ? _localMachineDescriptor : _localUserDescriptor);

            var contentBuffer          = CryptographicBuffer.CreateFromByteArray(data);
            var contentInputStream     = new InMemoryRandomAccessStream();
            var protectedContentStream = new InMemoryRandomAccessStream();

            //storing data in the stream
            IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0);
            var           dataWriter   = new DataWriter(outputStream);

            dataWriter.WriteBuffer(contentBuffer);
            await dataWriter.StoreAsync();

            await dataWriter.FlushAsync();

            //reopening in input mode
            IInputStream encodingInputStream = contentInputStream.GetInputStreamAt(0);

            IOutputStream protectedOutputStream = protectedContentStream.GetOutputStreamAt(0);
            await provider.ProtectStreamAsync(encodingInputStream, protectedOutputStream);

            await protectedOutputStream.FlushAsync();

            //verify that encryption happened
            var inputReader     = new DataReader(contentInputStream.GetInputStreamAt(0));
            var protectedReader = new DataReader(protectedContentStream.GetInputStreamAt(0));

            await inputReader.LoadAsync((uint)contentInputStream.Size);

            await protectedReader.LoadAsync((uint)protectedContentStream.Size);

            var inputBuffer     = inputReader.ReadBuffer((uint)contentInputStream.Size);
            var protectedBuffer = protectedReader.ReadBuffer((uint)protectedContentStream.Size);

            if (!CryptographicBuffer.Compare(inputBuffer, protectedBuffer))
            {
                return(protectedBuffer.ToArray());
            }
            else
            {
                return(null);
            }
        }
コード例 #9
0
        private async Task SaveNavigationStateAsync()
        {
            MemoryStream sessionData = new MemoryStream();
            var          session     = RootFrame.GetNavigationState();

            new DataContractSerializer(typeof(string)).WriteObject(sessionData, session);

            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(NavigationStateFileName, CreationCollisionOption.ReplaceExisting);

            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var provider = new DataProtectionProvider(NavigationDataProtectionProvider);
                // Encrypt the session data and write it to disk.
                await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);

                await fileStream.FlushAsync();
            }
        }
コード例 #10
0
        public async Task SaveAsync()
        {
            this.SaveApplicationState();
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(SessionStateFileName, CreationCollisionOption.ReplaceExisting);

            var bytes = this.SerializeState(this.states);

            using (var sessionData = new MemoryStream(bytes))
            {
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    var provider = new DataProtectionProvider("LOCAL=user");

                    await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);

                    await fileStream.FlushAsync();
                }
            }
        }
        /// <summary>
        /// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
        /// registered with <see cref="RegisterFrame"/> will also preserve their current
        /// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
        /// to save its state.
        /// </summary>
        /// <returns>An asynchronous task that reflects when session state has been saved.</returns>
        public async Task SaveAsync()
        {
            try
            {
                // Save the navigation state for all registered frames
                foreach (var weakFrameReference in _registeredFrames)
                {
                    IFrameFacade frame;
                    if (weakFrameReference.TryGetTarget(out frame))
                    {
                        SaveFrameNavigationState(frame);
                    }
                }

                // Serialize the session state synchronously to avoid asynchronous access to shared
                // state
                MemoryStream           sessionData = new MemoryStream();
                DataContractSerializer serializer  = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes);
                serializer.WriteObject(sessionData, _sessionState);

                // Get an output stream for the SessionState file and write the state asynchronously
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(Constants.SessionStateFileName, CreationCollisionOption.ReplaceExisting);

                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    sessionData.Seek(0, SeekOrigin.Begin);
                    var provider = new DataProtectionProvider("LOCAL=user");

                    // Encrypt the session data and write it to disk.
                    await provider.ProtectStreamAsync(sessionData.AsInputStream(), fileStream);

                    await fileStream.FlushAsync();
                }
            }
            catch (Exception e)
            {
                throw new SessionStateServiceException(e);
            }
        }
コード例 #12
0
        public async void SampleDataProtectionStream(String descriptor)
        {
            EncryptDecryptText.Text += "*** Sample Stream Data Protection for " + descriptor + " ***\n";

            IBuffer    data = CryptographicBuffer.GenerateRandom(10000);
            DataReader reader1, reader2;
            IBuffer    buff1, buff2;

            DataProtectionProvider     Provider     = new DataProtectionProvider(descriptor);
            InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream();

            //Populate the new memory stream
            IOutputStream outputStream              = originalData.GetOutputStreamAt(0);
            DataWriter    writer                    = new DataWriter(outputStream);

            writer.WriteBuffer(data);
            await writer.StoreAsync();

            await outputStream.FlushAsync();

            //open new memory stream for read
            IInputStream source = originalData.GetInputStreamAt(0);

            //Open the output memory stream
            InMemoryRandomAccessStream protectedData = new InMemoryRandomAccessStream();
            IOutputStream dest = protectedData.GetOutputStreamAt(0);

            // Protect
            await Provider.ProtectStreamAsync(source, dest);

            //Flush the output
            if (await dest.FlushAsync())
            {
                EncryptDecryptText.Text += "    Protected output was successfully flushed\n";
            }


            //Verify the protected data does not match the original
            reader1 = new DataReader(originalData.GetInputStreamAt(0));
            reader2 = new DataReader(protectedData.GetInputStreamAt(0));

            await reader1.LoadAsync((uint)originalData.Size);

            await reader2.LoadAsync((uint)protectedData.Size);

            EncryptDecryptText.Text += "    Size of original stream:  " + originalData.Size + "\n";
            EncryptDecryptText.Text += "    Size of protected stream:  " + protectedData.Size + "\n";

            if (originalData.Size == protectedData.Size)
            {
                buff1 = reader1.ReadBuffer((uint)originalData.Size);
                buff2 = reader2.ReadBuffer((uint)protectedData.Size);
                if (CryptographicBuffer.Compare(buff1, buff2))
                {
                    EncryptDecryptText.Text += "ProtectStreamAsync returned unprotected data";
                    return;
                }
            }

            EncryptDecryptText.Text += "    Stream Compare completed.  Streams did not match.\n";

            source = protectedData.GetInputStreamAt(0);

            InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();

            dest = unprotectedData.GetOutputStreamAt(0);

            // Unprotect
            DataProtectionProvider Provider2 = new DataProtectionProvider();
            await Provider2.UnprotectStreamAsync(source, dest);

            if (await dest.FlushAsync())
            {
                EncryptDecryptText.Text += "    Unprotected output was successfully flushed\n";
            }

            //Verify the unprotected data does match the original
            reader1 = new DataReader(originalData.GetInputStreamAt(0));
            reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));

            await reader1.LoadAsync((uint)originalData.Size);

            await reader2.LoadAsync((uint)unprotectedData.Size);

            EncryptDecryptText.Text += "    Size of original stream:  " + originalData.Size + "\n";
            EncryptDecryptText.Text += "    Size of unprotected stream:  " + unprotectedData.Size + "\n";

            buff1 = reader1.ReadBuffer((uint)originalData.Size);
            buff2 = reader2.ReadBuffer((uint)unprotectedData.Size);
            if (!CryptographicBuffer.Compare(buff1, buff2))
            {
                EncryptDecryptText.Text += "UnrotectStreamAsync did not return expected data";
                return;
            }

            EncryptDecryptText.Text += "*** Done!\n";
        }