예제 #1
0
        private void AddKey(object sender, RoutedEventArgs e)
        {
            AddKeyWindow requestWindow = sender as AddKeyWindow;

            //encrypt input key value before insert in db
            requestWindow.Key.KeyValue = KeyEncryptor.Encrypt(requestWindow.Key.KeyValue);

            fileService.AddKey(requestWindow.Key);
            requestWindow.Close();
        }
예제 #2
0
        private async void OnMessage(object sender, MessageEventArgs e)
        {
            Message message;

            string messageText = KeyEncryptor.Encrypt(Configuration["EncryptionKey"], e.Message.Text.ToString());

            try
            {
                string fileName = GoogleDrive.GetFileNameByKey(messageText);
                GoogleDrive.DownloadByKey(messageText);

                using (FileStream fileStream = System.IO.File.Open(Configuration["DownloadPath"] + "/" + fileName, FileMode.Open))
                {
                    message = await BotClient.SendDocumentAsync(
                        chatId : e.Message.Chat,
                        document : new InputOnlineFile(fileStream, fileName)
                        );
                }

                _logger.LogInformation(
                    $"{message.From.FirstName} sent file {fileName} " +
                    $"to user {e.Message.From.Username} at {message.Date}. "
                    );
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(
                    $"File was not sent to user {e.Message.From.Username} with text '{e.Message.Text}' " +
                    $"because of exception: {ex.Message}."
                    );

                await BotClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : ex.Message
                    );
            }
            catch (Exception ex)
            {
                _logger.LogError($"{DateTime.Now} : {ex.Message}");
            }
        }
예제 #3
0
        /// <summary>
        /// Encrypt the given password with strong encryption
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string[] EncryptPassword(string password)
        {
            string EncryptedPassword = "";
            string InitVector        = "";

            string[] ReturnArray = new string[2];

            try
            {
                // Instantiate the Encryptor
                KeyEncryptor Enc      = new KeyEncryptor(this.Algorithm);
                byte[]       Password = Encoding.ASCII.GetBytes(password);

                // Get the password key
                string StoredKey = this.GetPasswordKey();
                byte[] Key       = Convert.FromBase64String(StoredKey);

                // Set the Initialization vector property to null so a brand new one will get generated
                Enc.IV = null;

                // Encrypt the Password and Convert the resulting array of bytes to a Base64 string
                byte[] CipherText = Enc.Encrypt(Password, Key);

                // Retrieve the intialization vector needed for decryption.
                byte[] IV = Enc.IV;

                // Update table with new values
                EncryptedPassword = Convert.ToBase64String(CipherText);
                InitVector        = Convert.ToBase64String(IV);
            }
            catch (Exception ex)
            {
                throw new Exception("Exception Encrypting Password. " + ex.Message);
            }

            ReturnArray[0] = EncryptedPassword;
            ReturnArray[1] = InitVector;
            return(ReturnArray);
        }
예제 #4
0
        IKey IInternalXmlKeyManager.CreateNewKey(Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate)
        {
            // <key id="{guid}" version="1">
            //   <creationDate>...</creationDate>
            //   <activationDate>...</activationDate>
            //   <expirationDate>...</expirationDate>
            //   <descriptor deserializerType="{typeName}">
            //     ...
            //   </descriptor>
            // </key>

            _logger.CreatingKey(keyId, creationDate, activationDate, expirationDate);

            var newDescriptor = _authenticatedEncryptorConfiguration.CreateNewDescriptor()
                                ?? CryptoUtil.Fail <IAuthenticatedEncryptorDescriptor>("CreateNewDescriptor returned null.");
            var descriptorXmlInfo = newDescriptor.ExportToXml();

            _logger.DescriptorDeserializerTypeForKeyIs(keyId, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName);

            // build the <key> element
            var keyElement = new XElement(KeyElementName,
                                          new XAttribute(IdAttributeName, keyId),
                                          new XAttribute(VersionAttributeName, 1),
                                          new XElement(CreationDateElementName, creationDate),
                                          new XElement(ActivationDateElementName, activationDate),
                                          new XElement(ExpirationDateElementName, expirationDate),
                                          new XElement(DescriptorElementName,
                                                       new XAttribute(DeserializerTypeAttributeName, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName),
                                                       descriptorXmlInfo.SerializedDescriptorElement));

            // If key escrow policy is in effect, write the *unencrypted* key now.
            if (_keyEscrowSink != null)
            {
                _logger.KeyEscrowSinkFoundWritingKeyToEscrow(keyId);
            }
            else
            {
                _logger.NoKeyEscrowSinkFoundNotWritingKeyToEscrow(keyId);
            }
            _keyEscrowSink?.Store(keyId, keyElement);

            // If an XML encryptor has been configured, protect secret key material now.
            if (KeyEncryptor == null)
            {
                _logger.NoXMLEncryptorConfiguredKeyMayBePersistedToStorageInUnencryptedForm(keyId);
            }
            var possiblyEncryptedKeyElement = KeyEncryptor?.EncryptIfNecessary(keyElement) ?? keyElement;

            // Persist it to the underlying repository and trigger the cancellation token.
            var friendlyName = string.Format(CultureInfo.InvariantCulture, "key-{0:D}", keyId);

            KeyRepository.StoreElement(possiblyEncryptedKeyElement, friendlyName);
            TriggerAndResetCacheExpirationToken();

            // And we're done!
            return(new Key(
                       keyId: keyId,
                       creationDate: creationDate,
                       activationDate: activationDate,
                       expirationDate: expirationDate,
                       descriptor: newDescriptor,
                       encryptorFactories: _encryptorFactories));
        }
        IKey IInternalXmlKeyManager.CreateNewKey(Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate)
        {
            // <key id="{guid}" version="1">
            //   <creationDate>...</creationDate>
            //   <activationDate>...</activationDate>
            //   <expirationDate>...</expirationDate>
            //   <descriptor deserializerType="{typeName}">
            //     ...
            //   </descriptor>
            // </key>

            if (_logger.IsInformationLevelEnabled())
            {
                _logger.LogInformationF($"Creating key {keyId:B} with creation date {creationDate:u}, activation date {activationDate:u}, and expiration date {expirationDate:u}.");
            }

            var newDescriptor = _authenticatedEncryptorConfiguration.CreateNewDescriptor()
                                ?? CryptoUtil.Fail <IAuthenticatedEncryptorDescriptor>("CreateNewDescriptor returned null.");
            var descriptorXmlInfo = newDescriptor.ExportToXml();

            if (_logger.IsVerboseLevelEnabled())
            {
                _logger.LogVerboseF($"Descriptor deserializer type for key {keyId:B} is '{descriptorXmlInfo.DeserializerType.AssemblyQualifiedName}'.");
            }

            // build the <key> element
            var keyElement = new XElement(KeyElementName,
                                          new XAttribute(IdAttributeName, keyId),
                                          new XAttribute(VersionAttributeName, 1),
                                          new XElement(CreationDateElementName, creationDate),
                                          new XElement(ActivationDateElementName, activationDate),
                                          new XElement(ExpirationDateElementName, expirationDate),
                                          new XElement(DescriptorElementName,
                                                       new XAttribute(DeserializerTypeAttributeName, descriptorXmlInfo.DeserializerType.AssemblyQualifiedName),
                                                       descriptorXmlInfo.SerializedDescriptorElement));

            // If key escrow policy is in effect, write the *unencrypted* key now.
            if (_logger.IsVerboseLevelEnabled())
            {
                if (_keyEscrowSink != null)
                {
                    _logger.LogVerboseF($"Key escrow sink found. Writing key {keyId:B} to escrow.");
                }
                else
                {
                    _logger.LogVerboseF($"No key escrow sink found. Not writing key {keyId:B} to escrow.");
                }
            }
            _keyEscrowSink?.Store(keyId, keyElement);

            // If an XML encryptor has been configured, protect secret key material now.
            if (KeyEncryptor == null && _logger.IsWarningLevelEnabled())
            {
                _logger.LogWarningF($"No XML encryptor configured. Key {keyId:B} may be persisted to storage in unencrypted form.");
            }
            var possiblyEncryptedKeyElement = KeyEncryptor?.EncryptIfNecessary(keyElement) ?? keyElement;

            // Persist it to the underlying repository and trigger the cancellation token.
            string friendlyName = Invariant($"key-{keyId:D}");

            KeyRepository.StoreElement(possiblyEncryptedKeyElement, friendlyName);
            TriggerAndResetCacheExpirationToken();

            // And we're done!
            return(new Key(
                       keyId: keyId,
                       creationDate: creationDate,
                       activationDate: activationDate,
                       expirationDate: expirationDate,
                       descriptor: newDescriptor));
        }