public IBuffer HashData (IBuffer data)
		{
			if (data == null)
				return new byte[HashLength].AsBuffer();

			return this.context.ComputeHash (data.AsStream()).AsBuffer();
		}
Exemple #2
0
    public static string GetHash(Windows.Storage.Streams.IBuffer buffer)
    {
        var algorithm = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm("SHA1");
        var hash      = algorithm.HashData(buffer);

        return(Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(hash));
    }
		/// <summary>
		/// Encodes a buffer to a base64 string.
		/// </summary>
		/// <param name="buffer">Input buffer.</param>
		/// <returns>Base64-encoded output string.</returns>
		public static string EncodeToBase64String( IBuffer buffer )
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");

			return Convert.ToBase64String(buffer.ToArray());
		}
        public Rc4RandomGenerator(IBuffer key)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            
            _state = new byte[256];
            var keyLength = key.Length;

            for (uint w = 0; w < 256; ++w)
                _state[w] = (byte)w;

            unchecked
            {
                byte j = 0;
                uint keyIndex = 0;

                for (uint w = 0; w < 256; ++w) // Key setup
                {
                    j += (byte)(_state[w] + key.GetByte(keyIndex));

                    var temp = _state[0];
                    _state[0] = _state[j];
                    _state[j] = temp;

                    ++keyIndex;
                    if (keyIndex >= keyLength)
                        keyIndex = 0;
                }
            }

            GetRandomBytes(512);
        }
        public static IBuffer Encrypt(IBuffer data,
                                            CryptographicKey key,
                                            out IBuffer iv,
                                            String AlgorithmName = null)
        {
            //declares
            var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm;
            iv = null;

            // Open a symmetric algorithm provider for the specified algorithm. 
            var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Determine whether the message length is a multiple of the block length.
            // This is not necessary for PKCS #7 algorithms which automatically pad the
            // message to an appropriate length.
            if (!strAlgName.Contains("PKCS7"))
            {
                if ((data.Length % objAlg.BlockLength) != 0)
                    throw new Exception("Message buffer length must be multiple of block length.");
            }

            // CBC algorithms require an initialization vector. Here, a random
            // number is used for the vector.
            if (strAlgName.Contains("CBC"))
                iv = CryptographicBuffer.GenerateRandom(objAlg.BlockLength);

            // Encrypt the data and return.
            return CryptographicEngine.Encrypt(key, data, iv);
        }
        // Sample the original image
        private void SampleOriginalImage()
        {
            originalBitmap = new WriteableBitmap(originalImage);
            double ratio = (double)originalBitmap.PixelWidth / (double)originalBitmap.PixelHeight;
            double w = Application.Current.RootVisual.RenderSize.Width;
            double h = Application.Current.RootVisual.RenderSize.Height;
            double previewWidth;
            double previewHeight;

            if (w / ratio > h)
            {
                previewHeight = h;
                previewWidth = h * ratio;
            }
            else
            {
                previewWidth = w;
                previewHeight = w / ratio;
            }

            originalPreviewBitmap = originalBitmap.Resize((int)previewWidth, (int)previewHeight, System.Windows.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);
            currentPreviewBitmap = originalBitmap.Resize((int)previewWidth, (int)previewHeight, System.Windows.Media.Imaging.WriteableBitmapExtensions.Interpolation.Bilinear);

            // Create buffer
            previewStream = new MemoryStream();
            currentPreviewBitmap.SaveJpeg(previewStream, originalPreviewBitmap.PixelWidth, originalPreviewBitmap.PixelHeight, 0, 75);
            previewBuffer = previewStream.GetWindowsRuntimeBuffer();
        }
        public void SaveToPicturesLibrary(IBuffer imageBuffer, [CallerMemberName] string fileName = "", [CallerFilePath]string callerFilePath = "")
        {
            fileName = Path.GetFileNameWithoutExtension(callerFilePath) + "_" + fileName;

            if (!Path.HasExtension(fileName))
            {
                fileName = Path.ChangeExtension(fileName, "jpg");
            }

            lock (m_lockObject)
            {
                if (m_isClosed)
                {
                    throw new InvalidOperationException("ImageResults closed, cannot queue more operations.");
                }

                m_saveTask = m_saveTask.ContinueWith(async _ =>
                {
                    m_stopwatch.Start();

                    var file = await m_folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false);

                    await FileIO.WriteBufferAsync(file, imageBuffer).AsTask().ConfigureAwait(false);

                    m_stopwatch.Stop();

                });
            }
        }
        private async Task <SolidColorBrush> GetPixelColor()
        {
            RenderTargetBitmap retarbi = new RenderTargetBitmap();
            await retarbi.RenderAsync(PocketPaintApplication.GetInstance().PaintingAreaCanvas,
                                      (int)PocketPaintApplication.GetInstance().PaintingAreaCanvas.ActualWidth,
                                      (int)PocketPaintApplication.GetInstance().PaintingAreaCanvas.ActualHeight);

            Windows.Storage.Streams.IBuffer buffer = await(retarbi.GetPixelsAsync());
            var pixels = WindowsRuntimeBufferExtensions.ToArray(buffer);

            var width  = retarbi.PixelWidth;
            var height = retarbi.PixelHeight;

            double NormfactorX = (double)width / (double)PocketPaintApplication.GetInstance().Bitmap.PixelWidth;
            double NormfactorY = (double)height / (double)PocketPaintApplication.GetInstance().Bitmap.PixelHeight;

            double doubleY = ((double)Y) * NormfactorY;
            double doubleX = ((double)X) * NormfactorX;

            int intX = (int)Math.Round(doubleX, 0);
            int intY = (int)Math.Round(doubleY, 0);

            int intTemp  = intY * width;
            int intXTemp = intTemp + intX;
            int intValue = intXTemp * 4;

            var a = pixels[intValue + 3];
            var r = pixels[intValue + 2];
            var g = pixels[intValue + 1];
            var B = pixels[intValue];

            return(new SolidColorBrush(Windows.UI.Color.FromArgb(a, r, g, B)));
        }
		public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync (IBuffer buffer, uint count, InputStreamOptions options)
		{
			if (disposed)
				throw new ObjectDisposedException(GetType().FullName);

			throw new NotImplementedException();
		}
        internal static IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, UInt32 count)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream is SREMemoryStream);
            Debug.Assert(stream.CanRead);
            Debug.Assert(stream.CanSeek);
            Debug.Assert(buffer != null);
            Debug.Assert(buffer is IBufferByteAccess);
            Debug.Assert(0 <= count);
            Debug.Assert(count <= Int32.MaxValue);
            Debug.Assert(count <= buffer.Capacity);
            Contract.EndContractBlock();

            // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
            // This is permitted by the WinRT stream contract.
            // The user specified buffer will not have any data put into it:
            buffer.Length = 0;

            SREMemoryStream memStream = stream as SREMemoryStream;
            Debug.Assert(memStream != null);

            try
            {
                IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((Int32)memStream.Position, (Int32)count);
                if (dataBuffer.Length > 0)
                    memStream.Seek(dataBuffer.Length, SeekOrigin.Current);

                return AsyncInfo.CreateCompletedOperation<IBuffer, UInt32>(dataBuffer);
            }
            catch (Exception ex)
            {
                return AsyncInfo.CreateFaultedOperation<IBuffer, UInt32>(ex);
            }
        }  // ReadAsync_MemoryStream
Exemple #11
0
    /// <summary>
    /// Дешифрования текст
    /// </summary>
    /// <param name="SourceText">Исходный (шифрованный) текст</param>
    /// <param name="InputKey">Ключ шифрования</param>
    /// <param name="AlgorytmName">Имя алгоритма дешифрования</param>
    /// 
    /// <returns>Расшифрованный (открытый) текст</returns>
    public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize)
    {
        SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName);
        IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE);
        IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE);
        //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial);

        KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512);

        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000);

        CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer);

        IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms,Convert.ToUInt32(KeySize)/8);

          //  string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial);

        CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial);

        if (AlgorytmName.Contains("CBC"))
        {
            IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE);
        }
        // Set the data to encrypt.
           SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText);

        // Decrypt
        DecryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer);
        DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64

        return DecryptTextOutput;
    }
        public virtual async Task SetAsync(string key, IBuffer buffer, DateTime expires)
        {
            try
            {
                var names = key.Split('\\');
                var folder = rootFolder;

                for (int i = 0; i < names.Length - 1; i++)
                {
                    folder = await folder.CreateFolderAsync(names[i], CreationCollisionOption.OpenIfExists);
                }

                var file = await folder.CreateFileAsync(names[names.Length - 1], CreationCollisionOption.ReplaceExisting);
                await FileIO.WriteBufferAsync(file, buffer);

                // Use ImageProperties.DateTaken to store expiration date
                var imageProperties = await file.Properties.GetImagePropertiesAsync();
                imageProperties.DateTaken = expires;
                await imageProperties.SavePropertiesAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #13
0
        protected override void OnValueChanged(IBuffer buffer)
        {
            DataReader wReader = DataReader.FromBuffer(buffer);

            using (wReader)
            {
                byte[] b = new byte[4];
                wReader.ReadBytes(b);

                var ambientTemperature = BitConverter.ToInt16(b, 2) / 128.0;

                double Vobj2 = BitConverter.ToInt16(b, 0);
                Vobj2 *= 0.00000015625;

                double Tdie = ambientTemperature + 273.15;

                double S0 = 5.593E-14;
                double a1 = 1.75E-3;
                double a2 = -1.678E-5;
                double b0 = -2.94E-5;
                double b1 = -5.7E-7;
                double b2 = 4.63E-9;
                double c2 = 13.4;
                double Tref = 298.15;
                double S = S0 * (1 + a1 * (Tdie - Tref) + a2 * Math.Pow((Tdie - Tref), 2));
                double Vos = b0 + b1 * (Tdie - Tref) + b2 * Math.Pow((Tdie - Tref), 2);
                double fObj = (Vobj2 - Vos) + c2 * Math.Pow((Vobj2 - Vos), 2);
                double tObj = Math.Pow(Math.Pow(Tdie, 4) + (fObj / S), .25);

                //CurrentTemperature = tObj - 273.15;
                // On retourne plutôt le température ambiante, plus réaliste que temp courante.
                CurrentTemperature = ambientTemperature;
            }
        }
Exemple #14
0
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            try{
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(partition)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                Windows.Storage.Streams.IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(data);
                byte[] Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                dataOut = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
            }
            catch (Exception ex)
            {
                dataOut = "";
                return(getErrorCode() == 0 ? 1 : 0);
            }

            return(getErrorCode() == 0 ? 1 : 0);
        }
Exemple #15
0
        /// <summary>
        /// Decrypts the specified input stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="masterKey">The master key.</param>
        /// <param name="masterSeed">The master seed.</param>
        /// <param name="encryptionIV">The encryption initialization vector.</param>
        /// <returns>The decrypted buffer.</returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="input"/>, <paramref name="masterSeed"/>, <paramref name="masterKey"/>
        /// and <paramref name="encryptionIV"/> cannot be <c>null</c>.
        /// </exception>
        public static async Task<IInputStream> Decrypt(IRandomAccessStream input,
            IBuffer masterKey, IBuffer masterSeed, IBuffer encryptionIV)
        {
            if (input == null) throw new ArgumentNullException("input");
            if (masterSeed == null) throw new ArgumentNullException("masterSeed");
            if (masterKey == null) throw new ArgumentNullException("masterKey");
            if (encryptionIV == null) throw new ArgumentNullException("encryptionIV");

            var sha = HashAlgorithmProvider
                .OpenAlgorithm(HashAlgorithmNames.Sha256)
                .CreateHash();

            sha.Append(masterSeed);
            sha.Append(masterKey);

            var seed = sha.GetValueAndReset();
            var aes = SymmetricKeyAlgorithmProvider
                .OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7)
                .CreateSymmetricKey(seed);

            var buffer = WindowsRuntimeBuffer.Create(
                (int)(input.Size - input.Position));
            buffer = await input.ReadAsync(buffer, buffer.Capacity);
            buffer = CryptographicEngine.Decrypt(aes, buffer, encryptionIV);

            var stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(buffer);
            stream.Seek(0);

            return stream;
        }
        public Aes128Pkcs7ReadStream(Stream parent, byte[] key, byte[] iv)
        {
            if (parent == null)
                throw new ArgumentNullException(nameof(parent));

            if (key == null)
                throw new ArgumentNullException(nameof(key));

            if (!parent.CanRead)
                throw new ArgumentException("parent must be a readable stream");

            _parent = parent;

            var algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
            var lastAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            _blockLength = (int)lastAlgorithm.BlockLength;

            if (null != iv && iv.Length != _blockLength)
                throw new ArgumentOutOfRangeException(nameof(iv), "length must match the block length");

            _encryptedBuffer = _encrypted.AsBuffer();
            _encryptedBuffer.Length = 0;

            var keyBuffer = key.AsBuffer();

            _key = algorithm.CreateSymmetricKey(keyBuffer);
            _lastKey = lastAlgorithm.CreateSymmetricKey(keyBuffer);

            _ivBuffer = CopyArray(iv).AsBuffer();
        }
        /// <summary>
        /// 对字符串依据指定的算法和密钥进行加密,如果使用 CBC 算法,还需要初始化向量
        /// </summary>
        /// <param name="content">源字符串</param>
        /// <param name="strAlgName">加密算法</param>
        /// <param name="encoding">字符串编码方式</param>
        /// <param name="key">密钥</param>
        /// <param name="iniVec">CBC 初始化向量</param>
        /// <returns></returns>
        public static IBuffer CipherEncryption(string content, string strAlgName,
            BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null)
        {
            // Create a buffer that contains the encoded message to be encrypted. 
            IBuffer buffContent = CryptographicBuffer.ConvertStringToBinary(content, encoding);

            // Open a symmetric algorithm provider for the specified algorithm. 
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Determine whether the message length is a multiple of the block length.
            // This is not necessary for PKCS #7 algorithms which automatically pad the
            // message to an appropriate length.
            if (!strAlgName.Contains("PKCS7"))
            {
                if ((buffContent.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            if (strAlgName.Contains("CBC") && iniVec == null)
            {
                throw new ArgumentException("Using CBC Encryption, initial vector must have value");
            }
            // Encrypt the data and return.
            IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffContent, iniVec);
            return buffEncrypt;
        }
        async public Task <int> preparePaintingAreaCanvasForEraser()
        {
            RenderTargetBitmap retarbi      = new RenderTargetBitmap();
            Canvas             eraserCanvas = PocketPaintApplication.GetInstance().EraserCanvas;

            try
            {
                if (eraserCanvas.Visibility == Visibility.Collapsed)
                {
                    eraserCanvas.Visibility = Visibility.Visible;
                }
                await retarbi.RenderAsync(eraserCanvas);

                Windows.Storage.Streams.IBuffer buffer = await(retarbi.GetPixelsAsync());
                pixelsCanvasEraser = WindowsRuntimeBufferExtensions.ToArray(buffer);

                this.pixelHeightCanvas = retarbi.PixelHeight;
                this.pixelWidthCanvas  = retarbi.PixelWidth;
            }
            catch
            {
                return(1);
            }
            return(0);
        }
	uint Read(IBuffer buffer, uint offset, uint count)
	{
		if (this.needSeek) {
			if (this.position < 44)
				asap.Seek(0);
			else {
				ulong bytes = this.position - 44 & ~(BufferSize - 1UL);
				asap.SeekSample((int) (bytes / wavHeader[32]));
			}
			this.needSeek = false;
		}

		ulong left = this.size - this.position;
		if (count > left)
			count = (uint) left;
		if (this.position < 44UL) {
			uint n = Math.Min(44 - (uint) this.position, count);
			this.wavHeader.CopyTo((int) this.position, buffer, offset, (int) n);
			this.position += n;
			offset += n;
			count -= n;
		}
		while (count > 0) {
			int i = (int) this.position - 44 & BufferSize - 1;
			if (i == 0)
				asap.Generate(this.samples, BufferSize, ASAPSampleFormat.S16LE);
			uint n = Math.Min((uint) BufferSize - (uint) i, count);
			this.samples.CopyTo(i, buffer, offset, (int) n);
			this.position += n;
			offset += n;
			count -= n;
		}
		return offset;
	}
        public async Task GetNewFrameAndApplyEffect(IBuffer frameBuffer, Size frameSize)
        {
            if (_semaphore.WaitOne(500))
            {
                var scanlineByteSize = (uint)frameSize.Width * 4; // 4 bytes per pixel in BGRA888 mode
                var bitmap = new Bitmap(frameSize, ColorMode.Bgra8888, scanlineByteSize, frameBuffer);

                try
                {
                    if (_blendEffect != null)
                    {
                        _blendEffect.GlobalAlpha = GlobalAlpha;

                        var renderer = new BitmapRenderer(_blendEffect, bitmap);
                        await renderer.RenderAsync();
                    }
                    else
                    {
                        var renderer = new BitmapRenderer(_cameraPreviewImageSource, bitmap);
                        await renderer.RenderAsync();
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("RealtimeBlendDemo.GetNewFrameAndApplyEffect(): "
                        + ex.ToString());
                }

                _semaphore.Release();
            }
        }
 public PixelBufferInfo(IBuffer pixelBuffer)
 {
     this.pixelStream = WindowsRuntimeBufferExtensions.AsStream(pixelBuffer);
     this.Bytes = new byte[this.pixelStream.Length];
     this.pixelStream.Seek(0L, SeekOrigin.Begin);
     this.pixelStream.Read(this.Bytes, 0, this.Bytes.Length);
 }
        public async Task GetNewFrameAndApplyEffect(IBuffer frameBuffer, Size frameSize)
        {
            if (_semaphore.WaitOne(500))
            {
                var scanlineByteSize = (uint)frameSize.Width * 4; // 4 bytes per pixel in BGRA888 mode
                var bitmap = new Bitmap(frameSize, ColorMode.Bgra8888, scanlineByteSize, frameBuffer);

                if (_filterEffect != null)
                {
                    var renderer = new BitmapRenderer(_filterEffect, bitmap);
                    await renderer.RenderAsync();
                }
                else if (_customEffect != null)
                {
                    var renderer = new BitmapRenderer(_customEffect, bitmap);
                    await renderer.RenderAsync();
                }
                else
                {
                    var renderer = new BitmapRenderer(_cameraPreviewImageSource, bitmap);
                    await renderer.RenderAsync();
                }

                _semaphore.Release();
            }
        }
		public static byte[] ToBytes(IBuffer value) 
		{
			if(value == null)
				throw new ArgumentException();
			var temp = new byte[value.Length];
			DataReader.FromBuffer(value).ReadBytes(temp);
			return temp;
		}
Exemple #24
0
 // Gets a byte array from a buffer
 public static byte[] ReadBufferToBytes(IBuffer buffer)
 {
     var dataLength = buffer.Length;
     var data = new byte[dataLength];
     var reader = DataReader.FromBuffer(buffer);
     reader.ReadBytes(data);
     return data;
 }
        public static void CopyTo(this Byte[] source, IBuffer destination)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (destination == null) throw new ArgumentNullException("destination");
            Contract.EndContractBlock();

            CopyTo(source, 0, destination, 0, source.Length);
        }
 public PixelBufferInfo(IBuffer pixelBuffer)
 {
     this.pixelStream = pixelBuffer.AsStream();
     this.Bytes = new byte[this.pixelStream.Length];
     this.pixelStream.Seek(0, SeekOrigin.Begin);
     this.pixelStream.Read(this.Bytes, 0, Bytes.Length);
     //this.Pixels = bytes.ToPixels();
 }
 public static IBuffer Decrypt(IBuffer input, string password = "******")
 {
     var iv = CreateInitializationVector(password);
     var key = CreateKey(password);
     var decryptedBuffer = CryptographicEngine.Decrypt(
       key, input, iv);
     return decryptedBuffer;
 }
 public MP3Extract(IBuffer mp3, Image cover)
 {
     this.mp3 = mp3;
     fileData.Add("Album", "");
     fileData.Add("Title", "");
     fileData.Add("Artist", "");
     data = DataReader.FromBuffer(mp3);
     this.cover = cover;
 }
Exemple #29
0
 // Multiple
 public static string ParseUInt8Multi(IBuffer buffer)
 {
     var bytes = ReadBufferToBytes(buffer);
     var result = "";
     foreach (var b in bytes) {
         result += Convert.ToString(b); 
     }
     return result; 
 }
 public static string getStringFromBuffer(IBuffer buffer)
 {
     using (DataReader dataReader = DataReader.FromBuffer(buffer))
     {
         byte[] bufferBytes = new byte[buffer.Length];
         dataReader.ReadBytes(bufferBytes);
         return (Convert.ToBase64String(bufferBytes));
     }
 }
Exemple #31
0
		public void Append (IBuffer Data)
		{
			if (Data == null)
				return;

			WindowsRuntimeBuffer buffer = (WindowsRuntimeBuffer)Data;

			throw new NotImplementedException();
		}
		public CryptographicKey CreateSymmetricKey (IBuffer keyMaterial)
		{
			if (keyMaterial == null)
				throw new COMException ("Invalid key material", -1073741811);

			WindowsRuntimeBuffer buffer = (WindowsRuntimeBuffer)keyMaterial;

			throw new NotImplementedException();
		}
Exemple #33
0
        /// <summary>
        /// Decrypts the specified input stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="masterKey">The master key.</param>
        /// <param name="headers">The database file headers.</param>
        /// <returns>The decrypted buffer.</returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="input"/>, <paramref name="masterKey"/>,
        /// <paramref name="headers"/> cannot be <c>null</c>.
        /// </exception>
        public static Task<IInputStream> Decrypt(IRandomAccessStream input,
            IBuffer masterKey, FileHeaders headers)
        {
            if (headers == null)
                throw new ArgumentNullException("headers");

            return Decrypt(input, masterKey,
                headers.MasterSeed, headers.EncryptionIV);
        }
Exemple #34
0
        protected override async void Loop()
        {
            Streams.DataReader reader = null;

            try
            {
                while (true)
                {
                    if (socket == null)
                    {
                        socket = new StreamSocket();
                        await socket.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                    }

                    var readBuf = new Streams.Buffer((uint)NetworkBufferSize);
                    var readOp  = socket.InputStream.ReadAsync(readBuf, (uint)NetworkBufferSize, Streams.InputStreamOptions.Partial);

                    readOp.Completed = (IAsyncOperationWithProgress <Streams.IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
                    {
                        switch (asyncStatus)
                        {
                        case AsyncStatus.Completed:
                            Debug.WriteLine("Config:Completed ");
                            try
                            {
                                Streams.IBuffer localBuf  = asyncAction.GetResults();
                                uint            bytesRead = localBuf.Length;
                                Debug.WriteLine("Config:Buffer (" + bytesRead + ")");
                                reader = Streams.DataReader.FromBuffer(localBuf);
                                OnDataReadCompletion(bytesRead, reader);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteLine(e.ToString());
                            }
                            break;

                        case AsyncStatus.Canceled:
                            Debug.WriteLine("Config:Canceled ");
                            break;

                        case AsyncStatus.Error:
                            Debug.WriteLine("Config:Error ");
                            break;
                        }
                    };
                    //socket.Dispose();
                    await Task.Delay(500);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                Stop();
            }
        }
 public static IBuffer EncryptString(String strMsg,
                                     CryptographicKey key,
                                     out IBuffer iv,
                                     String AlgorithmName = null)
 {
     // Create a buffer that contains the encoded message to be encrypted. 
     var buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);
     //encrypt
     return Encrypt(buffMsg, key, out iv, AlgorithmName: AlgorithmName);
 }
Exemple #36
0
        public async void Start()
        {
            var listener   = new StreamSocketListener();
            var XmlHandler = new XmlHandler();

            XmlHandler.MainAsync();

            await listener.BindServiceNameAsync("8081");

            listener.ConnectionReceived += async(sender, args) =>
            {
                var request = new StringBuilder();

                using (var input = args.Socket.InputStream)
                {
                    var data = new byte[BufferSize];
                    Windows.Storage.Streams.IBuffer buffer = data.AsBuffer();
                    var dataRead = BufferSize;

                    while (dataRead == BufferSize)
                    {
                        await input.ReadAsync(
                            buffer, BufferSize, InputStreamOptions.Partial);

                        request.Append(Encoding.UTF8.GetString(
                                           data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                //string query = GetQuery(request);
                string query = await XmlHandler.RunQuery(GetQuery(request));

                using (var output = args.Socket.OutputStream)
                {
                    using (var response = output.AsStreamForWrite())
                    {
                        var html = Encoding.UTF8.GetBytes(
                            $"<html><head><title>Background Message</title></head><body>{query}</body></html>");
                        using (var bodyStream = new MemoryStream(html))
                        {
                            var header      = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";
                            var headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray,
                                                      0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                }
            };
        }
Exemple #37
0
        public int setDbCryptKey(String partition, String key, bool bPersistent)
        {
            Windows.Storage.Streams.IBuffer keyByte    = Encoding.UTF8.GetBytes(key).AsBuffer();
            DataProtectionProvider          protecotor = new DataProtectionProvider();
            IAsyncOperation <IBuffer>       task       = protecotor.ProtectAsync(keyByte);

            task.AsTask().Wait();
            Windows.Storage.Streams.IBuffer protectedKeyByte = task.GetResults();
            this.writeKeyToFile(partition, protectedKeyByte.ToArray());
            return(getErrorCode() == 0 ? 1 : 0);
        }
        async public Task <int> preparePaintingAreaCanvasPixel()
        {
            RenderTargetBitmap retarbi = new RenderTargetBitmap();
            Canvas             canvas  = PocketPaintApplication.GetInstance().PaintingAreaCanvas;
            await retarbi.RenderAsync(canvas);

            Windows.Storage.Streams.IBuffer buffer = await(retarbi.GetPixelsAsync());
            pixelsCanvas = WindowsRuntimeBufferExtensions.ToArray(buffer);

            this.pixelHeightCanvas = retarbi.PixelHeight;
            this.pixelWidthCanvas  = retarbi.PixelWidth;
            return(0);
        }
Exemple #39
0
        private async Task <Windows.Storage.Streams.IRandomAccessStream> toStream(Windows.Storage.Streams.IBuffer ibuffer)
        {
            var stream       = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var outputStream = stream.GetOutputStreamAt(0);
            var datawriter   = new Windows.Storage.Streams.DataWriter(outputStream);

            datawriter.WriteBuffer(ibuffer);
            await datawriter.StoreAsync();

            await outputStream.FlushAsync();

            return(stream);
        }
        private static MiDeviceData ReadDatas(Windows.Storage.Streams.IBuffer buffer)
        {
            var data = ExtractBytesFromBuffer(buffer);

            byte[] readableValue = data.ToArray();
            double temperature   = ((readableValue[1] & 0x7F) << 8 | readableValue[0]) / 100.0;
            byte   moisture      = readableValue[2];

            return(new MiDeviceData()
            {
                Temperature = temperature,
                Moisture = moisture
            });
        }
        private static byte[] ExtractBytesFromBuffer(Windows.Storage.Streams.IBuffer buffer)
        {
            List <byte> data = new List <byte>(capacity: (int)buffer.Length);

            using (Windows.Storage.Streams.DataReader dr = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
            {
                while (dr.UnconsumedBufferLength > 0)
                {
                    data.Add(dr.ReadByte());
                }
            }

            return(data.ToArray());
        }
        public void GenerateKey(string password, string salt, out Windows.Storage.Streams.IBuffer keyMaterial, out Windows.Storage.Streams.IBuffer iv)
        {
            IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8);
            KeyDerivationParameters        keyParams = KeyDerivationParameters.BuildForSP800108(saltBuffer, GetNonce());
            KeyDerivationAlgorithmProvider kdf       = KeyDerivationAlgorithmProvider.OpenAlgorithm(Encryptor.Settings.KeyDerivationAlgorithm);
            IBuffer          passwordBuffer          = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            CryptographicKey keyOriginal             = kdf.CreateKey(passwordBuffer);

            int     keySize    = 256;
            int     ivSize     = 128 / 8;
            uint    totalData  = (uint)(keySize + ivSize);
            IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial(keyOriginal, keyParams, totalData);

            byte[] keyMaterialBytes = keyDerived.ToArray();
            keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize);
            iv          = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize);
        }
Exemple #43
0
        private byte[] HandleReceive(uint bytesRead, DataReader readPacket, int length = 1024 *1024 *5)
        {
            var bufferSpace = length * 2;

            byte[] tmpRet = new byte[length];
            Windows.Storage.Streams.IBuffer ibuffer = readPacket.ReadBuffer(readPacket.UnconsumedBufferLength);
            Byte[] convBuffer = WindowsRuntimeBufferExtensions.ToArray(ibuffer);

            if (bytesRead > 0)
            {
                System.Buffer.BlockCopy(convBuffer, 0, tmpRet, (int)0, (int)length);
            }
            _transferredSize += bytesRead;

            var kucing = System.Text.Encoding.UTF8.GetString(tmpRet, 0, tmpRet.Length);

            WhatsAPI.UniversalApps.Libs.Utils.Logger.Log.WriteLog("Receive Message => " + System.Text.Encoding.UTF8.GetString(tmpRet, 0, tmpRet.Length));
            return(tmpRet);
        }
Exemple #44
0
 public void UpdateData(Windows.Storage.Streams.IBuffer buffer)
 {
     this.data = buffer.ToArray();
     ParseData();
 }
Exemple #45
0
        public bool Start()
        {
            try
            {
                StreamSocketListener listener = new StreamSocketListener();
                listener.BindServiceNameAsync("80").AsTask();
                listener.ConnectionReceived += async(sender, args) =>
                {
                    StringBuilder request = new StringBuilder();
                    using (Windows.Storage.Streams.IInputStream input = args.Socket.InputStream)
                    {
                        byte[] data = new byte[BufferSize];
                        Windows.Storage.Streams.IBuffer buffer = data.AsBuffer();
                        uint dataRead = BufferSize;
                        while (dataRead == BufferSize)
                        {
                            await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);

                            request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                            dataRead = buffer.Length;
                        }
                        //In the future, maybe we parse the HTTP request and serve different HTML pages for now we just always push index.html
                    }
                    using (IOutputStream output = args.Socket.OutputStream)
                    {
                        using (System.IO.Stream response = output.AsStreamForWrite())
                        {
                            string page   = "";
                            var    folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                            // acquire file
                            var file = await folder.GetFileAsync("index.html");

                            var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);

                            foreach (var line in readFile)
                            {
                                page += line;
                            }
                            byte[] bodyArray  = Encoding.UTF8.GetBytes(page);
                            var    bodyStream = new MemoryStream(bodyArray);
                            //iCount++;

                            var header = "HTTP/1.1 200 OK\r\n" +
                                         $"Content-Length: {bodyStream.Length}\r\n" +
                                         "Connection: close\r\n\r\n";
                            byte[] headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray, 0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                };
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemple #46
0
 public IAsyncOperationWithProgress <IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
 => _stream.ReadAsync(buffer, count, options);
Exemple #47
0
 public IAsyncOperationWithProgress <uint, uint> WriteAsync(IBuffer buffer)
 => _stream.WriteAsync(buffer);
Exemple #48
0
        }  // ReadAsync_AbstractStream

        #endregion ReadAsync implementations


        #region WriteAsync implementations

        internal static IAsyncOperationWithProgress <uint, uint> WriteAsync_AbstractStream(Stream stream, IBuffer buffer)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanWrite);
            Debug.Assert(buffer != null);

            // Choose the optimal writing strategy for the kind of buffer supplied:
            Func <CancellationToken, IProgress <uint>, Task <uint> > writeOperation;

            byte[] data;
            int    offset;

            // If buffer is backed by a managed array:
            if (buffer.TryGetUnderlyingData(out data, out offset))
            {
                writeOperation = async(cancelToken, progressListener) =>
                {
                    if (cancelToken.IsCancellationRequested)  // CancellationToken is non-nullable
                    {
                        return(0);
                    }

                    Debug.Assert(buffer.Length <= int.MaxValue);

                    int bytesToWrite = (int)buffer.Length;

                    await stream.WriteAsync(data, offset, bytesToWrite, cancelToken).ConfigureAwait(continueOnCapturedContext: false);

                    if (progressListener != null)
                    {
                        progressListener.Report((uint)bytesToWrite);
                    }

                    return((uint)bytesToWrite);
                };
                // Otherwise buffer is of an unknown implementation:
            }
            else
            {
                writeOperation = async(cancelToken, progressListener) =>
                {
                    if (cancelToken.IsCancellationRequested)  // CancellationToken is non-nullable
                    {
                        return(0);
                    }

                    uint   bytesToWrite = buffer.Length;
                    Stream dataStream   = buffer.AsStream();

                    int buffSize = 0x4000;
                    if (bytesToWrite < buffSize)
                    {
                        buffSize = (int)bytesToWrite;
                    }

                    if (buffSize > 0)
                    {
                        await dataStream.CopyToAsync(stream, buffSize, cancelToken).ConfigureAwait(continueOnCapturedContext: false);
                    }

                    if (progressListener != null)
                    {
                        progressListener.Report((uint)bytesToWrite);
                    }

                    return((uint)bytesToWrite);
                };
            }  // if-else

            // Construct and run the async operation:
            return(AsyncInfo.Run <uint, uint>(writeOperation));
        }  // WriteAsync_AbstractStream
Exemple #49
0
        internal static IAsyncOperationWithProgress <IBuffer, uint> ReadAsync_MemoryStream(Stream stream, IBuffer buffer, uint count)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream is MemoryStream);
            Debug.Assert(stream.CanRead);
            Debug.Assert(stream.CanSeek);
            Debug.Assert(buffer != null);
            Debug.Assert(0 <= count);
            Debug.Assert(count <= int.MaxValue);
            Debug.Assert(count <= buffer.Capacity);

            // We will return a different buffer to the user backed directly by the memory stream (avoids memory copy).
            // This is permitted by the WinRT stream contract.
            // The user specified buffer will not have any data put into it:
            buffer.Length = 0;

            MemoryStream memStream = stream as MemoryStream;

            Debug.Assert(memStream != null);

            try
            {
                IBuffer dataBuffer = memStream.GetWindowsRuntimeBuffer((int)memStream.Position, (int)count);
                if (dataBuffer.Length > 0)
                {
                    memStream.Seek(dataBuffer.Length, SeekOrigin.Current);
                }

                return(AsyncInfo.CreateCompletedOperation <IBuffer, uint>(dataBuffer));
            }
            catch (Exception ex)
            {
                return(AsyncInfo.CreateFaultedOperation <IBuffer, uint>(ex));
            }
        }  // ReadAsync_MemoryStream
Exemple #50
0
        }  // ReadAsync_MemoryStream

        internal static IAsyncOperationWithProgress <IBuffer, uint> ReadAsync_AbstractStream(Stream stream, IBuffer buffer, uint count,
                                                                                             InputStreamOptions options)
        {
            Debug.Assert(stream != null);
            Debug.Assert(stream.CanRead);
            Debug.Assert(buffer != null);
            Debug.Assert(0 <= count);
            Debug.Assert(count <= int.MaxValue);
            Debug.Assert(count <= buffer.Capacity);
            Debug.Assert(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead);

            int bytesrequested = (int)count;

            // Check if the buffer is our implementation.
            // IF YES: In that case, we can read directly into its data array.
            // IF NO:  The buffer is of unknown implementation. It's not backed by a managed array, but the wrapped stream can only
            //         read into a managed array. If we used the user-supplied buffer we would need to copy data into it after every read.
            //         The spec allows to return a buffer instance that is not the same as passed by the user. So, we will create an own
            //         buffer instance, read data *directly* into the array backing it and then return it to the user.
            //         Note: the allocation costs we are paying for the new buffer are unavoidable anyway, as we would need to create
            //         an array to read into either way.

            IBuffer dataBuffer = buffer as WindowsRuntimeBuffer;

            if (dataBuffer == null)
            {
                dataBuffer = WindowsRuntimeBuffer.Create((int)Math.Min((uint)int.MaxValue, buffer.Capacity));
            }

            // This operation delegate will we run inside of the returned IAsyncOperationWithProgress:
            Func <CancellationToken, IProgress <uint>, Task <IBuffer> > readOperation = async(cancelToken, progressListener) =>
            {
                // No bytes read yet:
                dataBuffer.Length = 0;

                // Get the buffer backing array:
                byte[] data;
                int    offset;
                bool   managedBufferAssert = dataBuffer.TryGetUnderlyingData(out data, out offset);
                Debug.Assert(managedBufferAssert);

                // Init tracking values:
                bool done           = cancelToken.IsCancellationRequested;
                int  bytesCompleted = 0;

                // Loop until EOS, cancelled or read enough data according to options:
                while (!done)
                {
                    int bytesread = 0;

                    try
                    {
                        // Read asynchronously:
                        bytesread = await stream.ReadAsync(data !, offset + bytesCompleted, bytesrequested - bytesCompleted, cancelToken)
                                    .ConfigureAwait(continueOnCapturedContext: false);

                        // We will continue here on a different thread when read async completed:
                        bytesCompleted += bytesread;
                        // We will handle a cancelation exception and re-throw all others:
                    }
                    catch (OperationCanceledException)
                    {
                        // We assume that cancelToken.IsCancellationRequested is has been set and simply proceed.
                        // (we check cancelToken.IsCancellationRequested later)
                        Debug.Assert(cancelToken.IsCancellationRequested);

                        // This is because if the cancellation came after we read some bytes we want to return the results we got instead
                        // of an empty cancelled task, so if we have not yet read anything at all, then we can throw cancellation:
                        if (bytesCompleted == 0 && bytesread == 0)
                        {
                            throw;
                        }
                    }

                    // Update target buffer:
                    dataBuffer.Length = (uint)bytesCompleted;

                    Debug.Assert(bytesCompleted <= bytesrequested);

                    // Check if we are done:
                    done = options == InputStreamOptions.Partial || // If no complete read was requested, any amount of data is OK
                           bytesread == 0 ||                          // this implies EndOfStream
                           bytesCompleted == bytesrequested ||        // read all requested bytes
                           cancelToken.IsCancellationRequested;       // operation was cancelled

                    // Call user Progress handler:
                    if (progressListener != null)
                    {
                        progressListener.Report(dataBuffer.Length);
                    }
                }  // while (!done)

                // If we got here, then no error was detected. Return the results buffer:
                return(dataBuffer);
            };  // readOperation

            return(AsyncInfo.Run <IBuffer, uint>(readOperation));
        }  // ReadAsync_AbstractStream
Exemple #51
0
 /// <summary>
 /// 把图片保存到本地临时文件夹中
 /// </summary>
 /// <param name="file"></param>
 /// <param name="buffer"></param>
 /// <returns></returns>
 public async Task SaveFile(StorageFile file, Windows.Storage.Streams.IBuffer buffer)
 {
     await Windows.Storage.FileIO.WriteBufferAsync(file, buffer);
 }