private byte[] Decrypt(byte[] buffer, Encryption encryption, byte[] iv = null, byte[] salt = null, string password = null)
        {
            if (buffer is null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (encryption == Encryption.Password)
            {
                if (iv is null)
                {
                    throw new ArgumentNullException(nameof(iv));
                }

                if (salt is null)
                {
                    throw new ArgumentNullException(nameof(salt));
                }

                if (string.IsNullOrEmpty(password))
                {
                    PasswordRequiredEventArgs e = new PasswordRequiredEventArgs();
                    PasswordRequired?.Invoke(this, e);

                    if (string.IsNullOrEmpty(e.Password))
                    {
                        throw new ArgumentException("Password cannot be empty or null.", nameof(password));
                    }
                    else
                    {
                        password = e.Password;
                    }
                }
            }

            byte[] plainText = new byte[buffer.Length];
            buffer.CopyTo(plainText, 0);

            if (encryption == Encryption.Password)
            {
                using var random = RNGCryptoServiceProvider.Create();

                using Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, salt, KeyDerivationIterations, HashAlgorithmName.SHA512);

                Aes aes;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    aes = new AesCng();
                }
                else
                {
                    aes = new AesManaged();
                }
                aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                aes.IV  = iv;

                using var decryptor = aes.CreateDecryptor();
                plainText           = decryptor.TransformFinalBlock(plainText, 0, plainText.Length);

                aes.Dispose();
            }
            else if (encryption == Encryption.LocalMachine)
            {
                plainText = ProtectedData.Unprotect(plainText, null, DataProtectionScope.LocalMachine);
            }
            else if (encryption == Encryption.CurrentUser)
            {
                plainText = ProtectedData.Unprotect(plainText, null, DataProtectionScope.CurrentUser);
            }

            return(plainText);
        }
Example #2
0
 private void OnPasswordRequired(PasswordRequiredEventArgs e)
 {
     PasswordRequired?.Invoke(this, e);
 }