Наследование: IDataProtectionProvider
Пример #1
0
 public async Task<string> EncryptString(string input) {
     if (input == null) return "";
     var provider = new DataProtectionProvider("LOCAL=user");
     var inputBuffer = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);
     var crypted = await provider.ProtectAsync(inputBuffer);
     return CryptographicBuffer.EncodeToBase64String(crypted);
 }
 public IObservable<byte[]> DecryptBlock(byte[] block)
 {
     // Do not include a protectionDescriptor
     // http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.dataprotection.dataprotectionprovider.unprotectasync.aspx
     var dpapi = new DataProtectionProvider();
     return dpapi.UnprotectAsync(block.AsBuffer()).ToObservable().Select(b => b.ToArray());
 }
Пример #3
0
        /// <summary>Get the value of a local setting.</summary>
        /// <param name="name">The name of the setting.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <param name="isEncrypted">Is the setting encrypted.</param>
        /// <returns>The value of the setting if available, or the default value.</returns>
        public static async Task<string> GetLocalSettingAsync(string name, string defaultValue = "", bool isEncrypted = false)
        {
            object value = ApplicationData.Current.LocalSettings.Values[name];
            if (value == null)
            {
                return defaultValue;
            }

            if (isEncrypted)
            {
                try
                {
                    var dpp = new DataProtectionProvider();
                    var decrypted = await dpp.UnprotectAsync(CryptographicBuffer.DecodeFromBase64String(value.ToString()));

                    return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted);
                }
                catch
                {
                    return defaultValue;
                }
            }
            else
            {
                return value.ToString();
            }
        }
        /// <summary>
        /// Implementation of Load from storage for Windows Store.
        /// </summary>
        protected async Task<byte[]> LoadDataAsync()
        {
            try
            {
                // find the storage file
                var localFolder = ApplicationData.Current.LocalFolder;

                var storageFile = await localFolder.GetFileAsync(StorageFile);

                // read the data. It will be encrypted data
                IBuffer buffProtected = await FileIO.ReadBufferAsync(storageFile);
                DataProtectionProvider provider = new DataProtectionProvider();

                // decrypt the data
                IBuffer clearBuffer = await provider.UnprotectAsync(buffProtected);

                // convert it to byte array
                byte[] clearBytes = new byte[clearBuffer.Length];
                CryptographicBuffer.CopyToByteArray(clearBuffer, out clearBytes);

                return clearBytes;
            }
            catch (Exception)
            {
                return null;
            }
        }
        public async Task<string> UnprotectAsync(byte[] data, string key)
        {
            var provider = new DataProtectionProvider(key);
            var buffProtected = CryptographicBuffer.CreateFromByteArray(data);
            var buffUnprotected = await provider.UnprotectAsync(buffProtected);

            return CryptographicBuffer.ConvertBinaryToString(Encoding, buffUnprotected);
        }
Пример #6
0
        /// <summary>
        /// Encrypt an input stream and output to another stream
        /// </summary>
        /// <param name="inStream"></param>
        /// <param name="outStream"></param>
        /// <param name="userDescriptor"></param>
        /// <returns></returns>
        public static async Task ProtectStreamToStream(IInputStream inStream, IOutputStream outStream, string userDescriptor)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor);

            await Provider.ProtectStreamAsync(inStream, outStream);

        }
Пример #7
0
        /// <summary>
        /// Decrypt an input stream and output to another stream
        /// </summary>
        /// <param name="readStream"></param>
        /// <param name="outStream"></param>
        /// <returns></returns>
        public static async Task DecryptStream(IInputStream readStream, IOutputStream outStream, string userDescriptor)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor);

            await Provider.UnprotectStreamAsync(readStream, outStream);     // decrypt and output

            return;
        }
Пример #8
0
		public static async Task<string> GeneralRevil(this string clearText, string scope = "LOCAL=user")
		{
			if ((clearText == null) || (scope == null))
				return null;
			var clearBuffer = CryptographicBuffer.ConvertStringToBinary(clearText, BinaryStringEncoding.Utf8);
			var provider = new DataProtectionProvider(scope);
			var encryptedBuffer = await provider.ProtectAsync(clearBuffer);
			return CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
		}
Пример #9
0
		public static async Task<string> SaylaMass(this string encryptedText)
		{
			if (encryptedText == null)
				return null;
			var encryptedBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedText);
			var provider = new DataProtectionProvider();
			var clearBuffer = await provider.UnprotectAsync(encryptedBuffer);
			return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, clearBuffer);
		}
        public async Task<byte[]> ProtectAsync(string data, string key)
        {
            var provider = new DataProtectionProvider(key);
            var buffMessage = CryptographicBuffer.ConvertStringToBinary(data, Encoding);
            var buffProtected = await provider.ProtectAsync(buffMessage);

            var buffer = new byte[buffProtected.Length];
            CryptographicBuffer.CopyToByteArray(buffProtected, out buffer);
            return buffer;
        }
        public static async Task<string> UnprotectAsync(this string encryptedText)
        {
            if (encryptedText == null)
                throw new ArgumentNullException("encryptedText");

            var encryptedBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedText);
            var provider = new DataProtectionProvider();
            var clearBuffer = await provider.UnprotectAsync(encryptedBuffer);
            return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, clearBuffer);
        }
        public async Task<IBuffer> ProtectDataAsync(
            byte[] data,
            String strDescriptor)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(strDescriptor);

            // Encrypt the message.
            return await Provider.ProtectAsync(CryptographicBuffer.CreateFromByteArray(data));
        }
        public async Task<IBuffer> EncryptMessage(string message)
        {
            var dataProtectionProvider = new DataProtectionProvider("LOCAL=user");

            // Encode the plaintext input message to a buffer.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);

            // Encrypt the message.
            IBuffer buffProtected = await dataProtectionProvider.ProtectAsync(buffMsg);
            return buffProtected;
        }
Пример #14
0
        protected override IObservable<byte[]> BeforeWriteToDiskFilter(byte[] data, IScheduler scheduler)
        {
            if (data.Length == 0)
            {
                return Observable.Return(data);
            }

            var dpapi = new DataProtectionProvider("LOCAL=user");
            return dpapi.ProtectAsync(data.AsBuffer()).ToObservable()
                .Select(x => x.ToArray());
        }
Пример #15
0
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="message">String to encrypt</param>
        /// <returns>Encrypted string</returns>
        public async Task<string> EncryptAsync(string message)
        {
            if (string.IsNullOrEmpty(message))
                return message;

            string base64message = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(message));
            IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(base64message);
            DataProtectionProvider protectedData = new DataProtectionProvider("LOCAL=user");
            IBuffer encryptedBuffer = await protectedData.ProtectAsync(buffer);
            return CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
        }
Пример #16
0
        protected override IObservable<byte[]> AfterReadFromDiskFilter(byte[] data, IScheduler scheduler)
        {
            if (data.Length == 0)
            {
                return Observable.Return(data);
            }

            var dpapi = new DataProtectionProvider();
            return dpapi.UnprotectAsync(data.AsBuffer()).ToObservable()
                .Select(x => x.ToArray());
        }
        public async Task<IStorageFile> SaveAccessToken(string token, string name)
        {
            DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=user");
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(token, ENCODING);
            IBuffer buffProtected = await Provider.ProtectAsync(buffMsg);

            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file = await local.CreateFileAsync(name + ".txt", CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteBufferAsync(file, buffProtected);
            return file;
        }
Пример #18
0
        public async Task<IBuffer> UnProtectAsync()
        {
            DataProtectionProvider Provider = new DataProtectionProvider();

            // Encrypt the message.
            IBuffer buffProtected = await Provider.UnprotectAsync(this.Buffer);

            // Execution of the SampleProtectAsync function resumes here
            // after the awaited task (Provider.ProtectAsync) completes.
            return buffProtected;
        }
        public async Task<string> ReadAccessToken(string name)
        {
            StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
            var file = await local.GetFileAsync(name + ".txt");

            var text = await FileIO.ReadBufferAsync(file);

            DataProtectionProvider Provider = new DataProtectionProvider();
            IBuffer buffUnprotected = await Provider.UnprotectAsync(text);

            return CryptographicBuffer.ConvertBinaryToString(ENCODING, buffUnprotected);
        }
Пример #20
0
        /// <summary>
        /// Decrypts an encrypted string
        /// </summary>
        /// <param name="message">String to decrypt</param>
        /// <returns>Decrypted string inside the encrypted param string</returns>
        public async Task<string> DecryptAsync(string message)
        {
            if (string.IsNullOrEmpty(message))
                return message;

            IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(message);
            var protectedData = new DataProtectionProvider("LOCAL=user");
            var decryptedBuffer = await protectedData.UnprotectAsync(buffer);
            string base64message = CryptographicBuffer.EncodeToBase64String(decryptedBuffer);
            byte[] msgContents = Convert.FromBase64String(base64message);
            return System.Text.Encoding.UTF8.GetString(msgContents, 0, msgContents.Length);
        }
        public static async Task<string> ProtectAsync(string clearText, string scope = "LOCAL=user")
        {
            if (clearText == null)
                throw new ArgumentNullException("clearText");
            if (scope == null)
                throw new ArgumentNullException("scope");

            var clearBuffer = CryptographicBuffer.ConvertStringToBinary(clearText, BinaryStringEncoding.Utf8);
            var provider = new DataProtectionProvider(scope);
            var encryptedBuffer = await provider.ProtectAsync(clearBuffer);
            return CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
        }
        public async Task<string> DecryptMessage(IBuffer buffer)
        {
            if (buffer == null) return string.Empty;

            var dataProtectionProvider = new DataProtectionProvider("LOCAL=user");

            // Decrypt the message
            IBuffer buffUnProtected = await dataProtectionProvider.UnprotectAsync(buffer);

            // Decode the buffer to a plaintext message.
            string message = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUnProtected);
            return message;
        }
Пример #23
0
        public async static Task<string> UnProtect(string data)
        {
            DataProtectionProvider provider;
            IBuffer unprotectedBuffer;
            IBuffer protectedBuffer;

            if (data == null)
                return null;
            provider = new DataProtectionProvider(descriptor);
            protectedBuffer = CryptographicBuffer.DecodeFromBase64String(data);
            unprotectedBuffer = await provider.UnprotectAsync(protectedBuffer).AsTask().ConfigureAwait(false);
            return CryptographicBuffer.ConvertBinaryToString(encoding, unprotectedBuffer);
        }
Пример #24
0
        public async static Task<IBuffer> ProtectAsync(
            IBuffer unprotectedBuffer)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider("LOCAL=machine");

            // Encrypt the message.
            IBuffer buffProtected = await Provider.ProtectAsync(unprotectedBuffer);

            // Execution of the SampleProtectAsync function resumes here
            // after the awaited task (Provider.ProtectAsync) completes.
            return buffProtected;
        }
Пример #25
0
        /// <summary>
        /// Encrypt a string and limit access to the LOCAL=user
        /// </summary>
        /// <param name="message"></param>
        /// <param name="userDescriptor"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task<IBuffer> ProtectString(string message, string userDescriptor)
        {
            // Create a DataProtectionProvider object for the specified descriptor.
            DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor);

            // Encode the plaintext input message to a buffer.
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;  // same as the decrypting function
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(message, encoding);

            // Encrypt the message.
            IBuffer buffProtected = await Provider.ProtectAsync(buffMsg);   // wait

            return buffProtected;   // Return encrypted message
        }
Пример #26
0
        public async Task<string> Decrypt(IBuffer buffProtected, BinaryStringEncoding encoding)
        {
            try
            {
                // Create a DataProtectionProvider object.
                DataProtectionProvider Provider = new DataProtectionProvider();

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

                // Create a random access stream to contain the decrypted data.
                InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream();

                // Retrieve an IOutputStream object and fill it with the input (encrypted) data.
                IOutputStream outputStream = inputData.GetOutputStreamAt(0);
                DataWriter writer = new DataWriter(outputStream);
                writer.WriteBuffer(buffProtected);
                await writer.StoreAsync();
                await outputStream.FlushAsync();

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

                // Retrieve an IOutputStream object and fill it with decrypted data.
                IOutputStream dest = unprotectedData.GetOutputStreamAt(0);
                await Provider.UnprotectStreamAsync(source, dest);
                await dest.FlushAsync();

                // Write the decrypted data to an IBuffer object.
                DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0));
                await reader2.LoadAsync((uint)unprotectedData.Size);
                IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size);

                // Convert the IBuffer object to a string using the same encoding that was
                // used previously to conver the plaintext string (before encryption) to an
                // IBuffer object.
                String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData);

                // Return the decrypted data.
                return strUnprotected;
            }
            catch (Exception ex)
            {
                App.Telemetry.TrackException(ex);
                return "";

            }

        }
Пример #27
0
        public async static Task<string> Protect(string data)
        {
            DataProtectionProvider provider;
            IBuffer unprotectedBuffer;
            IBuffer protectedBuffer;

            if (data == null)
                return null;
            provider = new DataProtectionProvider(descriptor);
            unprotectedBuffer = CryptographicBuffer.ConvertStringToBinary(data, encoding);
            if (unprotectedBuffer == null)
                return null;
            protectedBuffer = await provider.ProtectAsync(unprotectedBuffer).AsTask().ConfigureAwait(false);
            return CryptographicBuffer.EncodeToBase64String(protectedBuffer);
        }
Пример #28
0
        /// <summary>Sets the value of a local setting.</summary>
        /// <param name="name">The name of the setting.</param>
        /// <param name="value">The value to set.</param>
        /// <param name="isEncrypted">Indicates if the value should be encrypted.</param>
        public static async void SetLocalSettingAsync(string name, string value, bool isEncrypted = false)
        {
            if (isEncrypted)
            {
                var dpp = new DataProtectionProvider("LOCAL=user");
                var encrypted = await dpp.ProtectAsync(CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8));
                var base64 = CryptographicBuffer.EncodeToBase64String(encrypted);

                ApplicationData.Current.LocalSettings.Values[name] = base64;
            }
            else
            {
                ApplicationData.Current.LocalSettings.Values[name] = value;
            }
        }
        /// <summary>
        /// Implementation of Save to storage for Windows Store, WP8.1 and UWP
        /// </summary>
        private async Task SaveDataAsync(byte[] clearBytes)
        {
            // create the storage file
            var localFolder = ApplicationData.Current.LocalFolder;
            var storageFile = await localFolder.CreateFileAsync(StorageFile, CreationCollisionOption.ReplaceExisting);

            // create buffer from byte array
            IBuffer clearBuffer = CryptographicBuffer.CreateFromByteArray(clearBytes);

            // Encrypt the buffer.
            var provider = new DataProtectionProvider(DPProvider);
            IBuffer protectedBuffer = await provider.ProtectAsync(clearBuffer);

            // save to storage
            await FileIO.WriteBufferAsync(storageFile, protectedBuffer);
        }
Пример #30
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();
                }
            }
        }