Exemplo n.º 1
0
        private TransferRecord GetEncryptedTransferRecord(string complexBody, Record originalRecord)
        {
            var secretsData = GetSecretsData(SecretKeyAccessor != null);
            var encryptedBodyPair = _cryptoProvider.Encrypt(complexBody, secretsData);

            var resultRecord = new TransferRecord(_hashUtils.GetSha256Hash(originalRecord.RecordKey),
                encryptedBodyPair.Data,
                originalRecord.PrecommitBody != null
                    ? _cryptoProvider.Encrypt(originalRecord.PrecommitBody, secretsData).Data
                    : null,
                _hashUtils.GetSha256Hash(originalRecord.ProfileKey),
                TransformSearchKey(originalRecord.Key1, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key2, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key3, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key4, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key5, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key6, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key7, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key8, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key9, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key10, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key11, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key12, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key13, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key14, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key15, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key16, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key17, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key18, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key19, _hashSearchKeys),
                TransformSearchKey(originalRecord.Key20, _hashSearchKeys),
                _hashUtils.GetSha256Hash(originalRecord.ServiceKey1),
                _hashUtils.GetSha256Hash(originalRecord.ServiceKey2),
                originalRecord.RangeKey1,
                originalRecord.RangeKey2,
                originalRecord.RangeKey3,
                originalRecord.RangeKey4,
                originalRecord.RangeKey5,
                originalRecord.RangeKey6,
                originalRecord.RangeKey7,
                originalRecord.RangeKey8,
                originalRecord.RangeKey9,
                originalRecord.RangeKey10,
                parentKey: _hashUtils.GetSha256Hash(originalRecord.ParentKey),
                version: encryptedBodyPair.KeyVersion,
                isEncrypted: SecretKeyAccessor != null
            );

            return resultRecord;
        }
Exemplo n.º 2
0
        public async Task <User> Register(string username, string password)
        {
            var userServiceModel = await _usersService.RegisterUser(username.ToLower()) ?? await _usersService.GetUser(username.ToLower());

            if (userServiceModel == null)
            {
                return(null);
            }

            if (!await _portfolioService.CreatePortfolio(userServiceModel.UserId))
            {
                return(null);
            }
            if (!await _bankService.CreateBankAndAccount(userServiceModel.UserId))
            {
                return(null);
            }

            var cipher = CryptoProvider.Encrypt(new CryptoProvider.Plain {
                Password = password
            });
            var user = new User
            {
                UserId   = userServiceModel.UserId,
                Username = userServiceModel.Email,
                Hash     = cipher.Hash,
                Salt     = cipher.Salt
            };

            _unitOfWork.AuthenticationRepository.Register(user);
            await _unitOfWork.CommitAsync();

            return(user);
        }
Exemplo n.º 3
0
 public string Encrypt(string value)
 {
     if (_password == null)
     {
         throw new InvalidOperationException("Secure Password not provided");
     }
     return(CryptoProvider.Encrypt <TripleDESCryptoServiceProvider>(value, _password));
 }
Exemplo n.º 4
0
 public string Encrypt(string value)
 {
     if (_password == null)
     {
         throw new InvalidOperationException("Secure Password not provided");
     }
     return(CryptoProvider.Encrypt <AesManaged>(value, _password));
 }
Exemplo n.º 5
0
        public void Do(ConnectClient client)
        {
            Client = client;

            Loger.Log("Server ReceiveBytes1");

            ///установка условно защищенного соединения
            //Строго первый пакет: Передаем серверу КОткр
            var rc     = Client.ReceiveBytes();
            var crypto = new CryptoProvider();

            if (SessionClient.UseCryptoKeys)
            {
                crypto.OpenKey = Encoding.UTF8.GetString(rc);
            }

            //Строго первый ответ: Передаем клиенту КОткр(Сессия)
            SetKey();
            Loger.Log("Server SendMessage1");
            if (SessionClient.UseCryptoKeys)
            {
                Client.SendMessage(crypto.Encrypt(Key));
            }
            else
            {
                Client.SendMessage(Key);
            }

            //if (LogMessage != null) LogMessage("session Connected");

            Worker = new Service();

            ///рабочий цикл
            while (true)
            {
                //Loger.Log("Server Loop1");
                var rec = Client.ReceiveBytes();
                //Loger.Log("Server Loop2");
                var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key);
                //Loger.Log("Server " + Loger.Bytes(rec2));
                //Loger.Log("Server Loop3");
                var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize
                //Loger.Log("Server Loop4");

                var sendObj = Service(recObj);

                //Loger.Log("Server Loop5");
                var ob = GZip.ZipObjByte(sendObj); //Serialize
                //Loger.Log("Server Loop6");
                var send = CryptoProvider.SymmetricEncrypt(ob, Key);
                //Loger.Log("Server Loop7");
                Client.SendMessage(send);
            }
        }
Exemplo n.º 6
0
        public Message GetMessageSecurely(KeyValuePair <string, string> sessionIDPublicKeyPair)
        {
            // Fetch the message indicated by the sessionId in the KV pair passed in.
            var plainTextMessage = SessionManager.Instance.WaitingMessages[sessionIDPublicKeyPair.Key];

            // Encrypt the fields on the message using the public key in the KV pair passed in.
            var cypherTextMessage = CryptoProvider.Encrypt(sessionIDPublicKeyPair.Value, plainTextMessage);

            // Remove any expired messages from the WaitingMessages dictionary.
            //RemoveExpiredMessages();

            return(cypherTextMessage);
        }
Exemplo n.º 7
0
        /// <summary>
        ///     AES Encryption service.
        /// </summary>
        /// <param name="toEncryption">CLI input model.</param>
        /// <returns>CLI output model with information about decryption.</returns>
        public static SymmetricCryptographyCliOutput EncryptionRequest(ISymmetricCryptographyCliInput toEncryption, CryptoProvider cryptoProvider)
        {
            Log.Information($"New aes encryption request => {toEncryption.CipherType}");

            byte[] key = null;
            byte[] IV  = null;

            // check if user provide encryption key
            if (!string.IsNullOrEmpty(toEncryption.Key))
            {
                Log.Information("Working with the provided encryption key.");

                key = Convert.FromBase64String(toEncryption.Key);
            }
            else
            {
                Log.Information("Generating new encryption key.");

                key = cryptoProvider.GenerateKey(toEncryption.CipherType.KeySize);
            }

            // check if user provide IV
            if (!string.IsNullOrEmpty(toEncryption.InitializationVector) && toEncryption.CipherType.CipherMode != CipherMode.ECB)
            {
                Log.Information("Working with the provided initialization vector.");

                Console.WriteLine("Using same initialization vector for more then one encryption is not recommended!");
                IV = Convert.FromBase64String(toEncryption.InitializationVector);
            }
            else
            {
                Log.Information("Generating new initialization vector.");

                IV = cryptoProvider.GenerateInitializationVector();
            }

            var encrypted = cryptoProvider.Encrypt(toEncryption.Content, key, IV, toEncryption.CipherType.CipherMode);

            Log.Information("Successfully encrypted.");

            if (toEncryption.CipherType.CipherMode == CipherMode.ECB)
            {
                return(new SymmetricCryptographyCliOutput(key, encrypted, toEncryption.CipherType));
            }
            else
            {
                return(new SymmetricCryptographyCliOutput(IV, key, encrypted, toEncryption.CipherType));
            }
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
        public void CryptoProvider_Encrypt_WithEmptyArgument_ThrowsArgumentNullException(
            string value,
            string secret,
            string saltKey,
            string paramName)
        {
            // Arrange
            var cryptoProvider = new CryptoProvider();

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

            Assert.Equal(paramName, exception.ParamName);
        }
Exemplo n.º 10
0
        public void DefaultCurrentCipherTest()
        {
            const int secretVersion = 7;
            var       secret        = new EncryptionSecret(secretVersion, Encoding.UTF8.GetBytes("password"));

            using var cipher         = new AesGcmPbkdf10KBase64Cipher(Encoding.UTF8);
            using var cryptoProvider = new CryptoProvider();
            var text          = Guid.NewGuid().ToString();
            var encryptResult =
                cryptoProvider.Encrypt(text, new SecretsData(new List <Secret> {
                secret
            }, secret));

            Assert.NotNull(encryptResult);
            Assert.AreEqual(secretVersion, encryptResult.KeyVersion);
            var decrypted = cipher.Decrypt(encryptResult.Data.Substring(2), secret);

            Assert.AreEqual(text, decrypted);
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
0
        public async Task SendMessage(string message)
        {
            log.Info("Getting public key for transfer");
            // Get a public key from the server.
            var publicKey = await _chatHubProxy.Invoke <string>("GetPublicKeyForSecureTransfer");

            log.Info("Encrypting message");
            // Encrypt the message data
            var cypherMessage = CryptoProvider.Encrypt(publicKey, new Message()
            {
                Sender = _nick, MessageContent = message
            });

            // Send the encrypted message, include the public key so the server can identify the session.
            cypherMessage.PublicKey = publicKey;

            log.Info("Attempting to send message");
            await _chatHubProxy.Invoke <Message>("SendMessage", cypherMessage);

            log.Info("Sent");
        }
Exemplo 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);
        }
Exemplo n.º 14
0
 private static void EncryptAppSetting(string settingName, string value)
 {
     SaveAppSetting(settingName, CryptoProvider.Encrypt(value));
 }
Exemplo n.º 15
0
        protected async override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.dialog);

                loadProgress   = FindViewById <ProgressBar>(Resource.Id.loadMessProgress);
                messageContent = FindViewById <EditText>(Resource.Id.edittext_chatbox);
                send           = FindViewById <Button>(Resource.Id.send);

                connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService);
                networkInfo         = null;

                dialog   = Intent.GetStringExtra("dialogName");
                receiver = Intent.GetStringExtra("receiver");
                flag     = Intent.GetIntExtra("flag", 0);
                SupportActionBar.SetHomeButtonEnabled(true);
                SupportActionBar.SetDisplayHomeAsUpEnabled(true);
                SupportActionBar.SetBackgroundDrawable(new ColorDrawable(Color.ParseColor("#2196f3")));
                ContactsController.instance.CreateTable();
                if (receiver != null)
                {
                    if (ContactsController.instance.ReturnContactName(receiver) != null)
                    {
                        SupportActionBar.Title = ContactsController.instance.ReturnContactName(receiver);
                    }
                }

                if (FirebaseController.instance.app == null)
                {
                    FirebaseController.instance.initFireBaseAuth();
                }
                var layoutManager = new LinearLayoutManager(this)
                {
                    Orientation = LinearLayoutManager.Vertical
                };
                recyclerList = FindViewById <RecyclerView>(Resource.Id.reyclerview_message_list);
                recyclerList.SetLayoutManager(layoutManager);

                MessagingController.instance.ReturnLastMessages(dialog, this);

                MessagesController.instance.CreateTable();
                messageList = MessagesController.instance.GetItems().ToList().FindAll(x => x.dialogName == dialog);

                loadProgress.Visibility = ViewStates.Visible;
                bool result = await fill_list();

                loadProgress.Visibility = ViewStates.Invisible;
                adapter = new RecyclerViewAdapter(messageList);

                recyclerList.SetAdapter(adapter);
                recyclerList.ScrollToPosition(messageList.Count() - 1);

                networkInfo = connectivityManager.ActiveNetworkInfo;
                if (networkInfo != null && networkInfo.IsConnected == true)
                {
                    FirebaseDatabase databaseInstance = FirebaseDatabase.GetInstance(FirebaseController.instance.app);
                    var userNode        = databaseInstance.GetReference("chats");
                    DatabaseReference u = userNode.Child(dialog);
                    u.AddValueEventListener(this);
                }

                send.Click += async delegate
                {
                    if (messageContent.Text != "" && messageContent.Text != " ")
                    {
                        networkInfo = connectivityManager.ActiveNetworkInfo;
                        if (networkInfo != null && networkInfo.IsConnected == true)
                        {
                            loadProgress.Visibility = ViewStates.Visible;

                            List <MessageFlags> flags = new List <MessageFlags>();
                            if (encryption)
                            {
                                flags.Add(MessageFlags.Encoded);
                            }
                            else
                            {
                                flags.Add(MessageFlags.NotEncoded);
                            }

                            List <AccessFlags> acess = new List <AccessFlags>();
                            acess.Add(AccessFlags.NotRead);
                            lastMessage = new Message
                            {
                                //contentP = messageContent.Text,
                                senderP    = AccountsController.mainAccP.emailP,
                                flags      = flags,
                                access     = acess,
                                receiverP  = receiver,
                                timeP      = DateTime.Now.ToString(),
                                dialogName = dialog
                            };
                            if (!encryption)
                            {
                                lastMessage.contentP = messageContent.Text;
                            }
                            else
                            {
                                CryptoProvider c = new CryptoProvider();
                                if (ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP != null &&
                                    ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP != "no key")
                                {
                                    lastMessage.contentP = c.Encrypt(messageContent.Text, ContactsController.instance.FindContact(receiver).contactRsaOpenKeyP);
                                    lastMessage.decodedP = messageContent.Text;
                                    MessagesController.instance.CreateTable();
                                    MessagesController.instance.SaveItem(lastMessage, true);
                                }
                                else
                                {
                                    Utils.MessageBox("Невозможно отправить зашифрованное сообщение! Собеседник не предоставил соотетствующий ключ.", this);
                                    loadProgress.Visibility = ViewStates.Invisible;
                                    return;
                                }
                            }
                            Task <bool> sendTask = MessagingController.instance.SendMessage(lastMessage, dialog, this);
                            bool        sent     = await sendTask;
                            if (sent)
                            {
                                messageContent.Text = "";
                                recyclerList.ScrollToPosition(messageList.Count() - 1);
                            }
                            else
                            {
                                Utils.MessageBox("error", this);
                            }
                            loadProgress.Visibility = ViewStates.Invisible;
                        }
                        else
                        {
                            Utils.MessageBox("Ошибка! Проверьте интернет-соединение.", this);
                        }
                    }
                };
                if (DialogsController.currDialP.lastMessage.access[0] == AccessFlags.Deleted)
                {
                    send.Visibility           = ViewStates.Invisible;
                    messageContent.Visibility = ViewStates.Invisible;
                }
            }
            catch (Exception ex)
            {
                Utils.MessageBox("Произошла сетевая ошибка! Проверьте подключение к интернету и повторите позже.", this);
            }


            // Create your application here
        }
Exemplo n.º 16
0
        }// end:OnPublish()

        // ------------------------ PublishRMContent --------------------------
        /// <summary>
        ///   Writes an encrypted righted managed content file.</summary>
        /// <param name="contentFile">
        ///   The path and filename of the source content file.</param>
        /// <param name="xrmlFile">
        ///   The path and filename of the XrML rights management file.</param>
        /// <param name="encryptedFile">
        ///   The path and filename for writing the RM encrypted content.</param>
        /// <returns>
        ///   true if the encrypted package is written successfully;
        ///   otherwise false.</returns>
        public bool PublishRMContent(
            string contentFile, string xrmlFile, string encryptedFile)
        {
            string xrmlString;

            // Extract individual filenames without the path.
            string contentFilename   = FilenameOnly(contentFile);
            string xrmlFilename      = FilenameOnly(xrmlFile);
            string encryptedFilename = FilenameOnly(encryptedFile);

            try
            {
                //<SnippetRmContPubUnsLic>
                WriteStatus("   Reading '" + xrmlFilename + "' permissions.");
                try
                {
                    StreamReader sr = File.OpenText(xrmlFile);
                    xrmlString = sr.ReadToEnd();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR: '"+xrmlFilename+"' open failed.\n"+
                        "Exception: " + ex.Message, "XrML File Error",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                WriteStatus("   Building UnsignedPublishLicense");
                WriteStatus("       from '" + xrmlFilename + "'.");
                UnsignedPublishLicense unsignedLicense =
                    new UnsignedPublishLicense(xrmlString);
                ContentUser author = unsignedLicense.Owner;
                //</SnippetRmContPubUnsLic>

                WriteStatus("   Building secure environment.");
                try
                {
                    //<SnippetRmContPubSecEnv>
                    string applicationManifest = "<manifest></manifest>";
                    if (File.Exists("rpc.xml"))
                    {
                        StreamReader manifestReader = File.OpenText("rpc.xml");
                        applicationManifest = manifestReader.ReadToEnd();
                    }

                    if (_secureEnv == null)
                    {
                        if (SecureEnvironment.IsUserActivated(new ContentUser(
                                    _currentUserId, AuthenticationType.Windows)))
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest, new ContentUser(
                                    _currentUserId, AuthenticationType.Windows));
                        }
                        else
                        {
                            _secureEnv = SecureEnvironment.Create(
                                applicationManifest,
                                AuthenticationType.Windows,
                                UserActivationMode.Permanent);
                        }
                    }
                    //</SnippetRmContPubSecEnv>
                }
                catch (RightsManagementException ex)
                {
                    MessageBox.Show("ERROR: Failed to build secure environment.\n" +
                        "Exception: " + ex.Message + "\n\n" +
                        ex.FailureCode.ToString() + "\n\n" + ex.StackTrace,
                        "Rights Management Exception",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }

                // If using Windows authentication and the Xrml owner name
                // does not match the current log-in name, show error message
                if ((author.AuthenticationType == AuthenticationType.Windows)
                    && (author.Name != _currentUserId))
                {
                    MessageBox.Show("ERROR: The current user name does not " +
                        "match the UnsignedPublishLicense owner.\n" +
                        "Please check the owner <NAME> element contained in '" +
                        xrmlFilename + "'\n\n" +
                        "Current user log-in ID: " + _currentUserId + "\n" +
                        "XrML UnsignedPublishLicense owner name: " + author.Name,
                        "Incorrect Authentication Name",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                   return false;
                }

                WriteStatus("   Signing the UnsignedPublishLicense\n" +
                            "       to create a signed PublishLicense.");
                UseLicense authorsUseLicense;
                PublishLicense publishLicense =
                    unsignedLicense.Sign(_secureEnv, out authorsUseLicense);

                // Save an XML version of the UseLicense.
                WriteStatus("   Saving UseLicense");
                string useLicenseFilepath = contentFile + ".UseLicense.xml";
                WriteStatus("       '" + FilenameOnly(useLicenseFilepath) + "'.");
                FileStream useStream =
                    new FileStream(useLicenseFilepath, FileMode.Create);
                StreamWriter useWriter =
                    new StreamWriter(useStream, System.Text.Encoding.ASCII);
                useWriter.WriteLine(authorsUseLicense.ToString());
                useWriter.Close();
                useStream.Close();

                // Save an XML version of the signed PublishLicense.
                WriteStatus("   Saving signed PublishLicense");
                string pubLicenseFilepath = contentFile + ".PublishLicense.xml";
                WriteStatus("       '" + FilenameOnly(pubLicenseFilepath) + "'.");
                FileStream pubStream =
                    new FileStream(pubLicenseFilepath, FileMode.Create);
                StreamWriter pubWriter =
                    new StreamWriter(pubStream, System.Text.Encoding.ASCII);
                pubWriter.WriteLine(publishLicense.ToString());
                pubWriter.Close();
                pubStream.Close();

                //<SnippetRmContPubEncrypt>
                WriteStatus("   Binding the author's UseLicense and");
                WriteStatus("       obtaining the CryptoProvider.");
                using (CryptoProvider cryptoProvider =
                            authorsUseLicense.Bind(_secureEnv))
                {
                    WriteStatus("   Writing encrypted content.");
                    using (Stream clearTextStream =
                                File.OpenRead(contentFile) )
                    {
                        using (Stream cryptoTextStream =
                                    File.OpenWrite(encryptedFile))
                        {
                            // Write the length of the source content file
                            // as the first four bytes of the encrypted file.
                            cryptoTextStream.Write(
                                BitConverter.GetBytes(clearTextStream.Length),
                                0, sizeof(Int32));

                            // Allocate clearText buffer.
                            byte[] clearTextBlock =
                                new byte[cryptoProvider.BlockSize];

                            // Encrypt clearText to cryptoText block by block.
                            for(;;)
                            {   // Read clearText block.
                                int readCount = ReliableRead(
                                                    clearTextStream,
                                                    clearTextBlock, 0 ,
                                                    cryptoProvider.BlockSize);
                                // readCount of zero is end of data.
                                if (readCount == 0)  break; // for

                                // Encrypt clearText to cryptoText.
                                byte[] cryptoTextBlock =
                                    cryptoProvider.Encrypt(clearTextBlock);

                                // Write cryptoText block.
                                cryptoTextStream.Write(cryptoTextBlock, 0,
                                                       cryptoTextBlock.Length);
                            }
                            WriteStatus("   Closing '" + encryptedFilename + "'.");
                        }// end:using (Stream cryptoTextStream =
                    }// end:using (Stream clearTextStream =
                }// end:using (CryptoProvider cryptoProvider =
                WriteStatus("   Done - Content encryption complete.");
                //</SnippetRmContPubEncrypt>
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception: " + ex.Message + "\n\n" +
                    ex.GetType().ToString() + "\n\n" + ex.StackTrace,
                    "Runtime Exception",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            WritePrompt("See the RightsManagedContentViewer sample for " +
                "details on how to access rights managed content.");
            return true;
        }// end:PublishRMContent()
Exemplo n.º 17
0
        //Token _token;
        /// <summary>
        /// Generates a token using the username and password set for this provider.
        /// </summary>
        /// <returns>The generated token or null if not applicable</returns>
        /// <remarks>This sets the Token property for the provider. It will be auto appended to
        /// any requests sent through the gateway used by this provider.</remarks>
        public async Task <Token> CheckGenerateToken(CancellationToken ct)
        {
            if (TokenRequest == null)
            {
                return(null);
            }

            if (_token != null && !_token.IsExpired)
            {
                return(_token);
            }

            _token     = null; // reset the Token
            _publicKey = null;

            CheckRefererHeader();

            var  url = TokenRequest.BuildAbsoluteUrl(RootUrl).Split('?').FirstOrDefault();
            Uri  uri;
            bool validUrl = Uri.TryCreate(url, UriKind.Absolute, out uri);

            if (!validUrl)
            {
                throw new HttpRequestException(String.Format("Not a valid url: {0}", url));
            }

            if (CryptoProvider != null && _publicKey == null && CanAccessPublicKeyEndpoint)
            {
                var publicKey = new PublicKey();
                var encryptionInfoEndpoint = publicKey.BuildAbsoluteUrl(RootUrl) + PortalGateway.AsRequestQueryString(Serializer, publicKey);

                String publicKeyResultString = null;
                try
                {
                    _httpClient.CancelPendingRequests();
                    HttpResponseMessage response = await _httpClient.GetAsync(encryptionInfoEndpoint, ct);

                    response.EnsureSuccessStatusCode();
                    publicKeyResultString = await response.Content.ReadAsStringAsync();
                }
                catch (TaskCanceledException cex)
                {
                    System.Diagnostics.Debug.WriteLine(cex.ToString());
                    return(null);
                }
                catch (HttpRequestException ex)
                {
                    CanAccessPublicKeyEndpoint = false;
                    System.Diagnostics.Debug.WriteLine("Public Key access failed for " + encryptionInfoEndpoint + ". " + ex.ToString());
                }

                if (ct.IsCancellationRequested)
                {
                    return(null);
                }

                if (CanAccessPublicKeyEndpoint)
                {
                    _publicKey = Serializer.AsPortalResponse <PublicKeyResponse>(publicKeyResultString);
                    if (_publicKey.Error != null)
                    {
                        throw new InvalidOperationException(_publicKey.Error.ToString());
                    }

                    TokenRequest = CryptoProvider.Encrypt(TokenRequest, _publicKey.Exponent, _publicKey.Modulus);
                }
            }

            if (ct.IsCancellationRequested)
            {
                return(null);
            }
            HttpContent content = new FormUrlEncodedContent(Serializer.AsDictionary(TokenRequest));

            _httpClient.CancelPendingRequests();

            String resultString = String.Empty;

            try
            {
                HttpResponseMessage response = await _httpClient.PostAsync(uri, content, ct);

                response.EnsureSuccessStatusCode();

                resultString = await response.Content.ReadAsStringAsync();
            }
            catch (TaskCanceledException cex)
            {
                System.Diagnostics.Debug.WriteLine(cex.ToString());
                return(null);
            }
            catch (HttpRequestException)
            {
                throw;
            }

            System.Diagnostics.Debug.WriteLine("Generate token result: " + resultString);
            var result = Serializer.AsPortalResponse <Token>(resultString);

            if (result.Error != null)
            {
                throw new InvalidOperationException(result.Error.ToString());
            }

            if (!String.IsNullOrWhiteSpace(TokenRequest.Referer))
            {
                result.Referer = TokenRequest.Referer;
            }

            _token = result;
            return(_token);
        }
Exemplo n.º 18
0
 public static byte[] QuickEncrypt(this byte[] data) => cp.Encrypt(data);
Exemplo n.º 19
0
        public void Do(ConnectClient client)
        {
            Client = client;

            Loger.Log("Server ReceiveBytes1");

            ///установка условно защищенного соединения
            //Строго первый пакет: Передаем серверу КОткр
            var rc     = Client.ReceiveBytes();
            var crypto = new CryptoProvider();

            if (SessionClient.UseCryptoKeys)
            {
                crypto.OpenKey = Encoding.UTF8.GetString(rc);
            }

            //Строго первый ответ: Передаем клиенту КОткр(Сессия)
            SetKey();
            Loger.Log("Server SendMessage1");
            if (SessionClient.UseCryptoKeys)
            {
                Client.SendMessage(crypto.Encrypt(Key));
            }
            else
            {
                Client.SendMessage(Key);
            }

            var context = new ServiceContext();

            Worker = new Service(context);

            ///рабочий цикл
            while (true)
            {
                var rec = Client.ReceiveBytes();

                if (context.Player != null)
                {
                    lock (context.Player)
                    {
                        context.Player.Public.LastOnlineTime = DateTime.UtcNow;
                    }
                }

                //отдельно обрабатываем пинг
                if (rec.Length == 1)
                {
                    if (rec[0] == 0x00)
                    {
                        Client.SendMessage(new byte[1] {
                            0x00
                        });
                    }
                    //отдельно обрабатываем запрос на обновление (ответ 0 - нет ничего, 1 - что-то есть)
                    else if (rec[0] == 0x01)
                    {
                        var exists = ServiceCheck();
                        Client.SendMessage(new byte[1] {
                            exists ? (byte)0x01 : (byte)0x00
                        });
                    }
                    continue;
                }

                var time1 = DateTime.UtcNow;

                var rec2   = CryptoProvider.SymmetricDecrypt(rec, Key);
                var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize

                if (rec.Length > 1024 * 512)
                {
                    Loger.Log($"Server Network fromC {rec.Length} unzip {GZip.LastSizeObj} ");
                }
                var time2 = DateTime.UtcNow;

                ModelContainer sendObj;
                try
                {
                    sendObj = Worker.GetPackage(recObj);
                }
                catch (Exception ext)
                {
                    Loger.Log("Exception GetPackage: " + ext.ToString());
                    sendObj = new ModelContainer()
                    {
                        TypePacket = 0
                    };
                }

                var time3 = DateTime.UtcNow;

                var ob   = GZip.ZipObjByte(sendObj); //Serialize
                var send = CryptoProvider.SymmetricEncrypt(ob, Key);

                if (send.Length > 1024 * 512)
                {
                    Loger.Log($"Server Network toC {send.Length} unzip {GZip.LastSizeObj} ");
                }
                var time4 = DateTime.UtcNow;

                Client.SendMessage(send);

                var time5 = DateTime.UtcNow;

                if ((time5 - time1).TotalMilliseconds > 900)
                {
                    Loger.Log($"Server Network timeDeserialize {(time2 - time1).TotalMilliseconds}" +
                              $" timeWorker {(time3 - time2).TotalMilliseconds}" +
                              $" timeSerialize {(time4 - time3).TotalMilliseconds}" +
                              $" timeSend {(time5 - time4).TotalMilliseconds}");
                }

                if (context.Player != null)
                {
                    lock (context.Player)
                    {
                        context.Player.Public.LastOnlineTime = DateTime.UtcNow;
                        if (context.Player.ExitReason != OCUnion.Transfer.DisconnectReason.AllGood)
                        {
                            //context.Player.ExitReason = OCUnion.Transfer.DisconnectReason.AllGood;
                            Loger.Log("Disconnect  . . ." + context.Player.ExitReason.ToString());
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        public void Do(ConnectClient client)
        {
            Client = client;

            Loger.Log("Server ReceiveBytes1");

            ///установка условно защищенного соединения
            //Строго первый пакет: Передаем серверу КОткр
            var rc     = Client.ReceiveBytes();
            var crypto = new CryptoProvider();

            if (SessionClient.UseCryptoKeys)
            {
                crypto.OpenKey = Encoding.UTF8.GetString(rc);
            }

            //Строго первый ответ: Передаем клиенту КОткр(Сессия)
            SetKey();
            Loger.Log("Server SendMessage1");
            if (SessionClient.UseCryptoKeys)
            {
                Client.SendMessage(crypto.Encrypt(Key));
            }
            else
            {
                Client.SendMessage(Key);
            }

            //if (LogMessage != null) LogMessage("session Connected");

            Worker = new Service();

            ///рабочий цикл
            while (true)
            {
                //Loger.Log("Server Loop1");
                var rec = Client.ReceiveBytes();

                if (Worker.Player != null)
                {
                    Worker.Player.Public.LastOnlineTime = DateTime.UtcNow;
                }

                //отдельно обрабатываем пинг
                if (rec.Length == 1)
                {
                    if (rec[0] == 0x00)
                    {
                        Client.SendMessage(new byte[1] {
                            0x00
                        });
                    }
                    //отдельно обрабатываем запрос на обновление (ответ 0 - нет ничего, 1 - что-то есть)
                    else if (rec[0] == 0x01)
                    {
                        var exists = ServiceCheck();
                        Client.SendMessage(new byte[1] {
                            exists ? (byte)0x01 : (byte)0x00
                        });
                    }
                    continue;
                }

                //Loger.Log("Server Loop2");
                var rec2 = CryptoProvider.SymmetricDecrypt(rec, Key);
                //Loger.Log("Server " + Loger.Bytes(rec2));
                //Loger.Log("Server Loop3");
                var recObj = (ModelContainer)GZip.UnzipObjByte(rec2); //Deserialize
                //Loger.Log("Server Loop4");

                var sendObj = Service(recObj);

                //Loger.Log("Server Loop5");
                var ob = GZip.ZipObjByte(sendObj); //Serialize
                //Loger.Log("Server Loop6");
                var send = CryptoProvider.SymmetricEncrypt(ob, Key);
                //Loger.Log("Server Loop7");
                Client.SendMessage(send);
            }
        }
Exemplo n.º 21
0
        //Token _token;
        /// <summary>
        /// Generates a token using the username and password set for this provider.
        /// </summary>
        /// <returns>The generated token or null if not applicable</returns>
        /// <remarks>This sets the Token property for the provider. It will be auto appended to
        /// any requests sent through the gateway used by this provider.</remarks>
        public async Task <Token> CheckGenerateToken(CancellationToken ct = default(CancellationToken))
        {
            if (TokenRequest == null)
            {
                return(null);
            }

            if (_token != null && !_token.IsExpired)
            {
                return(_token);
            }

            _token     = null; // reset the Token
            _publicKey = null;

            CheckRefererHeader();

            var  url      = TokenRequest.BuildAbsoluteUrl(RootUrl).Split('?').FirstOrDefault();
            bool validUrl = Uri.TryCreate(url, UriKind.Absolute, out Uri uri);

            if (!validUrl)
            {
                throw new HttpRequestException(string.Format("Not a valid url: {0}", url));
            }
            _logger.DebugFormat("Token request {0}", uri.AbsoluteUri);

            if (CryptoProvider != null && _publicKey == null && CanAccessPublicKeyEndpoint)
            {
                var publicKey = new PublicKey();
                var encryptionInfoEndpoint = publicKey.BuildAbsoluteUrl(RootUrl) + PortalGatewayBase.AsRequestQueryString(Serializer, publicKey);
                _logger.DebugFormat("Encrypted token request {0}", encryptionInfoEndpoint);

                string publicKeyResultString = null;
                try
                {
                    if (CancelPendingRequests)
                    {
                        _httpClient.CancelPendingRequests();
                    }
                    HttpResponseMessage response = await _httpClient.GetAsync(encryptionInfoEndpoint, ct).ConfigureAwait(false);

                    response.EnsureSuccessStatusCode();
                    publicKeyResultString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                catch (TaskCanceledException tce)
                {
                    _logger.WarnException("Token request cancelled (exception swallowed)", tce);
                    return(default(Token));
                }
                catch (HttpRequestException hex)
                {
                    _logger.WarnException("Token request exception (exception swallowed)", hex);
                    CanAccessPublicKeyEndpoint = false;
                }

                if (ct.IsCancellationRequested)
                {
                    return(null);
                }

                if (CanAccessPublicKeyEndpoint)
                {
                    _publicKey = Serializer.AsPortalResponse <PublicKeyResponse>(publicKeyResultString);
                    if (_publicKey.Error != null)
                    {
                        throw new InvalidOperationException(_publicKey.Error.ToString());
                    }

                    TokenRequest = CryptoProvider.Encrypt(TokenRequest, _publicKey.Exponent, _publicKey.Modulus);
                }
            }

            if (ct.IsCancellationRequested)
            {
                return(null);
            }

            HttpContent content = new FormUrlEncodedContent(Serializer.AsDictionary(TokenRequest));

            if (CancelPendingRequests)
            {
                _httpClient.CancelPendingRequests();
            }

            string resultString = string.Empty;

            try
            {
                _logger.DebugFormat("HTTP call: {0} {1}", uri, content);
                HttpResponseMessage response = await _httpClient.PostAsync(uri, content, ct).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                resultString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                _logger.DebugFormat("HTTP call response: {0}", resultString);
            }
            catch (TaskCanceledException tce)
            {
                _logger.WarnException("Token request cancelled (exception swallowed)", tce);
                return(default(Token));
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Token request failed", ex);
                return(default(Token));
            }
            // TODO ; add verbose logging
            Token result = null;

            try
            {
                result = Serializer.AsPortalResponse <Token>(resultString);
            }
            catch (Exception ex)
            {
                _logger.WarnException("unable to deserialize token", ex);
                return(default(Token));
            }

            if (result?.Error != null)
            {
                throw new InvalidOperationException(result.Error.ToString());
            }

            if (!string.IsNullOrWhiteSpace(TokenRequest.Referer))
            {
                result.Referer = TokenRequest.Referer;
            }

            _token = result;
            return(_token);
        }