public void DecryptedTextIsEqualToOriginalPlainText()
        {
            var cipherText          = _rijndaelCryptographyProvider.Encrypt(_plainText, _encryptionKey);
            var decryptedCipherText = _rijndaelCryptographyProvider.Decrypt(cipherText, _encryptionKey);

            Assert.That(decryptedCipherText, Is.EqualTo(_plainText));
        }
Esempio n. 2
0
        public bool Authenticate(SecureString password)
        {
            var authenticated = false;
            var attempts      = 0;

            while (!authenticated && attempts < MaxAttempts)
            {
                try
                {
                    _cryptographyProvider.Decrypt(_cipherText, password);
                    authenticated             = true;
                    LastAuthenticatedPassword = password;
                }
                catch (EncryptionException)
                {
                    password = AuthenticationRequestor?.Invoke();
                    if (password == null || password.Length == 0)
                    {
                        break;
                    }
                }
                attempts++;
            }
            return(authenticated);
        }
Esempio n. 3
0
        public string GetClearTextValue()
        {
            var encryptedText = _secureString.ConvertToUnsecureString();
            var clearText     = _cryptographyProvider.Decrypt(encryptedText, MachineKey);

            return(clearText);
        }
Esempio n. 4
0
        public async Task <TResult> Decrypt <T, TResult>(T value)
        {
            var tResultProperties = typeof(TResult).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var resultInstance    = _mapperProvider.Map <T, TResult>(value);

            foreach (var property in GetEncryptableProperties(typeof(T)))
            {
                var encryptCustomAttribute = property.GetCustomAttribute <EncryptAttribute>();

                if (encryptCustomAttribute.EncryptionMethod == EncryptionMethod.Hashing)
                {
                    continue;
                }

                var cryptographicCredentials = _cryptographicCredentialsSwitch
                                               .Case(encryptCustomAttribute.EncryptionSaltKey);

                var resultProperty = tResultProperties
                                     .FirstOrDefault(prop => property.Name == prop.Name);

                var val = (IEnumerable <byte>)property.GetValue(value);

                if (val == null)
                {
                    continue;
                }

                resultProperty.SetValue(resultInstance, await _cryptographyProvider.Decrypt(cryptographicCredentials, val));
            }

            return(resultInstance);
        }
        public void DecryptionFailureThrowsException()
        {
            var cipherText = _cryptographyProvider.Encrypt(_plainText, _encryptionKey);
            ActualValueDelegate <string> decryptMethod = () => _cryptographyProvider.Decrypt(cipherText, "wrongKey".ConvertToSecureString());

            Assert.That(decryptMethod, Throws.TypeOf <EncryptionException>());
        }
Esempio n. 6
0
        public bool Authenticate(SecureString password)
        {
            var authenticated = false;
            var attempts      = 0;

            while (!authenticated && attempts < MaxAttempts)
            {
                try
                {
                    _cryptographyProvider.Decrypt(_cipherText, password);
                    authenticated             = true;
                    LastAuthenticatedPassword = password;
                }
                catch
                {
                    var providedPassword = _authenticationRequestor();
                    if (!providedPassword.Any())
                    {
                        return(false);
                    }

                    password = providedPassword.First();
                    if (password == null || password.Length == 0)
                    {
                        break;
                    }
                }

                attempts++;
            }

            return(authenticated);
        }
        public int DecryptBulletin(int id, Dictionary <string, object> privateKey)
        {
            var info         = _cryptographyProvider.Decrypt(privateKey, _encryptedBulletins[id]);
            var stringResult = Encoding.UTF8.GetString(info);
            var choice       = Convert.ToInt32(stringResult);

            _candidates[choice]++;
            return(choice);
        }
Esempio n. 8
0
        protected virtual void ParsePasswordHash(string passwordHash, out string testNaasPassword, out string prodNaasPassword)
        {
            ExceptionUtils.ThrowIfEmptyString(passwordHash);
            string passwordsHashValue = _cryptographyProvider.Decrypt(passwordHash);

            string[] values = passwordsHashValue.Split(new string[] { PASSWORDS_SEPARATOR }, StringSplitOptions.None);
            ExceptionUtils.ThrowIfFalse(values.Length == 3, "Invalid password hash in database.");
            testNaasPassword = values[1];
            prodNaasPassword = values[2];
        }
Esempio n. 9
0
        private void DecryptAuthHeader(XElement rootElement, ICryptographyProvider cryptographyProvider, SecureString key)
        {
            var authAttribute = rootElement.Attribute("Auth");

            if (authAttribute == null)
            {
                throw new EncryptionException("Could not find Auth header in the XML repository root element.");
            }
            cryptographyProvider.Decrypt(authAttribute.Value, key);
        }
Esempio n. 10
0
        /// <summary>
        /// Decrypts the specified cipher text.
        /// </summary>
        /// <param name="algorithm">The <see cref="EncryptionAlgorithm"/> to use.</param>
        /// <param name="ciphertext">The encrypted data to decrypt.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cancel the operation.</param>
        /// <returns>
        /// The result of the decrypt operation. The returned <see cref="DecryptResult"/> contains the encrypted data
        /// along with information regarding the algorithm and key used to decrypt it.
        /// </returns>
        /// <exception cref="ArgumentException">The specified <paramref name="algorithm"/> does not match the key corresponding to the key identifier.</exception>
        /// <exception cref="CryptographicException">The local cryptographic provider threw an exception.</exception>
        /// <exception cref="InvalidOperationException">The key is invalid for the current operation.</exception>
        /// <exception cref="NotSupportedException">The operation is not supported with the specified key.</exception>
        public virtual DecryptResult Decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, CancellationToken cancellationToken = default)
        {
            DecryptResult result = null;

            if (_provider.SupportsOperation(KeyOperation.Decrypt))
            {
                result = _provider.Decrypt(algorithm, ciphertext, cancellationToken);
            }

            return(result ?? throw LocalCryptographyProvider.CreateOperationNotSupported(nameof(KeyOperation.Decrypt)));
        }
Esempio n. 11
0
 private string DecryptValue(string cipherText)
 {
     try
     {
         return(_cryptographyProvider.Decrypt(cipherText, _decryptionKey));
     }
     catch (EncryptionException)
     {
         // value may not be encrypted
         return(cipherText);
     }
 }
        private ICredentialRecord BuildCredential(XElement element, ICryptographyProvider cryptographyProvider, SecureString decryptionKey)
        {
            var credential = new CredentialRecord
            {
                Title    = $"{element.Attribute("Username")?.Value}\\{element.Attribute("Domain")?.Value}",
                Username = element.Attribute("Username")?.Value,
                Domain   = element.Attribute("Domain")?.Value,
                Password = cryptographyProvider.Decrypt(element.Attribute("Password")?.Value, decryptionKey).ConvertToSecureString()
            };

            return(credential);
        }
Esempio n. 13
0
        /// <summary>
        /// Decrypts the content file using <see cref="CryptographyProvider"/>
        /// </summary>
        /// <param name="Password">The password to decrypt the data with</param>
        public static void Decrypt(string Password)
        {
            try {
                CryptographyProvider.Initialise(Password);                                                     //Intialise the current cryptography provider with the provided password
                File.WriteAllBytes(ContentPath, CryptographyProvider.Decrypt(File.ReadAllBytes(ContentPath))); //Decrypt the data and write the data to the path
                CryptographyProvider.Terminate();                                                              //Close the cryptography provider, allowing it to dispose and clean up anything it uses for next execution
                IsOpen = true;                                                                                 //Marks the archive as open, and ready to read
            } catch (ArgumentNullException e) {
                //Path is null or byte array was empty
                Logging.Write($"Attempted to write an empty array to the file\nStack Trace:\n\t{e.StackTrace}", "ContentDecryption", LogLevel.Crash);
                throw;
            } catch (DirectoryNotFoundException e) {
                Logging.Write("The Content Path was not found. Attempting to generate new files.", "ContentDecryption", LogLevel.Warn);
                LoadEnvironment();
                if (!File.Exists(ContentPath))
                {
                    Logging.Write("Could not generate the Content Path!!", "ContentDecryption", LogLevel.Crash);
                    throw;
                }
            } catch (PathTooLongException e) {
                //Path was too long
                Logging.Write($"Content Path was too long: \"{ContentPath}\"", "ContentDecryption", LogLevel.Crash);
                throw;
            } catch (SecurityException e) {
                //TODO - Does not have required permissions
                Logging.Write("tempmsg - Do not have required permissions", "ContentDecryption", LogLevel.Crash);

                throw;
            } catch (IOException e) {
                Logging.Write($"Could not decrypt file ({e.Message})\nStack Trace:\n\t{e.StackTrace}", "ContentDecryption", LogLevel.Crash);
                throw;
            } catch (UnauthorizedAccessException e) {
                //TODO - HANDLE ERROR
                if (Directory.Exists(ContentPath))
                {
                    Logging.Write($"Content Path was a directory: \"{ContentPath}\"", "ContentDecryption", LogLevel.Crash);
                }
                else
                {
                    FileInfo fi = new FileInfo(ContentPath);

                    if (fi.IsReadOnly)
                    {
                        Logging.Write($"Content Path was read only: \"{ContentPath}\"", "ContentDecryption", LogLevel.Crash);
                    }
                    //File that is readonly
                    //File that is hidden
                    //Do not have permission
                }
                throw;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Decrypts the specified ciphertext.
        /// </summary>
        /// <param name="parameters">A <see cref="DecryptParameters"/> containing the data to decrypt and other parameters for algorithm-dependent decryption.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> to cancel the operation.</param>
        /// <returns>
        /// The result of the decrypt operation. The returned <see cref="DecryptResult"/> contains the encrypted data
        /// along with information regarding the algorithm and key used to decrypt it.
        /// </returns>
        /// <exception cref="ArgumentException">The specified algorithm does not match the key corresponding to the key identifier.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="parameters"/> is null.</exception>
        /// <exception cref="CryptographicException">The local cryptographic provider threw an exception.</exception>
        /// <exception cref="InvalidOperationException">The key is invalid for the current operation.</exception>
        /// <exception cref="NotSupportedException">The operation is not supported with the specified key.</exception>
        public virtual DecryptResult Decrypt(DecryptParameters parameters, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(parameters, nameof(parameters));

            DecryptResult result = null;

            if (_provider.SupportsOperation(KeyOperation.Decrypt))
            {
                result = _provider.Decrypt(parameters, cancellationToken);
            }

            return(result ?? throw LocalCryptographyProvider.CreateOperationNotSupported(nameof(KeyOperation.Decrypt)));
        }
        /// <summary>
        /// Decrypts the specified cipher text.
        /// </summary>
        /// <param name="algorithm">The algorithm to use</param>
        /// <param name="ciphertext">The encrypted data to decrypt</param>
        /// <param name="iv">
        /// The initialization vector. This should only be specified when using symmetric encryption algorithms,
        /// otherwise the caller must omit the parameter or pass null.
        /// </param>
        /// <param name="authenticationData">
        /// The authentication data. This should only be specified when using authenticated symmetric encryption algorithms,
        /// otherwise the caller must omit the parameter or pass null.
        /// </param>
        /// <param name="authenticationTag">The authentication tag. This should only be specified when using authenticated
        /// symmetric encryption algorithms, otherwise the caller must omit the parameter or pass null.
        /// </param>
        /// <param name="cancellationToken">Cancellation token</param>
        /// <returns>
        /// The result of the decrypt operation. The returned <see cref="DecryptResult"/> contains the encrypted data
        /// along with information regarding the algorithm and key used to decrypt it.
        /// </returns>
        public virtual DecryptResult Decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv = default, byte[] authenticationData = default, byte[] authenticationTag = default, CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _pipeline.CreateScope("Azure.Security.KeyVault.Keys.Cryptography.CryptographyClient.Decrypt");
            scope.AddAttribute("key", _keyId);
            scope.Start();

            try
            {
                return(_cryptoProvider.Decrypt(algorithm, ciphertext, iv, authenticationData, authenticationTag, cancellationToken));
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
Esempio n. 16
0
        private void Load()
        {
            Dictionary <string, ConfigItem> configItems = new Dictionary <string, ConfigItem>();

            foreach (ConfigItem item in ConfigDao.GetConfigItems())
            {
                if (item.Id == "NodeDatabaseVersion")
                {
                }
                else
                {
                    item.Value = _cryptographyProvider.Decrypt(item.Value);
                }
                configItems.Add(item.Id.ToUpper(), item);
            }
            lock (_lockObject)
            {
                _configItems = configItems;
            }
        }
Esempio n. 17
0
        public bool ConnectionsFileIsAuthentic(string protectedString, RootNodeInfo rootInfo)
        {
            var connectionsFileIsNotEncrypted = _cryptographyProvider.Decrypt(protectedString, Runtime.EncryptionKey) == "ThisIsNotProtected";

            return(connectionsFileIsNotEncrypted || Authenticate(protectedString, false, rootInfo));
        }
Esempio n. 18
0
 public string Decrypt(string plainText)
 {
     return(plainText == ""
         ? ""
         : _cryptographyProvider.Decrypt(plainText, _rootNodeInfo.PasswordString.ConvertToSecureString()));
 }
Esempio n. 19
0
 public string Decrypt(string plainText)
 {
     return(plainText == "" ? "" : _cryptographyProvider.Decrypt(plainText, Runtime.EncryptionKey));
 }
 private async Task DecryptMessageBody(Message message)
 {
     message.Body = await cryptographyProvider.Decrypt(message.Body).ConfigureAwait(false);
 }
Esempio n. 21
0
 public User GetUser(IEnumerable <User> users, string emailAddress)
 {
     return(users.SingleOrDefault(a =>
                                  _cryptographyProvider.Decrypt(a.EmailAddress, Data.Salt, Data.InitialVector, Encoding.ASCII) == emailAddress));
 }