public async Task <int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
        {
            StreamSocket socket = this._socket;

            if (null == socket)
            {
                throw new InvalidOperationException("The socket is not open");
            }
            IBuffer iBuffer  = WindowsRuntimeBufferExtensions.AsBuffer(buffer, offset, 0, length);
            IBuffer iBuffer2 = await WindowsRuntimeSystemExtensions.AsTask <IBuffer, uint>(socket.InputStream.ReadAsync(iBuffer, (uint)length, InputStreamOptions.Partial), cancellationToken).ConfigureAwait(false);

            int bytesRead = (int)iBuffer2.Length;
            int num;

            if (bytesRead <= 0)
            {
                num = 0;
            }
            else if (object.ReferenceEquals((object)iBuffer, (object)iBuffer2))
            {
                num = bytesRead;
            }
            else
            {
                Debug.Assert(bytesRead <= length, "Length out-of-range");
                WindowsRuntimeBufferExtensions.CopyTo(iBuffer2, 0U, buffer, offset, bytesRead);
                num = bytesRead;
            }
            return(num);
        }
        public void CopyTo_NegativeCount_ThrowsArgumentOutOfRangeException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, buffer, 0, -1));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("count", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, new byte[0], 0, -1));
        }
        public void CopyTo_InvalidDestinationIndexCount_ThrowsArgumentException(byte[] bytes, uint destinationIndex, uint count)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes);

            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], 0, buffer, destinationIndex, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, bytes, (int)destinationIndex, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, buffer, destinationIndex, count));
        }
        public void CopyTo_InvalidSourceIndexCount_ThrowsArgumentException(byte[] bytes, uint sourceIndex, uint count)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(bytes);

            AssertExtensions.Throws <ArgumentException>(sourceIndex >= bytes.Length ? "sourceIndex" : null, () => WindowsRuntimeBufferExtensions.CopyTo(bytes, (int)sourceIndex, buffer, 0, (int)count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, buffer, 0, count));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, sourceIndex, new byte[0], 0, (int)count));
        }
        public void CopyTo_LargeSourceIndex_ThrowsArgumentException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentException>("sourceIndex", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 1, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentException>(null, () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 1, new byte[0], 0, 0));
        }
Esempio n. 6
0
        //Initialize the new Crypto object (initialized only once per app startup)
        public async void initCrypto()
        {
            this.strAsymmetricAlgName = AsymmetricAlgorithmNames.RsaPkcs1;
            this.asymmetricKeyLength  = 512;

            //Checks SecureChat's folder if a key pair already exists and set keyPairExists boolean
            Windows.Storage.StorageFolder localAppFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            string cryptoFilePrivate = "SecureChatPrivateKeys.sckey";  //STORED AS BYTE DATA
            string cryptoFilePublic  = "SecureChatPublicKey.sckey";    //STORED AS TEXT DATA

            if ((await localAppFolder.TryGetItemAsync(cryptoFilePublic) != null) && (await localAppFolder.TryGetItemAsync(cryptoFilePrivate) != null))
            {
                this.keyPairExists = true;
            }
            else
            {
                this.keyPairExists = false;
            }
            //Load Keys depending on keyPairExists value
            if (this.keyPairExists == true)
            {
                //DIRECT IBUFFER
                //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic);
                //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic);

                //FROM BYTE
                //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync("BytePubKey.sckey");
                //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic);

                //Open Public Key File.  Convert key from STRING to BYTE and then convert to IBUFFER
                StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic);

                String publicKeyStringVersion = await FileIO.ReadTextAsync(loadedCryptoFilePublic);

                this.publicKeyByteVersion = Convert.FromBase64String(publicKeyStringVersion);
                this.buffPublicKey        = this.publicKeyByteVersion.AsBuffer();

                //Open Private Key File
                StorageFile loadedCryptoFilePrivate = await localAppFolder.GetFileAsync(cryptoFilePrivate);

                this.buffPrivateKeyStorage = await FileIO.ReadBufferAsync(loadedCryptoFilePrivate);
            }
            else
            {
                //Generate new key pair
                CryptographicKey temp = this.CreateAsymmetricKeyPair(strAsymmetricAlgName, asymmetricKeyLength, out buffPublicKey, out buffPrivateKeyStorage);

                //Convert public key from IBUFFER type to BYTE type.  Convert from BYTE type to STRING type
                WindowsRuntimeBufferExtensions.CopyTo(this.buffPublicKey, this.publicKeyByteVersion);
                string publicKeyStringVersion = Convert.ToBase64String(this.publicKeyByteVersion);

                //Store keys in appropriate files (Public as PLAIN TEXT, Private as IBUFFER)
                await FileIO.WriteTextAsync((await localAppFolder.CreateFileAsync(cryptoFilePublic)), publicKeyStringVersion);

                await FileIO.WriteBufferAsync((await localAppFolder.CreateFileAsync(cryptoFilePrivate)), this.buffPrivateKeyStorage);
            }
        }
Esempio n. 7
0
        //BUTTON:  UPDATE CRYPTO KEY
        private async void updatePublicKey_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new MessageDialog("Updating your current key will cause previous messages to no longer be decryptable");

            dialog.Title = "Are you sure?";
            dialog.Commands.Add(new UICommand {
                Label = "Ok", Id = 0
            });
            dialog.Commands.Add(new UICommand {
                Label = "Cancel", Id = 1
            });
            var res = await dialog.ShowAsync();

            IBuffer clientPublicKeyBUFFER = Crypto.returnPublicKey(App.secrets);

            byte[] clientPublicKeyBYTE = new byte[512];
            WindowsRuntimeBufferExtensions.CopyTo(clientPublicKeyBUFFER, clientPublicKeyBYTE);
            string clientPublicKeySTRING = Convert.ToBase64String(clientPublicKeyBYTE);

            //Create a Key and Pair match with object data (prepared for POST request)
            var values = new Dictionary <string, string>
            {
                { "key", clientPublicKeySTRING },
                { "user", App.userManagement.getURL_string() }
            };
            var theContent = new FormUrlEncodedContent(values);

            if ((int)res.Id == 0)
            {
                //PUT REQUEST
                string publicKeyURL = App.userManagement.getPublicKey_string();
                using (HttpClient client = new HttpClient()) //using block makes the object disposable (one time use)
                {
                    var byteArray = Encoding.ASCII.GetBytes(App.userManagement.getCurrentUser_string() + ":" + currentUserPasswordActual.Password);
                    var header    = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    client.DefaultRequestHeaders.Authorization = header;
                    using (HttpResponseMessage response = await client.PutAsync(publicKeyURL, theContent))       //BUG:  HANDLE OFFLINE MODE
                    {
                        using (HttpContent content = response.Content)
                        {
                            string content_string = await content.ReadAsStringAsync();

                            System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers;
                        }
                    }
                }
                MessageDialog msgbox2 = new MessageDialog("Overwriting serverside key");
                await msgbox2.ShowAsync();
            }

            if ((int)res.Id == 1)
            {
                //DO NOTHING
                MessageDialog msgbox2 = new MessageDialog("Cancelling request");
                await msgbox2.ShowAsync();
            }
        }
        public void CopyTo_NullDestination_ThrowsArgumentNullException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (IBuffer)null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, (byte[])null));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(new byte[0], 0, null, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, null, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("destination", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, (IBuffer)null, 0, 0));
        }
        public void CopyTo_NullSource_ThrowsArgumentNullException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((byte[])null, buffer));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, new byte[0]));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, buffer));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, buffer, 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo(null, 0, new byte[0], 0, 0));
            AssertExtensions.Throws <ArgumentNullException>("source", () => WindowsRuntimeBufferExtensions.CopyTo((IBuffer)null, 0, buffer, 0, 0));
        }
Esempio n. 10
0
        private async void WriteOutputReport(Byte[] data)
        {
            var report = _store.Item2.CreateOutputReport();

            // Only grab the byte we need
            Byte[] bytesToModify = data;

            WindowsRuntimeBufferExtensions.CopyTo(bytesToModify, 0, report.Data, 0, bytesToModify.Length);

            await _store.Item2.SendOutputReportAsync(report);
        }
        public void CopyTo_CustomBuffer_ThrowsInvalidCastException()
        {
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], new CustomBuffer()));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), new byte[10]));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), new CustomBuffer()));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10], 0, new CustomBuffer(), 0, 0));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new byte[10], 0, 0));

            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new CustomBuffer(), 0, 0));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new CustomBuffer(), 0, new byte[10].AsBuffer(), 0, 0));
            Assert.Throws <InvalidCastException>(() => WindowsRuntimeBufferExtensions.CopyTo(new byte[10].AsBuffer(), 0, new CustomBuffer(), 0, 0));
        }
Esempio n. 12
0
        /// <summary>
        /// The app sends an output report to the motion sensor to set the sensor's report interval.
        /// </summary>
        /// <param name="valueToWrite"></param>
        /// <returns>A task that can be used to chain more methods after completing the scenario</returns>
        private async Task SendNumericOutputReportAsync(Byte valueToWrite)
        {
                var outputReport = DeviceList.Current.CurrentDevice.CreateOutputReport();

                Byte[] bytesToCopy = new Byte[1];
                bytesToCopy[0] = valueToWrite;

                WindowsRuntimeBufferExtensions.CopyTo(bytesToCopy, 0, outputReport.Data, 1, 1);

                uint bytesWritten = await DeviceList.Current.CurrentDevice.SendOutputReportAsync(outputReport);

                rootPage.NotifyUser("Bytes written:  " + bytesWritten.ToString() + "; Value Written: " + valueToWrite.ToString(), NotifyType.StatusMessage);
        }
        public void CopyTo_Buffer_Success(byte[] source, int sourceIndex, byte[] destination, int destinationIndex, int count, byte[] expected)
        {
            byte[] Clone(byte[] array) => (byte[])array.Clone();
            IBuffer Buffer(byte[] array) => Clone(array).AsBuffer();

            if (sourceIndex == 0 && destinationIndex == 0 && count == source.Length)
            {
                // CopyTo(byte[], IBuffer)
                byte[]  source1      = Clone(source);
                IBuffer destination1 = Buffer(destination);
                WindowsRuntimeBufferExtensions.CopyTo(source1, destination1);
                Assert.Equal(expected, destination1.ToArray());

                // CopyTo(IBuffer, byte[])
                IBuffer source2      = Buffer(source);
                byte[]  destination2 = Clone(destination);
                WindowsRuntimeBufferExtensions.CopyTo(source2, destination2);
                Assert.Equal(expected, destination2);

                // CopyTo(IBuffer, IBuffer)
                IBuffer source3      = Buffer(source);
                IBuffer destination3 = Buffer(destination);
                WindowsRuntimeBufferExtensions.CopyTo(source3, destination3);
                Assert.Equal(expected, destination3.ToArray());
            }

            // CopyTo(byte[], int, IBuffer, int, int)
            byte[]  source4      = Clone(source);
            IBuffer destination4 = Buffer(destination);

            WindowsRuntimeBufferExtensions.CopyTo(source4, sourceIndex, destination4, (uint)destinationIndex, count);
            Assert.Equal(expected, destination4.ToArray());

            // CopyTo(IBuffer, int, byte[], int, int)
            IBuffer source5 = Buffer(source);

            byte[] destination5 = Clone(destination);
            WindowsRuntimeBufferExtensions.CopyTo(source5, (uint)sourceIndex, destination5, destinationIndex, count);
            Assert.Equal(expected, destination5);

            // CopyTo(IBuffer, int, IBuffer, int, int)
            IBuffer source6      = Buffer(source);
            IBuffer destination6 = Buffer(destination);

            WindowsRuntimeBufferExtensions.CopyTo(source6, (uint)sourceIndex, destination6, (uint)destinationIndex, (uint)count);
            Assert.Equal(expected, destination6.ToArray());
        }
        async void sendusb() // Send to
        {
            // Declare the output report
            var outputReport = DeviceList.Current.CurrentDevice.CreateOutputReport();

            // Declare an output buffer
            Byte[] outputBuffer = new Byte[64];

            //Control bits.
            outputBuffer[0] = 1;

            // Copies bytes from bytesToCopy to outputReport
            WindowsRuntimeBufferExtensions.CopyTo(outputBuffer, 0, outputReport.Data, 1, outputBuffer.Length);

            // Send the output report
            await DeviceList.Current.CurrentDevice.SendOutputReportAsync(outputReport);
        }
Esempio n. 15
0
//NON-USER INTERFACE METHODS

        //Verify keys with client and server
        private async void verifyKeys()
        {
            //Convert client key from IBUFFER to STRING
            IBuffer clientPublicKeyBUFFER = Crypto.returnPublicKey(App.secrets);

            byte[] clientPublicKeyBYTE = new byte[512];
            WindowsRuntimeBufferExtensions.CopyTo(clientPublicKeyBUFFER, clientPublicKeyBYTE);
            string clientPublicKeySTRING = Convert.ToBase64String(clientPublicKeyBYTE);

            String serverPublicKey;

            //GET request to server (fetch new messages from server at the same time)
            string publicKeyURL = App.userManagement.getPublicKey_string();

            if (publicKeyURL != null)
            {
                using (HttpClient client = new HttpClient())                                   //using block makes the object disposable (one time use)
                {
                    using (HttpResponseMessage response = await client.GetAsync(publicKeyURL)) //BUG:  HANDLE OFFLINE MODE
                    {
                        using (HttpContent content = response.Content)
                        {
                            string content_string = await content.ReadAsStringAsync();

                            System.Net.Http.Headers.HttpContentHeaders content_headers = content.Headers;
                            dynamic incomingJSON = JsonConvert.DeserializeObject(content_string);
                            serverPublicKey = incomingJSON.key;
                        }
                    }
                }
            }
            else
            {
                serverPublicKey = "-1";
            }
            if (clientPublicKeySTRING != serverPublicKey)
            {
                var dialog = new MessageDialog("Please Update your public key");
                dialog.Title = "WARNING:  Local and Server public keys are not in sync";
                dialog.Commands.Add(new UICommand {
                    Label = "Ok", Id = 0
                });
                var res = await dialog.ShowAsync();
            }
        }
        public void CopyTo_NegativeDestinationIndex_ThrowsArgumentOutOfRangeException()
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(new byte[0]);

            AssertExtensions.Throws <ArgumentOutOfRangeException>("destinationIndex", () => WindowsRuntimeBufferExtensions.CopyTo(buffer, 0, new byte[0], -1, 0));
        }