private async void SendPublicKeyForSecureTransfer(string sessionId)
        {
            // We need to generate a public/private key pair.
            KeyValuePair <string, string> cryptoKeyPair = CryptoProvider.GenerateKeys();

            // Store the Private Key, using its Public Key as the ID.
            SessionManager.Instance.sessions[cryptoKeyPair.Key] = cryptoKeyPair.Value;

            // Send the public key up to the server.
            // We need to include the sessionId so that the server knows
            // which message to encrypt and send down.
            log.Info("Sending generated public key, including sessionId");
            var cypherTextMessage = await _chatHubProxy.Invoke <Message>("GetMessageSecurely", new KeyValuePair <string, string>(sessionId, cryptoKeyPair.Key));

            log.Info("Recieved encrypted message");

            var message = CryptoProvider.Decrypt(cypherTextMessage, SessionManager.Instance.sessions[cryptoKeyPair.Key]);

            log.Info("Decrypted message");

            //Console.WriteLine("{0} {1}: {2}", DateTime.Now.ToShortTimeString(), message.Sender, message.MessageContent);
            printMessageUnobtrusively(message);

            // Remove the session from the session store
            SessionManager.Instance.sessions.Remove(cryptoKeyPair.Key);
        }
Esempio n. 2
0
 public string Decrypt(string encValue)
 {
     if (_password == null)
     {
         throw new InvalidOperationException("Secure Password not provided");
     }
     return(CryptoProvider.Decrypt <TripleDESCryptoServiceProvider>(encValue, _password));
 }
Esempio n. 3
0
        public void IllegalPtEncryptedVersionTest()
        {
            using var cryptoManager = new CryptoProvider();
            var exception =
                Assert.Throws <StorageCryptoException>(() => cryptoManager.Decrypt("someCypherText", null, 100500));

            Assert.AreEqual("Unknown cipher format", exception.Message);
        }
Esempio n. 4
0
 public string Decrypt(string encValue)
 {
     if (_password == null)
     {
         throw new InvalidOperationException("Secure Password not provided");
     }
     return(CryptoProvider.Decrypt <AesManaged>(encValue, _password));
 }
Esempio n. 5
0
        public void EncryptWithCustomCipherNegativeTest()
        {
            var          cipher           = new CipherWithException("some cipher");
            const string exceptionMessage = "some exception message";

#pragma warning disable CA1303
            var anotherCipher = new CipherWithException("another cipher", new StorageCryptoException(exceptionMessage));
#pragma warning restore CA1303
            using var provider = new CryptoProvider(cipher);
            provider.RegisterCipher(anotherCipher);

            var key        = new CustomEncryptionKey(1, Encoding.UTF8.GetBytes("Custom Encryption Key 32 symbols"));
            var secretData = new SecretsData(new List <Secret> {
                key
            }, key);

            var exception = Assert.Throws <StorageCryptoException>(() =>
                                                                   provider.Decrypt("c" + Guid.NewGuid() + ":123", secretData, 1));
            Assert.AreEqual("Unknown cipher format", exception.Message);

            exception = Assert.Throws <StorageCryptoException>(() =>
                                                               provider.Decrypt("z" + Guid.NewGuid() + ":123", secretData, 1));
            Assert.AreEqual("Unknown cipher format", exception.Message);

            exception = Assert.Throws <StorageCryptoException>(() =>
                                                               provider.Encrypt(Guid.NewGuid().ToString(), secretData));
            Assert.AreEqual("Unexpected exception during encryption", exception.Message);
            Assert.NotNull(exception.InnerException);

            exception = Assert.Throws <StorageCryptoException>(() =>
                                                               provider.Decrypt("cc29tZSBjaXBoZXI=:c29tZSBjaXBoZXI=", secretData, 1));
            Assert.AreEqual("Unexpected error", exception.Message);
            Assert.IsNotNull(exception.InnerException);

            exception = Assert.Throws <StorageCryptoException>(() =>
                                                               provider.Decrypt("cYW5vdGhlciBjaXBoZXI=:YW5vdGhlciBjaXBoZXI=", secretData, 1));
            Assert.AreEqual(exceptionMessage, exception.Message);

            using var anotherProvider = new CryptoProvider(anotherCipher);
            exception = Assert.Throws <StorageCryptoException>(() =>
                                                               anotherProvider.Encrypt(Guid.NewGuid().ToString(), secretData));
            Assert.AreEqual(exceptionMessage, exception.Message);
        }
Esempio n. 6
0
        public void DecryptAesGcm10KHexTest()
        {
            const string CipherMessageV1 =
                "1:8b02d29be1521e992b49a9408f2777084e9d8195e4a3392c68c70545eb559670b70ec928c8eeb2e34f118d32a23d77abdcde38446241efacb71922579d1dcbc23fca62c1f9ec5d97fbc3a9862c0a9e1bb630aaa3585eac160a65b24a96af5becef3cdc2b29";

            using var cryptoManager = new CryptoProvider();
            var decryptedMessage =
                cryptoManager.Decrypt(CipherMessageV1, SecretsDataGenerator.FromPassword("password"), 0);

            Assert.AreEqual("InCountry", decryptedMessage);
        }
Esempio n. 7
0
        public void DecryptUnknownTest()
        {
            const string CipherMessageV1 =
                "unknown";

            using var cryptoManager = new CryptoProvider();
            var exception = Assert.Throws <StorageCryptoException>(() =>
                                                                   cryptoManager.Decrypt(CipherMessageV1, SecretsDataGenerator.FromPassword("password"), 0));

            Assert.AreEqual("Unknown cipher format", exception.Message);
        }
        public async Task <List <Message> > GetAllMessages(string dialogName, Activity context)
        {
            List <Message> messageList = new List <Message>();

            if (FirebaseController.instance.app == null)
            {
                FirebaseController.instance.initFireBaseAuth();
            }
            try
            {
                client = new Firebase.Database.FirebaseClient("https://easymessage-1fa08.firebaseio.com/chats/");
                var p = await client.Child(dialogName).OnceAsync <Message>();

                var enumerator = p.GetEnumerator();
                enumerator.MoveNext();
                while (enumerator.Current != null)
                {
                    Message temp = enumerator.Current.Object;
                    if (temp.flags[0] != MessageFlags.Key)
                    {
                        if (temp.flags[0] != MessageFlags.Encoded)
                        {
                            messageList.Add(temp);
                        }
                        else
                        {
                            if (temp.senderP != AccountsController.mainAccP.emailP)
                            {
                                CryptoProvider c = new CryptoProvider();
                                temp.contentP = c.Decrypt(temp.contentP, AccountsController.mainAccP.privateKeyRsaP);
                                messageList.Add(temp);
                            }
                            else
                            {
                                messageList.Add(temp);
                            }
                        }
                    }
                    enumerator.MoveNext();
                }
                return(messageList);
            }
            catch (Newtonsoft.Json.JsonReaderException exc)
            {
                return(messageList);
            }
            catch (Exception ex)
            {
                Utils.MessageBox(ex.Message, context);
                return(messageList);
            }
        }
Esempio n. 9
0
        public void CryptoProvider_Encrypt_Decrypt_Succeeds(
            string value,
            string secret,
            string saltKey)
        {
            // Arrange
            var cryptoProvider = new CryptoProvider();

            // Act
            var encryptedString = cryptoProvider.Encrypt(value, secret, saltKey);
            var decryptedString = cryptoProvider.Decrypt(encryptedString, secret, saltKey);

            // Assert
            Assert.NotEqual(encryptedString, decryptedString);
            Assert.Equal(value, decryptedString);
        }
Esempio n. 10
0
 private static string DecryptAppSetting(string settingName)
 {
     var plainText = string.Empty;
     var cipherText = ConfigurationManager.AppSettings[settingName];
     if (!string.IsNullOrWhiteSpace(cipherText))
     {
         try
         {
             plainText = CryptoProvider.Decrypt(cipherText);
         }
         catch(Exception ex)
         {
             //ignore
         }
     }
     return plainText;
 }
Esempio n. 11
0
        public void CryptoProvider_Decrypt_WithEmptyArgument_ThrowsArgumentNullException(
            string value,
            string secret,
            string saltKey,
            string paramName)
        {
            // Arrange
            var cryptoProvider = new CryptoProvider();

            // Act
            // Assert
            var exception = Assert.Throws <ArgumentNullException>(() =>
            {
                cryptoProvider.Decrypt(value, secret, saltKey);
            });

            Assert.Equal(paramName, exception.ParamName);
        }
Esempio n. 12
0
        /// <summary>
        ///     AES Decryption service.
        /// </summary>
        /// <param name="toDecryption">CLI input model.</param>
        /// <returns>CLI output model with information about decryption.</returns>
        public static SymmetricCryptographyCliOutput DecryptionRequest(ISymmetricCryptographyCliInput toDecryption, CryptoProvider cryptoProvider)
        {
            Log.Information($"New aes decryption request => {toDecryption.CipherType}");

            if (string.IsNullOrEmpty(toDecryption.Content))
            {
                Log.Information("Data which should be decrypted missing - asking user for input.");

                toDecryption.Content = CLIHelpers.InformationProvider("Enter entrycpted phrase");
            }

            if (string.IsNullOrEmpty(toDecryption.Key))
            {
                Log.Information("The encryption key is missing - asking user for input.");

                toDecryption.Key = CLIHelpers.InformationProvider("Enter encryption key");
            }

            if (string.IsNullOrEmpty(toDecryption.InitializationVector) && toDecryption.CipherType.CipherMode != CipherMode.ECB)
            {
                Log.Information("The initialization vector is missing - asking user for input");

                toDecryption.InitializationVector = CLIHelpers.InformationProvider("Enter initialization vector");
            }

            SymmetricCryptographyProperties cryptoProperties;

            if (toDecryption.CipherType.CipherMode == CipherMode.ECB)
            {
                // ignore IV when ECB cipher mode is used
                cryptoProperties = new SymmetricCryptographyProperties(toDecryption.Key, toDecryption.CipherType.CipherMode);
            }
            else
            {
                cryptoProperties = new SymmetricCryptographyProperties(toDecryption.Key, toDecryption.InitializationVector, toDecryption.CipherType.CipherMode);
            }

            cryptoProvider.CryptographyProperties = cryptoProperties;
            var decrypted = cryptoProvider.Decrypt(toDecryption.Content);

            Log.Information("Successfully decrypted.");

            return(new SymmetricCryptographyCliOutput(decrypted));
        }
Esempio n. 13
0
        public void EncryptWithCustomCipherTest()
        {
            var cipher = new FernetCipher("Fernet cipher");

            using var provider = new CryptoProvider(cipher);
            const int version    = 5;
            var       key        = new CustomEncryptionKey(version, Encoding.UTF8.GetBytes("Custom Encryption Key 32 symbols"));
            var       secretData = new SecretsData(new List <Secret> {
                key
            }, key);
            var message      = "{'private_data':'" + Guid.NewGuid() + "'}";
            var cipheredData = provider.Encrypt(message, secretData);

            Assert.NotNull(cipheredData);
            Assert.AreEqual(version, cipheredData.KeyVersion);
            Assert.NotNull(cipheredData.Data);
            Assert.AreNotEqual(message, cipheredData.Data);
            Assert.IsTrue(cipheredData.Data.StartsWith("c", StringComparison.InvariantCulture));
            var decryptedText = provider.Decrypt(cipheredData.Data, secretData, cipheredData.KeyVersion);

            Assert.AreEqual(message, decryptedText);
        }
Esempio n. 14
0
        /// <summary>
        /// Broadcast message to all connected clients.
        /// </summary>
        /// <param name="message"></param>
        public void SendMessage(Message message)
        {
            // The message passed in will have encrypted fields. We
            // need to decrypt these fields using the right private key.
            var privateKeyString = SessionManager.Instance.sessions[message.PublicKey];

            // Decrypt the message with the private key.
            var plainTextMessage = CryptoProvider.Decrypt(message, privateKeyString);

            // Remove the session from the session dictionary.
            SessionManager.Instance.sessions.Remove(message.PublicKey);

            //-----------------------------------------
            // Initiate a secure broadcast.

            // Use the original public key as a sessionId.
            AskForPublicKeys(message.PublicKey);

            // Set a TTL and store this message against it's ID (the old public key).
            message.Expires = DateTime.Now + TimeSpan.FromMinutes(5);
            SessionManager.Instance.WaitingMessages.Add(message.PublicKey, plainTextMessage);

            //Clients.All.AddNewMessage(message);
        }
Esempio n. 15
0
        public static void MarshalPacket(Session session, string packet)
        {
            // command packet will always have at least 3 elements (seq, command, parameters...)
            string[] commandExplode = packet.TrimEnd('\n').Split('|');
            if (commandExplode.Length < 2)
            {
                return;
            }

            uint sequence;

            if (!uint.TryParse(commandExplode[0], out sequence))
            {
                return;
            }

            string command = commandExplode[1];

            string[] parameters = new string[commandExplode.Length - 2];
            Array.Copy(commandExplode, 2, parameters, 0, parameters.Length);

            // $@ is an encrypted transport packet, need to decryt first to obtain actual command
            if (command.StartsWith("$@"))
            {
                if (commandExplode.Length != 3)
                {
                    return;
                }

                try
                {
                    // decrypt and rebuild command to be parsed again
                    MarshalPacket(session, $"{commandExplode[0]}|{CryptoProvider.Decrypt(commandExplode[1].Remove(0, 2), commandExplode[2])}");
                }
                catch
                {
                    string source = session.Account?.Username ?? session.IpAddress;
                    LogManager.Write("Player", $"Malformed packet from {source}, failed to decrypt!");
                }
            }
            else
            {
                ClientCommandCached clientCommandCached;
                if (!clientCommandCache.TryGetValue(command, out clientCommandCached))
                {
                    LogManager.Write("Network", $"Received unknown packet {command}!");
                    return;
                }

                object instance = Activator.CreateInstance(clientCommandCached.Command);
                for (uint i = 2; i < commandExplode.Length; i++)
                {
                    // parameter will always have 2 values (key, element)
                    var parameter = commandExplode[i].Split(':');
                    if (parameter.Length != 2)
                    {
                        return;
                    }

                    PropertyInfo property;
                    if (!clientCommandCached.Fields.TryGetValue(parameter[0], out property))
                    {
                        LogManager.Write("Network", $"Unhandled element '{parameter[0]}' for command '{command}'!");
                        continue;
                    }

                    if (property.CanWrite)
                    {
                        property.SetValue(instance, Convert.ChangeType(parameter[1], property.PropertyType, null));
                    }
                }

                ((ClientCommand)instance).Handle(session);
            }
        }
Esempio n. 16
0
        }// end:OpenContent()


        // ---------------------- OpenEncryptedContent -----------------------
        /// <summary>
        ///   Loads and displays a given encrypted content file.</summary>
        /// <param name="encryptedFile">
        ///   The path and name of the encrypted file to display.</param>
        /// <returns>
        ///   true if the file loads successfully; otherwise false.</returns>
        public bool OpenEncryptedContent(string encryptedFile)
        {
            // Get the ID of the current user log-in.
            string currentUserId;
            try
                { currentUserId = GetDefaultWindowsUserName(); }
            catch
                { currentUserId = null; }
            if (currentUserId == null)
            {
                MessageBox.Show("No valid user ID available", "Invalid User ID",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                ShowStatus("   No valid user ID available.");
                return false;
            }

            ShowStatus("   Current user ID:  '" + currentUserId + "'");
            ShowStatus("   Using " + _authentication + " authentication.");
            ShowStatus("   Checking rights list for user:\n       " +
                           currentUserId);
            ShowStatus("   Initializing the environment.");

            try
            {
                string applicationManifest = "<manifest></manifest>";
                if (File.Exists("rvc.xml"))
                {
                    ShowStatus("   Reading manifest 'rvc.xml'.");
                    StreamReader manifestReader = File.OpenText("rvc.xml");
                    applicationManifest = manifestReader.ReadToEnd();
                }

                if (_secureEnv == null)
                {
                    ShowStatus("   Initiating SecureEnvironment as user:\n   " +
                        "    " + currentUserId + " [" + _authentication + "]");
                    if (SecureEnvironment.IsUserActivated(
                        new ContentUser(currentUserId, _authentication)))
                    {
                        ShowStatus("   User is already activated.");
                        _secureEnv = SecureEnvironment.Create(
                                                applicationManifest,
                                                new ContentUser(currentUserId,
                                                    _authentication) );
                    }
                    else // if user is not yet activated.
                    {
                        ShowStatus("   User is NOT activated,\n" +
                                   "       activating now....");
                        // If using the current Windows user, no credentials are
                        // required and we can use UserActivationMode.Permanent.
                        _secureEnv = SecureEnvironment.Create(
                                                applicationManifest,
                                                _authentication,
                                                UserActivationMode.Permanent );

                        // If not using the current Windows user, use
                        // UserActivationMode.Temporary to display the Windows
                        // credentials pop-up window.
                        //  _secureEnv = SecureEnvironment.Create(
                        //                        applicationManifest,
                        //                        _authentication,
                        //                        UserActivationMode.Temporary);
                    }
                    ShowStatus("   Created SecureEnvironment for user:\n       " +
                        _secureEnv.User.Name +
                        " [" + _secureEnv.User.AuthenticationType + "]");
                }

                // If the file is a supported image, show it in the image control.
                try
                {
                    // In this sample a UseLicense is provided with the example
                    // content files.  If the UseLicense for the current user
                    // does not exist, the following steps can be performed to
                    // obtain a UseLicense:
                    //   1. Open the PublishLicense.
                    //   2. Read the PublishLicense XML file to a string.
                    //   3. Create a PublishLicense instance passing the
                    //      PublishLicense string to the constructor.
                    //   4. Pass the PublishLicense to the license server to
                    //      obtain a UseLicense.

                    // Check if there is a UseLicense for the encryptedFile.
                    string useLicenseFile = encryptedFile;
                    if (encryptedFile.EndsWith(".protected"))
                    {   // Remove ".protected" from the file name.
                        useLicenseFile = useLicenseFile.Remove(
                            useLicenseFile.Length - ".protected".Length );
                    }
                    // Append ".UseLicense.xml" as the UseLicense file extension.
                    useLicenseFile = useLicenseFile + ".UseLicense.xml";
                    if (!File.Exists(useLicenseFile))
                    {
                        MessageBox.Show(useLicenseFile + "\n\nUseLicense for '" +
                            Filename(encryptedFile) + "' not found.",
                            "UseLicense Not Found",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                        ShowStatus("   UseLicense not found:\n      '" +
                                    Filename(useLicenseFile) + "'.");
                        return false;
                    }

                    ShowStatus("   Reading UseLicense '" +
                                   Filename(useLicenseFile) + "'.");
                    StreamReader useLicenseStream = File.OpenText(useLicenseFile);
                    string useLicenseString = useLicenseStream.ReadToEnd();
                    UseLicense useLicense = new UseLicense(useLicenseString);

                    ShowStatus("   Binding UseLicense with the SecureEnvironment" +
                             "\n       to obtain the CryptoProvider.");
                    CryptoProvider cryptoProvider = useLicense.Bind(_secureEnv);

                    ShowStatus("   Obtaining BoundGrants.");
                    ReadOnlyCollection<ContentGrant> grants =
                        cryptoProvider.BoundGrants;

                    rightsBlockTitle.Text = "Rights - " + Filename(useLicenseFile);
                    rightsBlock.Text = "GRANTS LIST\n-----------------\n";
                    foreach (ContentGrant grant in grants)
                    {
                        rightsBlock.Text += "USER:  "******" [" +
                            grant.User.AuthenticationType + "]\n";
                        rightsBlock.Text += "RIGHT: " + grant.Right.ToString() + "\n";
                        rightsBlock.Text += "    From:  " + grant.ValidFrom + "\n";
                        rightsBlock.Text += "    Until: " + grant.ValidUntil + "\n";
                    }

                    if (cryptoProvider.CanDecrypt == true)
                        ShowStatus("   Decryption granted.");
                    else
                        ShowStatus("   CANNOT DECRYPT!");

                    ShowStatus("   Decrypting '"+Filename(encryptedFile)+"'.");
                    byte[] imageBuffer;
                    using (Stream cipherTextStream = File.OpenRead(encryptedFile))
                    {
                        byte[] contentLengthByteBuffer = new byte[sizeof(Int32)];
                        // Read the length of the source content file
                        // from the first four bytes of the encrypted file.
                        ReliableRead(cipherTextStream, contentLengthByteBuffer,
                                     0, sizeof(Int32));

                        // Allocate the clearText buffer.
                        int contentLength =
                            BitConverter.ToInt32(contentLengthByteBuffer, 0);
                        imageBuffer = new byte[contentLength];

                        // Allocate the cipherText block.
                        byte[] cipherTextBlock =
                            new byte[cryptoProvider.BlockSize];

                        // decrypt cipherText to clearText block by block.
                        int imageBufferIndex = 0;
                        for ( ; ; )
                        {   // Read cipherText block.
                            int readCount = ReliableRead(
                                                cipherTextStream,
                                                cipherTextBlock, 0,
                                                cryptoProvider.BlockSize);
                            // readCount of zero is end of data.
                            if (readCount == 0)
                                break; // for

                            // Decrypt cipherText to clearText.
                            byte[] clearTextBlock =
                                cryptoProvider.Decrypt(cipherTextBlock);

                            // Copy the clearTextBlock to the imageBuffer.
                            int copySize = Math.Min(clearTextBlock.Length,
                                                contentLength-imageBufferIndex);
                            Array.Copy(clearTextBlock, 0,
                                imageBuffer, imageBufferIndex, copySize);
                            imageBufferIndex += copySize;
                        }
                    }// end:using (Stream cipherTextStream = (close/dispose)

                    ShowStatus("   Displaying decrypted image.");
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = new MemoryStream(imageBuffer);
                    bitmapImage.EndInit();
                    ImageViewer.Source = bitmapImage;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(encryptedFile + "\n\nThe specified file " +
                        "in not a valid unprotected image file.\n\n" +
                        "Exception: " + ex.Message + "\n\n" +
                        ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                        "Invalid File Format",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }// end:try
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            return true;
        }// end:OpenEncryptedContent()
        public async void OnChildAdded(DataSnapshot snapshot, string previousChildName)
        {
            IEnumerable <DataSnapshot> items = snapshot.Children?.ToEnumerable <DataSnapshot>();
            List <DataSnapshot>        t     = items.ToList();

            if (t.Count > 5)
            {
                var flag = t[2].Child("0").Value;
                List <MessageFlags> fls = new List <MessageFlags>();
                fls.Add((MessageFlags)Convert.ToInt32(flag.ToString()));

                var access             = t[0].Child("0").Value;
                List <AccessFlags> acs = new List <AccessFlags>();
                acs.Add((AccessFlags)Convert.ToInt32(access.ToString()));
                Message temp = new Message
                {
                    /*contentP = t[1].Value.ToString(),*/
                    flags      = fls,
                    receiverP  = t[3].Value.ToString(),
                    senderP    = t[4].Value.ToString(),
                    timeP      = t[5].Value.ToString(),
                    access     = acs,
                    dialogName = dialogName,
                    flagsP     = Convert.ToInt32(fls[0]),
                    accessP    = Convert.ToInt32(acs[0])
                };
                if (fls[0] != MessageFlags.Key)
                {
                    if (fls[0] == MessageFlags.Encoded)
                    {
                        if (t[4].Value.ToString() != AccountsController.mainAccP.emailP)
                        {
                            CryptoProvider c = new CryptoProvider();
                            temp.contentP = c.Decrypt(t[1].Value.ToString(), AccountsController.mainAccP.privateKeyRsaP);
                        }
                        else
                        {
                            temp.contentP = t[1].Value.ToString();
                        }
                    }
                    else
                    {
                        temp.contentP = t[1].Value.ToString();
                    }
                    MessagesController.instance.CreateTable();
                    if (MessagesController.instance.FindItem(temp) == null)
                    {
                        var mess = MessagesController.instance.GetItems().ToList();
                        if (mess.Count < 50)
                        {
                            MessagesController.instance.SaveItem(temp, 0);
                        }
                        else
                        {
                            MessagesController.instance.DeleteItem(mess[0].Id);
                            MessagesController.instance.SaveItem(temp, 0);
                        }
                    }
                }
                else
                {
                    if (temp.senderP != AccountsController.mainAccP.emailP)
                    {
                        ContactsController.instance.CreateTable();
                        Contact tempC = ContactsController.instance.FindContact(temp.senderP);
                        if (tempC == null)
                        {
                            ContactsController.instance.SaveItem(new Contact
                            {
                                contactAddressP    = temp.senderP,
                                contactNameP       = "user name",
                                contactRsaOpenKeyP = t[1].Value.ToString(),
                                dialogNameP        = temp.dialogName,
                                deletedP           = false
                            });
                        }
                        else
                        {
                            ContactsController.instance.SaveItem(new Contact
                            {
                                contactAddressP    = tempC.contactAddressP,
                                contactNameP       = tempC.contactNameP,
                                contactRsaOpenKeyP = t[1].Value.ToString(),
                                dialogNameP        = tempC.dialogNameP,
                                Id       = tempC.Id,
                                deletedP = tempC.deletedP
                            });
                        }
                        connectivityManager = (ConnectivityManager)context.GetSystemService(Android.Content.Context.ConnectivityService);
                        networkInfo         = connectivityManager.ActiveNetworkInfo;
                        if (networkInfo != null && networkInfo.IsConnected == true)
                        {
                            await FirebaseController.instance.InsertKey(AccountsController.mainAccP.emailP, temp.senderP,
                                                                        t[1].Value.ToString(), context);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
 public void DecryptPtNullTest()
 {
     using var cryptoManager = new CryptoProvider();
     Assert.IsNull(cryptoManager.Decrypt("", null, 100500));
 }
Esempio n. 19
0
        public async void OnDataChange(DataSnapshot snapshot)
        {
            try
            {
                IEnumerable <DataSnapshot> items = snapshot.Children?.ToEnumerable <DataSnapshot>();
                List <DataSnapshot>        t     = items.ToList();

                if (flag == 0)
                {
                    var a    = t.Last().Children.ToEnumerable <DataSnapshot>().ToList();
                    var flag = a[2].Child("0").Value;
                    List <MessageFlags> fls = new List <MessageFlags>();
                    fls.Add((MessageFlags)Convert.ToInt32(flag.ToString()));

                    var access             = a[0].Child("0").Value;
                    List <AccessFlags> acs = new List <AccessFlags>();
                    acs.Add((AccessFlags)Convert.ToInt32(access.ToString()));

                    if (a[4].Value.ToString() != AccountsController.mainAccP.emailP && Convert.ToInt32(access.ToString()) == 2)
                    {
                        await MessagingController.instance.UpdateFlag(t.Last().Key, dialog, this);

                        DialogsController.instance.CreateTable();
                        DialogsController.instance.UpdateItem(dialog);
                        DialogsController.currDialP = new MyDialog();
                    }

                    Message m = new Message
                    {
                        flags     = fls,
                        receiverP = a[3].Value.ToString(),
                        senderP   = a[4].Value.ToString(),
                        timeP     = a[5].Value.ToString(),
                        access    = acs
                    };
                    if (fls[0] == MessageFlags.Encoded && m.senderP != AccountsController.mainAccP.emailP)
                    {
                        CryptoProvider c = new CryptoProvider();
                        m.contentP = c.Decrypt(a[1].Value.ToString(), AccountsController.mainAccP.privateKeyRsaP);
                    }
                    else
                    {
                        m.contentP = a[1].Value.ToString();
                    }

                    if (messageList.Find(x => x.timeP == m.timeP && x.contentP == m.contentP) == null)
                    {
                        if (messageList == null)
                        {
                            messageList = new List <Message>();
                        }
                        messageList.Add(m);
                        DialogsController.currDialP = new MyDialog();

                        /*DialogsController.currDialP = new MyDialog
                         * {
                         *  dialogName = dialog,
                         *  lastMessage = m,
                         *  contentP = m.contentP,
                         *  senderP = m.senderP,
                         *  receiverP = m.receiverP,
                         *  timeP = m.timeP,
                         *  accessFlag = Convert.ToInt32(m.access[0]),
                         *  messageFlag = Convert.ToInt32(m.flags[0])
                         * };*/

                        adapter = new RecyclerViewAdapter(messageList);
                        recyclerList.SetAdapter(adapter);
                        recyclerList.ScrollToPosition(messageList.Count() - 1);
                    }
                }
                else
                {
                    if (flag == 1)
                    {
                        List <DataSnapshot> results = new List <DataSnapshot>();
                        List <DataSnapshot> temp    = t.FindAll(x => x.Children.ToEnumerable <DataSnapshot>().ToList().Count > 5);
                        foreach (var i in temp)
                        {
                            var a = i.Children.ToEnumerable <DataSnapshot>().ToList();
                            if (a.Find(x => x.Key == "senderP" &&
                                       x.Value.ToString() != AccountsController.mainAccP.emailP) != null &&
                                a.Find(x => x.Key == "access" && Convert.ToInt32(x.Child("0").Value.ToString()) == 2) != null)
                            {
                                results.Add(i);
                            }
                        }
                        foreach (var k in results)
                        {
                            //flag = -1;
                            await MessagingController.instance.UpdateFlag(k.Key, dialog, this);

                            DialogsController.instance.CreateTable();
                            DialogsController.instance.UpdateItem(dialog);
                            DialogsController.currDialP = new MyDialog();
                        }
                        flag = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.MessageBox(ex.Message, this);
            }
        }
Esempio n. 20
0
        public bool Connect(string addr, int port = 0)
        {
            ErrorMessage = null;
            if (port == 0)
            {
                port = DefaultPort;
            }
            try
            {
                IsLogined = false;
                if (Client != null)
                {
                    Client.Dispose();
                }
            }
            catch
            { }

            try
            {
                //Loger.Log("Client Connect1");
                // Generate open-close keys  KClose-KOpen
                //Генерим рандомную пару КЗакр-КОткр
                var crypto = new CryptoProvider();
                if (UseCryptoKeys)
                {
                    crypto.GenerateKeys();
                }

                //Loger.Log("Client Connect2");
                Client = new ConnectClient(addr, port);

                //Loger.Log("Client Connect3");//Строго первый пакет: Передаем серверу КОткр
                if (UseCryptoKeys)
                {
                    Client.SendMessage(Encoding.UTF8.GetBytes(crypto.OpenKey));
                }
                else
                {
                    Client.SendMessage(new byte[1] {
                        0x00
                    });
                }

                //Loger.Log("Client Connect4");
                //Строго первый ответ: Передаем клиенту КОткр(Сессия)
                var rc = Client.ReceiveBytes();
                if (UseCryptoKeys)
                {
                    Key = crypto.Decrypt(rc);
                }
                else
                {
                    Key = rc;
                }

                //Loger.Log("Client Connect5");
                //Обмен по протоколу ниже: Передаем серверу Сессия(Логин - Пароль или запрос на создание)

                //Запускаем таймер фоново поддерживающий открытое соединение при простое
                ConnectSaver.AddClient(Client, (cl) =>
                {
                    lock (LockObj)
                    {
                        cl.SendMessage(new byte[1] {
                            0x00
                        });
                        cl.ReceiveBytes();
                    }
                });

                return(true);
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message
                               + (e.InnerException == null ? "" : " -> " + e.InnerException.Message);
                ExceptionUtil.ExceptionLog(e, "Client");
                return(false);
            }
        }
Esempio n. 21
0
        public Record GetRecord(TransferRecord transferRecord)
        {
            if (transferRecord == null)
            {
                s_log.Debug(Messages.DtoTransformer.s_errNullRecord);
                return null;
            }

            ValidateTransferRecord(transferRecord);
            var recordVersion = transferRecord.Version ?? 0;
            var secretsData = GetSecretsData(SecretKeyAccessor != null);

            var complexBodyJson = _cryptoProvider.Decrypt(transferRecord.Body, secretsData, recordVersion);
            string precommitBody = null;
            if (!string.IsNullOrEmpty(transferRecord.PrecommitBody))
            {
                precommitBody = _cryptoProvider.Decrypt(transferRecord.PrecommitBody, secretsData, recordVersion);
            }

            var complexBody = JsonConvert.DeserializeObject<ComplexBody>(complexBodyJson, _jsonSettings);
            var resultRecord = new Record(complexBody.Meta.RecordKey ?? complexBody.Meta.Key,
                complexBody.Payload,
                precommitBody,
                complexBody.Meta.ProfileKey,
                complexBody.Meta.Key1,
                complexBody.Meta.Key2,
                complexBody.Meta.Key3,
                complexBody.Meta.Key4,
                complexBody.Meta.Key5,
                complexBody.Meta.Key6,
                complexBody.Meta.Key7,
                complexBody.Meta.Key8,
                complexBody.Meta.Key9,
                complexBody.Meta.Key10,
                complexBody.Meta.Key11,
                complexBody.Meta.Key12,
                complexBody.Meta.Key13,
                complexBody.Meta.Key14,
                complexBody.Meta.Key15,
                complexBody.Meta.Key16,
                complexBody.Meta.Key17,
                complexBody.Meta.Key18,
                complexBody.Meta.Key19,
                complexBody.Meta.Key20,
                complexBody.Meta.ServiceKey1,
                complexBody.Meta.ServiceKey2,
                transferRecord.RangeKey1,
                transferRecord.RangeKey2,
                transferRecord.RangeKey3,
                transferRecord.RangeKey4,
                transferRecord.RangeKey5,
                transferRecord.RangeKey6,
                transferRecord.RangeKey7,
                transferRecord.RangeKey8,
                transferRecord.RangeKey9,
                transferRecord.RangeKey10,
                transferRecord.CreatedAt,
                transferRecord.UpdatedAt,
                complexBody.Meta.ParentKey,
                recordVersion,
                transferRecord.Attachments == null || transferRecord.Attachments.Count == 0
                    ? null
                    : transferRecord.Attachments
            );
            return resultRecord;
        }
Esempio n. 22
0
 public static byte[] QuickDecrypt(this byte[] data) => cp.Decrypt(data);