public ReadBuffer ( ) : Windows.Storage.Streams.IBuffer | ||
Результат | Windows.Storage.Streams.IBuffer |
public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(Stream source) { Stream streamToConvert = null; if (!source.CanRead) throw new Exception("The source cannot be read."); if (!source.CanSeek) { var memStream = new MemoryStream(); await source.CopyToAsync(memStream); streamToConvert = memStream; } else { streamToConvert = source; } var reader = new DataReader(streamToConvert.AsInputStream()); streamToConvert.Position = 0; await reader.LoadAsync((uint) streamToConvert.Length); var buffer = reader.ReadBuffer((uint) streamToConvert.Length); var randomAccessStream = new InMemoryRandomAccessStream(); var outputStream = randomAccessStream.GetOutputStreamAt(0); await outputStream.WriteAsync(buffer); await outputStream.FlushAsync(); return randomAccessStream; }
public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream) { Stream streamToConvert = null; if (!stream.CanRead) { throw new Exception("Cannot read the source stream-"); } if (!stream.CanSeek) { MemoryStream memoryStream = new MemoryStream(); await stream.CopyToAsync(memoryStream); streamToConvert = memoryStream; } else { streamToConvert = stream; } DataReader dataReader = new DataReader(streamToConvert.AsInputStream()); streamToConvert.Position = 0; await dataReader.LoadAsync((uint)streamToConvert.Length); IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length); InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0); await outputstream.WriteAsync(buffer); await outputstream.FlushAsync(); return randomAccessStream; }
private async void ProtectData() { if (await storageFolder.TryGetItemAsync("config.txt") != null) // if user file exists { configSF = await storageFolder.GetFileAsync("config.txt"); var stream = await configSF.OpenAsync(Windows.Storage.FileAccessMode.Read); ulong size = stream.Size; using (var inputStream = stream.GetInputStreamAt(0)) { using (var dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); IBuffer textBuffer = dataReader.ReadBuffer(numBytesLoaded); string text = await SampleDataUnprotectStream(textBuffer, encoding); if (text.Length != 0 && text.IndexOf(" ") > 0) { Username.Text = text.Substring(0, text.IndexOf(" ")); Password.Password = text.Substring(text.IndexOf(" ") + 1); saveLogin = true; SavePasswordCheckBox.IsChecked = true; } } } } }
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 ""; } }
public async Task SaveBitmapAsync(string albumFolder, uint size, string songPath) { var songFile = await StorageFile.GetFileFromPathAsync(songPath); using (var thumbnail = await songFile.GetThumbnailAsync(ThumbnailMode.MusicView, size) ?? await songFile.GetThumbnailAsync(ThumbnailMode.VideosView, size)) { if (thumbnail == null) return; var reader = new DataReader(thumbnail); var fileLength = (uint)thumbnail.Size; await reader.LoadAsync(fileLength); var buffer = reader.ReadBuffer(fileLength); var memStream = new InMemoryRandomAccessStream(); await memStream.WriteAsync(buffer); await memStream.FlushAsync(); memStream.Seek(0); await ApplicationData.Current.LocalFolder.CreateFolderAsync(AlbumArtFolderName(albumFolder), CreationCollisionOption.OpenIfExists); var albumArtFileName = AlbumArtFileName(albumFolder, size); var outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(albumArtFileName, CreationCollisionOption.ReplaceExisting); // http://social.msdn.microsoft.com/Forums/windowsapps/en-US/1dda3a15-d299-40e0-b668-ec690a683f6e/how-to-resize-an-image-as-storagefile?forum=winappswithcsharp var decoder = await BitmapDecoder.CreateAsync(memStream); var transform = new BitmapTransform { ScaledHeight = size, ScaledWidth = size }; var pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); using (var destinationStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, size, size, 96, 96, pixelData.DetachPixelData()); await encoder.FlushAsync(); } } }
/// <summary> /// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents. /// </summary> /// <param name="stream">Content to be written to file</param> /// <param name="filename">Name of the file to be written in cache location</param> private static async Task WriteFileAsync(Stream stream, string filename) { // Prepare output file stream StorageFolder parent = GetCacheFolder(); StorageFile file = null; try { file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); } catch (Exception) { } if (file != null && stream != null) { // Prepare input image stream IInputStream inStream = stream.AsInputStream(); DataReader reader = new DataReader(inStream); IRandomAccessStream fileStream = null; try { fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); // Buffered write to file await reader.LoadAsync(1024); while (reader.UnconsumedBufferLength > 0) { await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength)); await reader.LoadAsync(1024); } } catch (Exception) { } finally { if (fileStream != null) { fileStream.FlushAsync(); } } inStream.Dispose(); } }
private async static Task <bool> SaveStreamTo3MF(Windows.Storage.Streams.IRandomAccessStream stream) { // set back stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { var dataLoad = await dataReader.LoadAsync((uint)stream.Size); if (dataLoad > 0) { var buffer = dataReader.ReadBuffer((uint)stream.Size); StorageFolder localFolder = ApplicationData.Current.LocalFolder; var outputfile = await localFolder.CreateFileAsync("output.3mf", CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteBufferAsync(outputfile, buffer); var options = new Windows.System.LauncherOptions(); options.TargetApplicationPackageFamilyName = "Microsoft.3DBuilder_8wekyb3d8bbwe"; } } return(true); }
private async void UnprotectAsyncBuffer_Click(object sender, RoutedEventArgs e) { string outputStr = ""; if (m_protectedStream != null) { IInputStream source = m_protectedStream.GetInputStreamAt(0); m_unprotectedStream = new InMemoryRandomAccessStream(); await DataProtectionManager.UnprotectStreamAsync(source, m_unprotectedStream ); var unprotectedReader = new DataReader(m_unprotectedStream.GetInputStreamAt(0)); await unprotectedReader.LoadAsync((uint)m_unprotectedStream.Size); IBuffer unprotectedStreamBuffer = unprotectedReader.ReadBuffer((uint)m_unprotectedStream.Size); outputStr += "\n UnProtected Stream buffer:" + CryptographicBuffer.EncodeToHexString(unprotectedStreamBuffer); rootPage.NotifyUser(outputStr, NotifyType.StatusMessage); } else { rootPage.NotifyUser("Please protect a stream to unprotect", NotifyType.ErrorMessage); } }
public async Task<bool> DownloadFileAsync(string ftpFile, string localFile, Boolean resume) { CheckLoggedIn(); var response = await ExecuteAsync("TYPE I"); response.CheckReturnCode(200); Debug.WriteLine("Downloading file " + ftpFile + " from " + HostName + "/" + WorkingDirectory, "FtpClient"); if (string.IsNullOrEmpty(localFile)) { localFile = ftpFile; } var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(localFile, CreationCollisionOption.OpenIfExists); var tempStream = await tempFile.OpenStreamForWriteAsync(); StreamSocket dataSocket = await OpenSocketForTransferAsync(); ulong resumeOffset = 0; if (resume) { var prop = await tempFile.GetBasicPropertiesAsync(); resumeOffset = prop.Size; if (resumeOffset > 0) { response = await ExecuteAsync("REST " + resumeOffset); if (response.ReturnCode != 350) { resumeOffset = 0; Debug.WriteLine("Resuming not supported:" + response.Message, "FtpClient"); } else { Debug.WriteLine("Resuming at offset " + resumeOffset, "FtpClient"); tempStream.Seek(Convert.ToInt64(resumeOffset), SeekOrigin.Begin); } } } response = await ExecuteAsync("RETR " + ftpFile); response.CheckReturnCode(150, 125); var reader = new DataReader(dataSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; var writer = new DataWriter(tempStream.AsOutputStream()); DateTime timeout = DateTime.Now.AddSeconds(TimeOut); while (timeout > DateTime.Now) { var count = await reader.LoadAsync(BUFFER_SIZE); var bytes = reader.ReadBuffer(count); writer.WriteBuffer(bytes); await writer.StoreAsync(); if (count < BUFFER_SIZE) { break; } } await tempStream.FlushAsync(); dataSocket.Dispose(); response = await ReadResponseAsync(); response.CheckReturnCode(226, 250); var props = await tempFile.GetBasicPropertiesAsync(); var tempSize = props.Size; var size = await GetFileSizeAsync(ftpFile); if (tempSize != size) return false; var destFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(localFile, CreationCollisionOption.ReplaceExisting); var destStream = await destFile.OpenStreamForWriteAsync(); tempStream.Seek(0, SeekOrigin.Begin); await tempStream.CopyToAsync(destStream); await destStream.FlushAsync(); await tempFile.DeleteAsync(StorageDeleteOption.PermanentDelete); return true; }
private static async Task<int> DoReadAsync(IInputStream stream, byte[] buffer, int offset, int count) { try { using (var reader = new DataReader(stream)) { await reader.LoadAsync((uint)count).AsTask().ConfigureAwait(false); var length = Math.Min((int)reader.UnconsumedBufferLength, count); reader.ReadBuffer((uint)length).CopyTo(0, buffer, offset, length); reader.DetachStream(); return length; } } catch { return 0; } }
private async Task<StorageFile> SaveTemporaryPhotoAsync(FilteredPhotoModel photo) { var filename = Application.Current.Resources["PhotoSaveTemporaryFilename"] as string; var folder = ApplicationData.Current.TemporaryFolder; var task = folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting).AsTask(); task.Wait(); var file = task.Result; CachedFileManager.DeferUpdates(file); using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) using (var photoStream = await photo.GetFilteredPhotoAsync()) using (var reader = new DataReader(photoStream)) using (var writer = new DataWriter(fileStream)) { await reader.LoadAsync((uint)photoStream.Size); var buffer = reader.ReadBuffer((uint)photoStream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); } var status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { return file; } else { return null; } }
private async Task CalculateHash( IDispatcher d, HashProgress notifier) { if (notifier != null) { Action action = () => notifier(Path, 0); if (d == null) { action(); } else { d.Execute(action); } } //TODO - exception handling StorageFile file = await GetFromRoot(m_path, m_root); int num_chunks = (int) (GetSize()/Chunker.chunk_size) + 1; int hash_size = num_chunks*32; float current_chunk = 0; var hash_builder = new StringBuilder(hash_size); m_hash = ""; var chunker = new Chunker(GetSize()); foreach (Chunk chunk in chunker.GetChunks()) { using (IRandomAccessStream inputStream = await file.OpenAsync(FileAccessMode.Read)) { using (var dataReader = new DataReader(inputStream.GetInputStreamAt(chunk.Start))) { await dataReader.LoadAsync(chunk.Length); IBuffer buf = dataReader.ReadBuffer(chunk.Length); IBuffer hashed = m_alg.HashData(buf); hash_builder.Append(CryptographicBuffer.EncodeToHexString(hashed)); } } current_chunk++; if (notifier != null) { float percent_done = current_chunk/num_chunks; Action action = () => notifier(Path, percent_done*100); if (d == null) { action(); } else { d.Execute(action); } } } m_hash = hash_builder.ToString(); if (hash_size > 32) //hash the hash { // Convert the string to UTF8 binary data. IBuffer hashbuf = CryptographicBuffer.ConvertStringToBinary(m_hash, BinaryStringEncoding.Utf8); IBuffer hashed = m_alg.HashData(hashbuf); m_hash = CryptographicBuffer.EncodeToHexString(hashed); } if (notifier != null) { Action action = () => notifier(Path, 100); if (d == null) { action(); } else { d.Execute(action); } } }
public async Task UsingDataWriter() { var inMem = new InMemoryRandomAccessStream(); var datawriter = new DataWriter(inMem); var starterBytes = CryptographicBuffer.GenerateRandom(32).AsBytes(); var mStream = CryptographicBuffer.GenerateRandom(1024 * 1024).AsBytes(); MemoryStream outStream = new System.IO.MemoryStream(); var tinyStream = ConfigureStream(outStream, PwCompressionAlgorithm.GZip, true); await tinyStream.WriteAsync(starterBytes, 0, starterBytes.Length); await tinyStream.WriteAsync(mStream, 0, mStream.Length); tinyStream.Dispose(); byte[] bb = outStream.ToArray(); var source = bb.AsBuffer(); var aesKey = CryptographicBuffer.GenerateRandom(32); var iv = CryptographicBuffer.GenerateRandom(16); var encrypted = EncryptDatabase(source, aesKey, iv); CollectionAssert.AreNotEqual(mStream, encrypted.AsBytes()); datawriter.WriteBuffer(encrypted); await datawriter.StoreAsync(); datawriter.DetachStream(); datawriter.Dispose(); var i = inMem.GetInputStreamAt(0); var datareader = new DataReader(i); datareader.ByteOrder = ByteOrder.LittleEndian; await datareader.LoadAsync((uint)inMem.Size); var fromStrea = datareader.ReadBuffer(datareader.UnconsumedBufferLength); var decryped = DecryptDatabase(fromStrea, aesKey, iv); Stream bigStream = ConfigureStream(new MemoryStream(decryped.AsBytes()), PwCompressionAlgorithm.GZip, false); System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream(); bigStream.CopyTo(bigStreamOut); var buffer1 = CryptographicBuffer.CreateFromByteArray(bigStreamOut.ToArray()); var reader = DataReader.FromBuffer(buffer1); var x = reader.ReadBuffer(32).AsBytes(); CollectionAssert.AreEqual(starterBytes, x); }
private async void ProtectStreamAsync_Click(object sender, RoutedEventArgs e) { string outputStr = ""; Byte[] byteStream = { 1, 2, 3, 4, 5 }; InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); IOutputStream outputStream = randomAccessStream.GetOutputStreamAt(0); var writer = new DataWriter(outputStream); writer.WriteBytes(byteStream); await writer.StoreAsync(); IInputStream source = randomAccessStream.GetInputStreamAt(0); m_protectedStream = new InMemoryRandomAccessStream(); IOutputStream destination = m_protectedStream.GetOutputStreamAt(0); await DataProtectionManager.ProtectStreamAsync(source, Scenario1.m_enterpriseId, destination); var reader = new DataReader(m_protectedStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)m_protectedStream.Size); IBuffer protectedStreamBuffer = reader.ReadBuffer((uint)m_protectedStream.Size); outputStr += "\n Protected Stream buffer:" + CryptographicBuffer.EncodeToHexString(protectedStreamBuffer); rootPage.NotifyUser(outputStr, NotifyType.StatusMessage); }
public async Task<IStorageFile> ReadFileAsync(StreamSocket socket, StorageFolder folder, string outputFilename = null) { StorageFile file; using (var rw = new DataReader(socket.InputStream)) { // 1. Read the filename length await rw.LoadAsync(sizeof(Int32)); var filenameLength = (uint)rw.ReadInt32(); // 2. Read the filename await rw.LoadAsync(filenameLength); var originalFilename = rw.ReadString(filenameLength); if (outputFilename == null) { outputFilename = originalFilename; } //3. Read the file length await rw.LoadAsync(sizeof(UInt64)); var fileLength = rw.ReadUInt64(); // 4. Reading file var buffer = rw.ReadBuffer((uint)fileLength); file = await ApplicationData.Current.LocalFolder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting); await FileIO.WriteBufferAsync(file, buffer); //using (var memStream = await DownloadFile(rw, fileLength)) //{ // file = await folder.CreateFileAsync(outputFilename, CreationCollisionOption.ReplaceExisting); // using (var fileStream1 = await file.OpenAsync(FileAccessMode.ReadWrite)) // { // await RandomAccessStream.CopyAndCloseAsync(memStream.GetInputStreamAt(0), fileStream1.GetOutputStreamAt(0)); // } // rw.DetachStream(); //} } return file; }
private static async Task<StorageFile> SavePhotoAsync(FilteredPhotoModel photo, StorageFile file) { CachedFileManager.DeferUpdates(file); using (var fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) using (var photoStream = await photo.GetFilteredPhotoAsync()) using (var reader = new DataReader(photoStream)) using (var writer = new DataWriter(fileStream)) { await reader.LoadAsync((uint)photoStream.Size); var buffer = reader.ReadBuffer((uint)photoStream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); } var status = await CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { return file; } else { return null; } }
public async void mediaalbumart() { try { StorageFile media = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(futurelocation); string filename = "thumbnail" + ".png"; //var ThumbUri = new Uri("ms-appdata:///local/" + filename); // Store the file thumbnail in local applicatin storage using ( StorageItemThumbnail storageItemThumbnail = await media.GetThumbnailAsync(ThumbnailMode.SingleItem, 200, ThumbnailOptions.ResizeThumbnail)) using (IInputStream inputStreamAt = storageItemThumbnail.GetInputStreamAt(0)) using (var dataReader = new DataReader(inputStreamAt)) { uint u = await dataReader.LoadAsync((uint)storageItemThumbnail.Size); IBuffer readBuffer = dataReader.ReadBuffer(u); var tempFolder = ApplicationData.Current.LocalFolder; var imageFile = await tempFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream randomAccessStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite)) using (IOutputStream outputStreamAt = randomAccessStream.GetOutputStreamAt(0)) { await outputStreamAt.WriteAsync(readBuffer); await outputStreamAt.FlushAsync(); } } MediaControl.AlbumArt = new Uri("ms-appdata:///local/" + filename); } catch { // ErrorCorrecting("015"); } }
public async void albumart(StorageFile fil) { using (StorageItemThumbnail storageItemThumbnail = await fil.GetThumbnailAsync(ThumbnailMode.SingleItem, 200, ThumbnailOptions.ResizeThumbnail)) using (IInputStream inputStreamAt = storageItemThumbnail.GetInputStreamAt(0)) using (var dataReader = new DataReader(inputStreamAt)) { uint u = await dataReader.LoadAsync((uint)storageItemThumbnail.Size); IBuffer readBuffer = dataReader.ReadBuffer(u); var tempFolder = ApplicationData.Current.RoamingFolder; try { var imageFile = await tempFolder.CreateFileAsync(fil.DisplayName + ".png", CreationCollisionOption.OpenIfExists); using (IRandomAccessStream randomAccessStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite)) using (IOutputStream outputStreamAt = randomAccessStream.GetOutputStreamAt(0)) { await outputStreamAt.WriteAsync(readBuffer); await outputStreamAt.FlushAsync(); } } catch { // ErrorCorrecting("013"); } } }
public async Task<IBuffer> Encrypt(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; }
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"; }
private async void SavePackage() { rootPage.NotifyUser("", NotifyType.StatusMessage); FileSavePicker savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = ".3mf"; savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add("3MF File", new[] { ".3mf" }); var storageFile = await savePicker.PickSaveFileAsync(); if (storageFile == null) { return; } using (var stream = await currentPackage.SaveAsync()) { stream.Seek(0); using (var dataReader = new DataReader(stream)) { await dataReader.LoadAsync((uint)stream.Size); var buffer = dataReader.ReadBuffer((uint)stream.Size); await FileIO.WriteBufferAsync(storageFile, buffer); } } rootPage.NotifyUser("Saved", NotifyType.StatusMessage); }
private async static Task<bool> SaveStreamTo3MF(Windows.Storage.Streams.IRandomAccessStream stream) { // set back stream.Seek(0); using (var dataReader = new Windows.Storage.Streams.DataReader(stream)) { var dataLoad = await dataReader.LoadAsync((uint)stream.Size); if (dataLoad > 0) { var buffer = dataReader.ReadBuffer((uint)stream.Size); StorageFolder localFolder = ApplicationData.Current.LocalFolder; var outputfile = await localFolder.CreateFileAsync("output.3mf", CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteBufferAsync(outputfile, buffer); var options = new Windows.System.LauncherOptions(); options.TargetApplicationPackageFamilyName = "Microsoft.3DBuilder_8wekyb3d8bbwe"; } } return true; }
private async void OnConnection( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { DataReader reader = new DataReader(args.Socket.InputStream); try { while (true) { // Read first 4 bytes (length of the subsequent string). uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } uint sizeFieldCount1 = await reader.LoadAsync(sizeof(uint)); if (sizeFieldCount1 != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } // Read the string. uint stringLength = reader.ReadUInt32(); uint msgtype = reader.ReadUInt32(); uint actualStringLength = await reader.LoadAsync(stringLength); if (stringLength != actualStringLength) { // The underlying socket was closed before we were able to read the whole data. return; } // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal // the text back to the UI thread. if (msgtype == 1) { readByte = new byte[actualStringLength]; reader.ReadBytes(readByte); receive_byte_flag = 1; } else if (msgtype == 2) { stringtemp = reader.ReadString(actualStringLength); receive_client_ip = 1; } else if (msgtype == 3) { receiverbuf = reader.ReadBuffer(actualStringLength); receive_buf_flag = 1; } } } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } } }
public void Recieve(IAsyncAction operation) { while (realm.listenSocket) { Task.Delay(1); //if (clientSocket.Available > 0) { DataReader reader = new DataReader(clientSocket.InputStream); var size = reader.UnconsumedBufferLength; DataBuffer = new byte[size]; var buff = reader.ReadBuffer(size); CryptographicBuffer.CopyToByteArray(buff, out DataBuffer); HandleRealmData(DataBuffer); } } clientSocket.Dispose(); }
public static async Task<string> Recive(StreamSocket streamSocket, List<string> orstarts, List<string> orends, List<string> andstarts, List<string> andends) { string returnString = string.Empty; try { using (var dataReader = new DataReader(streamSocket.InputStream)) { dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; dataReader.InputStreamOptions = InputStreamOptions.Partial; var end = false; while (!end && await dataReader.LoadAsync(64000) != 0) { string readString; var buffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength); using (var dr = DataReader.FromBuffer(buffer)) { var bytes1251 = new Byte[buffer.Length]; dr.ReadBytes(bytes1251); readString = Encoding.GetEncoding("UTF-8").GetString(bytes1251, 0, bytes1251.Length); } if (!string.IsNullOrEmpty(readString)) returnString += readString; if (readString == null) { end = true; } else if (orstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null) { end = true; } else if (orends.FirstOrDefault(o => returnString.EndsWith(o)) != null) { end = true; } else if (andstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null && andends.FirstOrDefault(o => returnString.EndsWith(o)) != null) { end = true; } } dataReader.DetachStream(); } } catch(Exception ex) { Debug.WriteLine(ex.Message); returnString = string.Empty; } return returnString; }
/// <summary> /// Reads the specified hashed block stream into a memory stream. /// </summary> /// <param name="input">The hashed block stream.</param> /// <returns>The de-hashed stream.</returns> public static async Task<Stream> Read(IInputStream input) { if (input == null) throw new ArgumentNullException("input"); var blockIndex = 0; var result = new MemoryStream(); var hash = WindowsRuntimeBuffer.Create(32); var reader = new DataReader(input) { ByteOrder = ByteOrder.LittleEndian, }; var sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256); try { while (true) { // Detect end of file var read = await reader.LoadAsync(4); if (read == 0) break; // Verify block index var index = reader.ReadInt32(); if (index != blockIndex) { throw new InvalidDataException(string.Format( "Wrong block ID detected, expected: {0}, actual: {1}", blockIndex, index)); } blockIndex++; // Block hash hash = await input.ReadAsync(hash, 32); if (hash.Length != 32) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } read = await reader.LoadAsync(4); if (read != 4) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Validate block size (< 10MB) var blockSize = reader.ReadInt32(); if (blockSize == 0) { // Terminator block var isTerminator = hash .ToArray() .All(x => x == 0); if (!isTerminator) { throw new InvalidDataException( "Data corruption detected (invalid hash for terminator block)"); } break; } if (0 > blockSize || blockSize > 10485760) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } // Check data truncate var loaded = await reader.LoadAsync((uint)blockSize); if (loaded < blockSize) { throw new InvalidDataException( "Data corruption detected (truncated data)"); } var buffer = reader.ReadBuffer((uint)blockSize); // Verify block integrity var actual = sha.HashData(buffer); if (!CryptographicBuffer.Compare(hash, actual)) { throw new InvalidDataException( "Data corruption detected (content corrupted)"); } await result.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length); } result.Position = 0; return result; } catch { result.Dispose(); throw; } }
private static async Task<string> GetReceiptAsync(string productId) { var encryptedFilename = CipherEncryption(productId); var encodedFileName = Convert.ToBase64String(encryptedFilename.ToArray()); var encodedAndEscapedFilename = encodedFileName.Replace('/', '-'); //var folder = ApplicationData.Current.RoamingFolder; var folder = ApplicationData.Current.RoamingFolder; if (folder == null) return "NoReceipt"; folder = await folder.CreateFolderAsync("Receipts", CreationCollisionOption.OpenIfExists); try { var file = await folder.GetFileAsync(encodedAndEscapedFilename + ".pmd"); var stream = await file.OpenAsync(FileAccessMode.Read); var dataReader = new DataReader(stream.GetInputStreamAt(0)); uint u = await dataReader.LoadAsync((uint)stream.Size); IBuffer buffEncrypted = dataReader.ReadBuffer(u); dataReader.DetachStream(); stream.Dispose(); stream = null; var receipt = CipherDecryption(buffEncrypted); if (productId.Contains("subscritpion") && DownloadManager.ReceiptExpired(receipt)) { await file.DeleteAsync(StorageDeleteOption.PermanentDelete); return "NoReceipt"; } return receipt; } catch (Exception) { return "NoReceipt"; } }
private async Task GetUrlsFromPDF(IRandomAccessStream stream) { using (var dataReader = new DataReader(stream.GetInputStreamAt(0))) { uint u = await dataReader.LoadAsync((uint)stream.Size); IBuffer buffer = dataReader.ReadBuffer(u); GetPDFLinks(buffer); TimeSpan t = new TimeSpan(0, 0, 1); await Task.Delay(t); } }
private async Task<InMemoryRandomAccessStream> DownloadFile(DataReader rw, ulong fileLength) { var memStream = new InMemoryRandomAccessStream(); // Download the file while (memStream.Position < fileLength) { Debug.WriteLine(string.Format("Receiving file...{0}/{1} bytes", memStream.Position, fileLength)); var lenToRead = Math.Min(Constants.BLOCK_SIZE, fileLength - memStream.Position); await rw.LoadAsync((uint)lenToRead); var tempBuff = rw.ReadBuffer((uint)lenToRead); await memStream.WriteAsync(tempBuff); } //var tempBuff = rw.ReadBuffer((uint)fileLength); //await memStream.WriteAsync(tempBuff); return memStream; }
private async Task<IRandomAccessStream> GetThumbnailStreamAsync() { #if DEBUG System.Diagnostics.Debug.WriteLine("GetThumbnailStreamAsync invoked " + this.GetHashCode()); #endif var maximumSide = (int)Windows.UI.Xaml.Application.Current.Resources["ThumbnailSide"]; var orientation = await GetPhotoOrientationAsync(); var orientationValue = orientation.HasValue ? orientation.Value : PhotoOrientation.Unspecified; #if WINDOWS_PHONE_APP // TODO Getting platform thumbnails is currently broken in the WP8.1 preview SDK, // thus generating thumbnails from the large original photos. Change to platform // thumbnails again when platform is live & fine. var size = await GetPhotoResolutionAsync(); using (var stream = await GetPhotoAsync()) { return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue); } #else using (var stream = await _file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView)) { if (stream.ContentType == "image/jpeg") { if (stream.OriginalWidth <= maximumSide || stream.OriginalHeight <= maximumSide) { using (var memoryStream = new InMemoryRandomAccessStream()) { using (var reader = new DataReader(stream)) using (var writer = new DataWriter(memoryStream)) { await reader.LoadAsync((uint)stream.Size); var buffer = reader.ReadBuffer((uint)stream.Size); writer.WriteBuffer(buffer); await writer.StoreAsync(); await writer.FlushAsync(); return memoryStream.CloneStream(); } } } else { return await ResizeStreamAsync(stream, new Size(maximumSide, maximumSide), orientationValue); } } else { using (var preview = await GetPreviewAsync()) { return await ResizeStreamAsync(preview, new Size(maximumSide, maximumSide), orientationValue); } } } #endif }
private void EncryptAllBookDataInDirectory(string extractToDir, CancellationToken token) { Task.WaitAll(Task.Run(async () => { try { var folder = await StorageFolder.GetFolderFromPathAsync(extractToDir); var files = await folder.GetFilesAsync(); foreach (var storageFile in files) { IBuffer encodedBuffer = null; using (var originalFileStream = await storageFile.OpenReadAsync()) { var dataReader = new DataReader(originalFileStream); var streamSize = (uint)originalFileStream.Size; await dataReader.LoadAsync(streamSize); var buffer = dataReader.ReadBuffer(streamSize); encodedBuffer = EncryptionProvider.Encrypt(buffer); } if (encodedBuffer != null) { var fileName = storageFile.Name; var encryptedFile = await folder.CreateFileAsync($"tmp_{fileName}"); using (var encryptedFileStream = await encryptedFile.OpenStreamForWriteAsync()) { var dataToWrite = encodedBuffer.ToArray(); await encryptedFileStream.WriteAsync(dataToWrite, 0, dataToWrite.Length, token); } await storageFile.DeleteAsync(StorageDeleteOption.PermanentDelete); await encryptedFile.RenameAsync(fileName, NameCollisionOption.ReplaceExisting); Debug.WriteLine($"{fileName} ENCRYPTED"); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } }, token)); }
public override async void send_file(String devicename, String bluid, int not) { try { _stopwatch.Start(); PeerFinder.AllowBluetooth = true; PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}"; var peers = await PeerFinder.FindAllPeersAsync(); foreach (var p in peers) { if (p.DisplayName.Equals(devicename)) { _peer_info = p; break; } } _bluetooth_client = new StreamSocket(); if (_peer_info.ServiceName.Equals("")) { await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}"); } else { await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName); } StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.GetFileAsync(this.filepath); IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync(); _length = (uint)filestream.Size; _ibuffer = new Windows.Storage.Streams.Buffer(_length); _datareader = new DataReader(filestream); await _datareader.LoadAsync(_length); _ibuffer = _datareader.ReadBuffer(_length); _datawriter = new DataWriter(_bluetooth_client.OutputStream); _datawriter.WriteBuffer(_ibuffer); await _datawriter.StoreAsync(); filestream.Dispose(); _datareader.Dispose(); _datawriter.Dispose(); _datareader = new DataReader(_bluetooth_client.InputStream); _datareader.InputStreamOptions = InputStreamOptions.Partial; scan_received_acks(); while (true) { uint count = await _datareader.LoadAsync(4); byte[] ack = new byte[count]; _datareader.ReadBytes(ack); _counter_all_acks += BitConverter.ToInt32(ack, 0); if ((uint)_counter_all_acks == _length) break; } _datareader.Dispose(); _bluetooth_client.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _ack_timer.Cancel(); _stopwatch.Stop(); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, devicename); } }