public DifferencesExpansionConfiguraitonDialogBox(DifferencesExpansionConfiguration standardDEConfig,
                                                          DifferenceExpansionBruteForceConfiguration bruteForceDEConfig,
                                                          AlgorithmConfiguration currentConfiguration)
        {
            InitializeComponent();

            if (standardDEConfig != null)
            {
                this.threshold   = standardDEConfig.Threeshold;
                tbThreshold.Text = threshold.ToString();
                cbEmbeddingDirection.SelectedIndex = (int)standardDEConfig.EmbeddingDirection;
                cbR.IsChecked = standardDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.R);
                cbG.IsChecked = standardDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.G);
                cbB.IsChecked = standardDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.B);
                ComboBoxItem standardComboBoxItem = new ComboBoxItem();
                standardComboBoxItem.Content    = "Standard";
                standardComboBoxItem.IsSelected = currentConfiguration is DifferencesExpansionConfiguration;
                cbConfigurationType.Items.Add(standardComboBoxItem);
            }

            if (bruteForceDEConfig != null)
            {
                cbHorizontal_BF.IsChecked = bruteForceDEConfig.EmbeddingDirections.Contains(Direction.Horizontal);
                cbVertical_BF.IsChecked   = bruteForceDEConfig.EmbeddingDirections.Contains(Direction.Vertical);
                cbR_BF.IsChecked          = bruteForceDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.R);
                cbG_BF.IsChecked          = bruteForceDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.G);
                cbB_BF.IsChecked          = bruteForceDEConfig.EmbeddingChanels.Contains(EmbeddingChanel.B);
                ComboBoxItem bruteForceItem = new ComboBoxItem();
                bruteForceItem.Content    = "Brute force";
                bruteForceItem.IsSelected = currentConfiguration is DifferenceExpansionBruteForceConfiguration;
                cbConfigurationType.Items.Add(bruteForceItem);
            }
        }
        public Tuple <Bitmap, string> Decode(Bitmap encodedImage, AlgorithmConfiguration configuration)
        {
            // Algorithm instances
            DifferencesExpansionAlgorithm de = new DifferencesExpansionAlgorithm();
            HistogramShiftingAlgorithm    hs = new HistogramShiftingAlgorithm();
            // Algorithm configs
            DifferenceExpansionBruteForceConfiguration deConfig = new DifferenceExpansionBruteForceConfiguration(
                new HashSet <EmbeddingChanel>()
            {
                EmbeddingChanel.R, EmbeddingChanel.G, EmbeddingChanel.B
            }, new HashSet <Direction>()
            {
                Direction.Horizontal, Direction.Vertical
            });
            HistogramShiftingConfiguration hsConfig = new HistogramShiftingConfiguration(true,
                                                                                         new HashSet <EmbeddingChanel>()
            {
                EmbeddingChanel.R, EmbeddingChanel.G, EmbeddingChanel.B
            });
            // Decoding
            var deResult = de.BruteforceDecode(encodedImage, deConfig);

            if (deResult != null)
            {
                return(deResult);
            }
            var hsResult = hs.Decode(encodedImage, hsConfig);

            if (hsResult != null)
            {
                return(hsResult);
            }
            return(null);
        }
예제 #3
0
        /// <summary>
        /// Creates an <see cref="XmlKeyManager"/>.
        /// </summary>
        /// <param name="keyManagementOptions">The <see cref="IOptions{KeyManagementOptions}"/> instance that provides the configuration.</param>
        /// <param name="activator">The <see cref="IActivator"/>.</param>
        /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
        public XmlKeyManager(IOptions <KeyManagementOptions> keyManagementOptions, IActivator activator, ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            _logger        = _loggerFactory.CreateLogger <XmlKeyManager>();

            KeyRepository = keyManagementOptions.Value.XmlRepository;
            KeyEncryptor  = keyManagementOptions.Value.XmlEncryptor;
            if (KeyRepository == null)
            {
                if (KeyEncryptor != null)
                {
                    throw new InvalidOperationException(
                              Resources.FormatXmlKeyManager_IXmlRepositoryNotFound(nameof(IXmlRepository), nameof(IXmlEncryptor)));
                }
                else
                {
                    var keyRepositoryEncryptorPair = GetFallbackKeyRepositoryEncryptorPair();
                    KeyRepository = keyRepositoryEncryptorPair.Key;
                    KeyEncryptor  = keyRepositoryEncryptorPair.Value;
                }
            }

            _authenticatedEncryptorConfiguration = keyManagementOptions.Value.AuthenticatedEncryptorConfiguration;

            var escrowSinks = keyManagementOptions.Value.KeyEscrowSinks;

            _keyEscrowSink = escrowSinks.Count > 0 ? new AggregateKeyEscrowSink(escrowSinks) : null;
            _activator     = activator;
            TriggerAndResetCacheExpirationToken(suppressLogging: true);
            _internalKeyManager = _internalKeyManager ?? this;
            _encryptorFactories = keyManagementOptions.Value.AuthenticatedEncryptorFactories;
        }
예제 #4
0
        internal DataProvider GetDataProvider <T>(AlgorithmConfiguration config)
            where T : DataProviderTestImplementation
        {
            var implementation = (T)Activator.CreateInstance(typeof(T), LoggerFactory, new TestTimerProvider(LoggerFactory));
            var data           = new DataProvider(LoggerFactory, implementation, config);

            return(data);
        }
예제 #5
0
 public DepthFirstAlgorithm(AlgorithmConfiguration cfg)
 {
     _graph            = cfg.Graph;
     _breakCriteria    = cfg.BreakCriteria;
     _addRouteCriteria = cfg.AddRouteCriteria;
     _trip             = cfg.Trip;
     _shouldBreak      = cfg.ShouldBreak;
     _possibleTrips    = new List <ITrip>();
 }
 private void SetStartup()
 {
     RbAlgorithm1.IsChecked       = true;
     CbActivityType.SelectedIndex = 0;
     addSignatureController       = new AddSignatureController();
     ImportImage(projectDirectory + "/Model/_img/lena.png");
     activeEncodingDEConfig = standardEncodingDEConfig;
     activeDecodingDEConfig = standardDecodingDEConfig;
 }
예제 #7
0
 public RegistryPolicy(
     AlgorithmConfiguration configuration,
     IEnumerable <IKeyEscrowSink> keyEscrowSinks,
     int?defaultKeyLifetime)
 {
     EncryptorConfiguration = configuration;
     KeyEscrowSinks         = keyEscrowSinks;
     DefaultKeyLifetime     = defaultKeyLifetime;
 }
예제 #8
0
        /// <summary>
        /// Builds container by evaluation the Trading command line argument.
        /// </summary>
        /// <param name="algorithmConfiguration">The configuration of the algorithm.</param>
        /// <typeparam name="T">The type of the algorithm.</typeparam>
        /// <returns>Binance container with providers.</returns>
        public ExchangeProvidersContainer BuildContainer <T>(AlgorithmConfiguration algorithmConfiguration)
            where T : IBaseAlgorithm
        {
            if (!Reflections.AlgorithmMatchesConfiguration(typeof(T), algorithmConfiguration.GetType()))
            {
                throw new InvalidOperationException(
                          $"Cannot build container for {typeof(T).Name} using a {algorithmConfiguration.GetType().Name} object");
            }

            return(Program.CommandLineArgs.Trading
                ? BuildBinanceContainer <T>(algorithmConfiguration)
                : BuildBacktestingContainer <T>(algorithmConfiguration));
        }
예제 #9
0
        internal DataProvider GetDataProviderWithTimer <TD, TT>(AlgorithmConfiguration config)
            where TD : DataProviderTestImplementation
            where TT : TimerProviderTestImplementation
        {
            var implementation = (TD)Activator.CreateInstance(typeof(TD), LoggerFactory, new TestTimerProvider(LoggerFactory));
            var timerProperty  = implementation.GetType()
                                 .GetProperty("TimerProvider", BindingFlags.NonPublic | BindingFlags.Instance)
                                 ?? throw new Exception(
                                           $"Expected property 'TimerProvider' on {implementation.GetType().Name}");
            var timerProvider = Activator.CreateInstance(typeof(TT), LoggerFactory);

            timerProperty.SetValue(implementation, timerProvider);
            return(new DataProvider(LoggerFactory, implementation, config));
        }
        private void BtnConfigSVD_Click(object sender, RoutedEventArgs e)
        {
            DwtSvdConfiguration config = currentDwtSvdConfiguration as DwtSvdConfiguration;
            var dialogBox = new DwtSvdConfigDialogBox(config.EmbeddingChanels, config.QuarterSymbol)
            {
                Owner = this,
            };

            dialogBox.ShowDialog();
            if (dialogBox.DialogResult == true)
            {
                HashSet <EmbeddingChanel> embeddingChanel = new HashSet <EmbeddingChanel>();
                if (dialogBox.cbR.IsChecked == true)
                {
                    embeddingChanel.Add(EmbeddingChanel.R);
                }
                if (dialogBox.cbG.IsChecked == true)
                {
                    embeddingChanel.Add(EmbeddingChanel.G);
                }
                if (dialogBox.cbB.IsChecked == true)
                {
                    embeddingChanel.Add(EmbeddingChanel.B);
                }
                HashSet <DwtDctSvdAlgorithm.QuarterSymbol> quarter = new HashSet <DwtDctSvdAlgorithm.QuarterSymbol>();
                if (dialogBox.qHH.IsChecked == true)
                {
                    quarter.Add(DwtDctSvdAlgorithm.QuarterSymbol.HH);
                }
                if (dialogBox.qHL.IsChecked == true)
                {
                    quarter.Add(DwtDctSvdAlgorithm.QuarterSymbol.HL);
                }
                if (dialogBox.qLH.IsChecked == true)
                {
                    quarter.Add(DwtDctSvdAlgorithm.QuarterSymbol.LH);
                }
                if (dialogBox.qLL.IsChecked == true)
                {
                    quarter.Add(DwtDctSvdAlgorithm.QuarterSymbol.LL);
                }
                currentDwtSvdConfiguration = new DwtSvdConfiguration(embeddingChanel, quarter);

                if (dialogBox.isFileLoaded)
                {
                    ImportOriginValues(dialogBox.fileName);
                }
            }
        }
예제 #11
0
        /// <inheritdoc />
        public ResponseObject Start(AlgorithmConfiguration configuration, ExchangeProvidersContainer container)
        {
            Guard.Argument(configuration).Require(
                x => x is T,
                x => $"{x} cannot not be converted to {typeof(T)}, please make sure to use the correct AlgorithmConfiguration");

            StateManager = new StateManager <T>(configuration as T, container, Initial);

            // Add state switch tracking
            DatabaseEventListenerService.AddStateSource(StateManager);

            container.TimerProvider.RunPeriodicTimer();

            return(new ResponseObject(ResponseCode.Success));
        }
        public Tuple <Bitmap, string> Decode(Bitmap encodedImage, AlgorithmConfiguration configuration)
        {
            Bitmap image = new Bitmap(encodedImage);

            // Depending on configuration standard or brute force decoding is performed
            if (configuration is DifferencesExpansionConfiguration)
            {
                return(Decode(image, (DifferencesExpansionConfiguration)configuration));
            }
            if (configuration is DifferenceExpansionBruteForceConfiguration)
            {
                return(BruteforceDecode(image, (DifferenceExpansionBruteForceConfiguration)configuration));
            }
            return(null);
        }
예제 #13
0
        /// <summary>
        /// Builds a container for Backtesting.
        /// </summary>
        /// <param name="config">The algorithm configuration to use.</param>
        /// <typeparam name="T">The algorithm type.</typeparam>
        /// <returns>ExchangeProviderContainer.</returns>
        public ExchangeProvidersContainer BuildBacktestingContainer <T>(AlgorithmConfiguration config)
            where T : IBaseAlgorithm
        {
            var backtestTimer         = new BacktestTimerProvider(_loggerFactory, Configuration.Instance.BacktestSettings);
            var dataImplementation    = new BacktestDataProvider(_loggerFactory, _databaseContext, backtestTimer);
            var tradingImplementation = new BacktestTradingProvider(_loggerFactory, backtestTimer, dataImplementation);

            var dataProvider    = new DataProvider(_loggerFactory, dataImplementation, config);
            var tradingProvider = new TradingProvider(_loggerFactory, tradingImplementation, dataProvider, _allocationManager);

            // Doubly linked inheritance for backtesting edge case
            dataImplementation.ParentImplementation    = dataProvider;
            tradingImplementation.ParentImplementation = tradingProvider;

            return(new ExchangeProvidersContainer(_loggerFactory, dataProvider, backtestTimer, tradingProvider, typeof(T)));
        }
        public Bitmap Encode(Bitmap inputImage, string payload, AlgorithmConfiguration configuration)
        {
            DifferencesExpansionConfiguration config = (DifferencesExpansionConfiguration)configuration;
            Bitmap image = new Bitmap(inputImage);
            // For multiple embedding channels payload to encode is divided into chunks - one for each RGB channel
            List <string> payloadChunks = GetPayloadChunks(payload, config.EmbeddingChanels);
            int           chunkNumber   = 0;

            foreach (EmbeddingChanel embeddingChanel in Enum.GetValues(typeof(EmbeddingChanel)))
            {
                if (config.EmbeddingChanels.Contains(embeddingChanel))
                {
                    // Encoding of payload chunk performed for given channel of RGB
                    EncodePayloadIntoImage(image, payloadChunks[chunkNumber++], config.EmbeddingDirection, config.Threeshold, embeddingChanel);
                }
            }
            return(image);
        }
예제 #15
0
        /// <summary>
        /// Starts the algorithm using a custom configuration object.
        /// </summary>
        /// <param name="algorithm">Algorithm to start.</param>
        /// <param name="configuration">Configuration object.</param>
        /// <returns>If the algorithm was started successfully.</returns>
        public ResponseObject StartAlgorithm(Type algorithm, AlgorithmConfiguration configuration)
        {
            if (!Reflections.AlgorithmMatchesConfiguration(algorithm, configuration.GetType()))
            {
                return(new ResponseObject(ResponseCode.Error, $"Provided settings object is of type {configuration.GetType()} and does not match {algorithm}"));
            }

            // Call StartAlgorithm<T> to start the algorithm
            return(GetType()
                   .GetMethod(
                       nameof(StartAlgorithm),
                       BindingFlags.Instance | BindingFlags.NonPublic,
                       Type.DefaultBinder,
                       new[] { typeof(AlgorithmConfiguration) },
                       null)
                   .MakeGenericMethod(algorithm)
                   .Invoke(this, new object[] { configuration }) as ResponseObject);
        }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StartBacktestCommand"/> class.
        /// </summary>
        /// <param name="inputs">inputs.</param>
        public StartBacktestCommand(string[] inputs)
            : base(inputs)
        {
            Parser parser = new Parser(x => x.HelpWriter = null);

            parser.ParseArguments <StartBacktestCommandArguments>(inputs)
            .WithNotParsed(_ => throw new InvalidCommandException("invalid arguments, use help to get more info"))
            .WithParsed(x => _args = x);

            // Check if the input type is a valid algorithm
            _algo = Reflections.GetAllImplementations(typeof(IBaseAlgorithm))
                    .FirstOrDefault(x => x.Name == _args.AlgorithmName)
                    ?? throw new InvalidCommandException($"{_args.AlgorithmName} is not a known algorithm");

            // Retrieve the settings type
            var settingsType = Reflections.GetAllSubtypes(typeof(AlgorithmConfiguration))
                               .FirstOrDefault(s => Reflections.AlgorithmMatchesConfiguration(_algo, s))
                               ?? throw new InvalidCommandException(
                                         $"{_args.AlgorithmName} does not have a configuration object and cannot be started.");

            // Optionally load with custom path.
            if (!_args.Inline)
            {
                _args.ConfigurationPath = _args.ConfigurationPath ?? _args.AlgorithmName + ".yaml";
                try
                {
                    _configuration = ConfigurationLoader.LoadConfiguration(settingsType, _args.ConfigurationPath);
                }
                catch (Exception e)
                {
                    throw new InvalidCommandException(e.Message);
                }
            }
            else
            {
                _configuration = BacktestDaemonService.GetConfigurationFromUser(settingsType);
            }

            DatabaseUtilities.Instance.ValidateCandleWidth(_configuration.TradingPairs, Configuration.Configuration.Instance.CandleWidth);
            ConfigureTimestampEdges(BacktestDaemonService.Instance.State, _args);
            Program.CommandLineArgs.BacktestOutputPath = _args.OutputPath;
        }
예제 #17
0
        /// <summary>
        /// Builds a container for Binance.
        /// </summary>
        /// <param name="config">The algorithm configuration to use.</param>
        /// <typeparam name="T">The algorithm type.</typeparam>
        /// <returns>ExchangeProviderContainer.</returns>
        public ExchangeProvidersContainer BuildBinanceContainer <T>(AlgorithmConfiguration config)
            where T : IBaseAlgorithm
        {
            // Makes sure that the communication is enabled
            _binanceCommunications.EnableStreams();
            var timerProvider         = new BinanceTimerProvider(_loggerFactory, _binanceCommunications.CandleDispenser);
            var dataImplementation    = new BinanceDataProvider(_loggerFactory, _binanceCommunications, timerProvider);
            var tradingImplementation = new BinanceTradingProvider(_loggerFactory, _binanceCommunications, timerProvider);

            var dataProvider    = new DataProvider(_loggerFactory, dataImplementation, config);
            var tradingProvider = new TradingProvider(_loggerFactory, tradingImplementation, dataProvider, _allocationManager);

            // Doubly linked data provider to check candles
            timerProvider.DataProvider = dataProvider;

            // Inject database event listener
            DatabaseEventListenerService.AddOrderSource(tradingProvider);

            return(new ExchangeProvidersContainer(_loggerFactory, dataProvider, timerProvider, tradingProvider, typeof(T)));
        }
예제 #18
0
        private RegistryPolicy ResolvePolicyCore(RegistryKey policyRegKey)
        {
            if (policyRegKey == null)
            {
                return(null);
            }

            // Read the encryption options type: CNG-CBC, CNG-GCM, Managed
            AlgorithmConfiguration configuration = null;

            var encryptionType = (string)policyRegKey.GetValue("EncryptionType");

            if (String.Equals(encryptionType, "CNG-CBC", StringComparison.OrdinalIgnoreCase))
            {
                configuration = new CngCbcAuthenticatedEncryptorConfiguration();
            }
            else if (String.Equals(encryptionType, "CNG-GCM", StringComparison.OrdinalIgnoreCase))
            {
                configuration = new CngGcmAuthenticatedEncryptorConfiguration();
            }
            else if (String.Equals(encryptionType, "Managed", StringComparison.OrdinalIgnoreCase))
            {
                configuration = new ManagedAuthenticatedEncryptorConfiguration();
            }
            else if (!String.IsNullOrEmpty(encryptionType))
            {
                throw CryptoUtil.Fail("Unrecognized EncryptionType: " + encryptionType);
            }
            if (configuration != null)
            {
                PopulateOptions(configuration, policyRegKey);
            }

            // Read ancillary data

            var defaultKeyLifetime = (int?)policyRegKey.GetValue("DefaultKeyLifetime");

            var keyEscrowSinks = ReadKeyEscrowSinks(policyRegKey).Select(item => _activator.CreateInstance <IKeyEscrowSink>(item));

            return(new RegistryPolicy(configuration, keyEscrowSinks, defaultKeyLifetime));
        }
 private void BtnConfigDE_Click(object sender, RoutedEventArgs e)
 {
     if (isWatermarkingModeSelected())
     {
         DifferencesExpansionConfiguration config = (DifferencesExpansionConfiguration)standardEncodingDEConfig;
         var dialogBox = new ConfigurationDialogBox.DifferencesExpansionConfiguraitonDialogBox(config, null, activeEncodingDEConfig)
         {
             Owner = this,
         };
         dialogBox.ShowDialog();
         AlgorithmConfiguration newConfig = GetConfigurationBasedOnDialogBoxResult(dialogBox);
         if (newConfig != null)
         {
             standardEncodingDEConfig = newConfig;
             activeEncodingDEConfig   = standardEncodingDEConfig;
         }
     }
     if (isAnalyzingModeSelected())
     {
         DifferencesExpansionConfiguration          deConfig           = (DifferencesExpansionConfiguration)standardDecodingDEConfig;
         DifferenceExpansionBruteForceConfiguration deBruteForceConfig = (DifferenceExpansionBruteForceConfiguration)bruteForceDecodingDEConfig;
         var dialogBox = new ConfigurationDialogBox.DifferencesExpansionConfiguraitonDialogBox(deConfig, deBruteForceConfig, activeDecodingDEConfig)
         {
             Owner = this,
         };
         dialogBox.ShowDialog();
         AlgorithmConfiguration newConfig = GetConfigurationBasedOnDialogBoxResult(dialogBox);
         if (dialogBox.cbConfigurationType.Text == "Standard" && newConfig != null)
         {
             standardDecodingDEConfig = newConfig;
             activeDecodingDEConfig   = standardDecodingDEConfig;
         }
         else if (dialogBox.cbConfigurationType.Text == "Brute force" && newConfig != null)
         {
             bruteForceDecodingDEConfig = newConfig;
             activeDecodingDEConfig     = bruteForceDecodingDEConfig;
         }
     }
 }
예제 #20
0
        /// <summary>
        /// Starts the algorithm using a custom configuration object.
        /// </summary>
        /// <param name="configuration">Configuration object.</param>
        /// <typeparam name="T">The type of algorithm to start.</typeparam>
        /// <returns>If the algorithm was started successfully.</returns>
        private ResponseObject StartAlgorithm <T>(AlgorithmConfiguration configuration)
            where T : IBaseAlgorithm
        {
            // Figure out which container to get
            var algorithm = (IBaseAlgorithm)Activator.CreateInstance(typeof(T));

            // Build container
            var container = _exchangeFactoryService.BuildContainer <T>(configuration);

            // Initialise algorithm with container
            var startResponse = algorithm.Start(configuration, container);

            if (!startResponse.Success)
            {
                return(startResponse);
            }

            // Run backtest asynchronously by awaiting the timer.
            return(Program.CommandLineArgs.Backtesting
                ? WaitTillBacktestFinished(container.TimerProvider as BacktestTimerProvider)
                : new ResponseObject(ResponseCode.Success));
        }
        public Tuple <Bitmap, string> Decode(Bitmap encodedImage, AlgorithmConfiguration configuration)
        {
            var payload = "";

            decimal[][,] inputDoubles = _imageArrayConverter.BitmapToPrecisionMatrices(encodedImage.DeepClone());
            _dwtHandler.OriginalImage = inputDoubles.DeepClone();
            _dwtHandler.ApplyHaarTransform(true, true, _iterations);

            var imageArrayAfterDwt = _dwtHandler.TransformedImage.DeepClone();

            decimal[][,] quarter = ExtractQuarter(imageArrayAfterDwt, _iterations, _quarter);
            var quarterDouble = _matrixService.DecimalToDouble(quarter);

            var originalImage2dAndPayload =
                _svdHandler.ExtractPayloadSVD(quarterDouble, _channel);

            var payload2d = originalImage2dAndPayload.Item2;

            var originalImage = originalImage2dAndPayload.Item1;

            var smallMatrixPrecisionOrigin = _matrixService.DoubleToDecimal(originalImage);

            var bigImageOrigin = MergeQuarter(smallMatrixPrecisionOrigin, imageArrayAfterDwt, _iterations, _quarter);

            _dwtHandler.OriginalImage    = null;
            _dwtHandler.TransformedImage = null;
            _dwtHandler.TransformedImage = bigImageOrigin;
            _dwtHandler.ApplyHaarTransform(false, true, _iterations);
            var newMatrix = _dwtHandler.OriginalImage;
            //TODO make original matrix
            var originImage = _imageArrayConverter.MatricesPrecisionToBitmap(newMatrix);

            payload = _stringArrayConverter.ArrayPayloadToString(_stringArrayConverter.ArrayDiagonalToArray(payload2d));

            Debug.WriteLine("");
            Debug.WriteLine($"payload : {payload}");
            Debug.WriteLine("");
            return(new Tuple <Bitmap, string>(originImage, payload));
        }
예제 #22
0
        internal XmlKeyManager(
            IOptions <KeyManagementOptions> keyManagementOptions,
            IActivator activator,
            ILoggerFactory loggerFactory,
            IDefaultKeyStorageDirectories keyStorageDirectories)
        {
            _loggerFactory         = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
            _logger                = _loggerFactory.CreateLogger <XmlKeyManager>();
            _keyStorageDirectories = keyStorageDirectories ?? throw new ArgumentNullException(nameof(keyStorageDirectories));

            KeyRepository = keyManagementOptions.Value.XmlRepository;
            KeyEncryptor  = keyManagementOptions.Value.XmlEncryptor;
            if (KeyRepository == null)
            {
                if (KeyEncryptor != null)
                {
                    throw new InvalidOperationException($"The '{nameof(IXmlRepository)}' instance could not be found. When an '{nameof(IXmlEncryptor)}' instance is set, a corresponding '{nameof(IXmlRepository)}' instance must also be set.");
                }
                else
                {
                    var keyRepositoryEncryptorPair = GetFallbackKeyRepositoryEncryptorPair();
                    KeyRepository = keyRepositoryEncryptorPair.Key;
                    KeyEncryptor  = keyRepositoryEncryptorPair.Value;
                }
            }

            _authenticatedEncryptorConfiguration = keyManagementOptions.Value.AuthenticatedEncryptorConfiguration;

            var escrowSinks = keyManagementOptions.Value.KeyEscrowSinks;

            _keyEscrowSink = escrowSinks.Count > 0 ? new AggregateKeyEscrowSink(escrowSinks) : null;
            _activator     = activator;
            TriggerAndResetCacheExpirationToken(suppressLogging: true);
            _internalKeyManager = _internalKeyManager ?? this;
            _encryptorFactories = keyManagementOptions.Value.AuthenticatedEncryptorFactories;
        }
예제 #23
0
    private static IDataProtectionBuilder UseCryptographicAlgorithmsCore(IDataProtectionBuilder builder, AlgorithmConfiguration configuration)
    {
        ((IInternalAlgorithmConfiguration)configuration).Validate(); // perform self-test

        builder.Services.Configure <KeyManagementOptions>(options =>
        {
            options.AuthenticatedEncryptorConfiguration = configuration;
        });

        return(builder);
    }
        public Bitmap Encode(Bitmap inputImage, string payload, AlgorithmConfiguration algconfig)
        {
            var config = algconfig as DwtSvdConfiguration;

            SetChannelFromConfiguration(config);
            SetQuarterFromConfiguration(config);
            decimal[][,] inputDoubles = _imageArrayConverter.BitmapToPrecisionMatrices(inputImage.DeepClone());
            _dwtHandler.OriginalImage = inputDoubles.DeepClone();
            _dwtHandler.ApplyHaarTransform(true, true, _iterations);

            var imageAfterDwt = _dwtHandler.TransformedImage.DeepClone();

            decimal[][,] quarter = ExtractQuarter(imageAfterDwt, _iterations, _quarter);

            var payloadDoubleVector = _stringArrayConverter.StringPayloadToArray(payload);

            //var smallImg2DMatrices = _imageArrayConverter.BitmapToMatrices(smallImage);
            var quarterDouble = _matrixService.DecimalToDouble(quarter);

            var smallMatrixWatermarked = _svdHandler.HidePayloadSVD(quarterDouble, payloadDoubleVector, _channel);

            var smallMatrixPrecisionWatermarked = _matrixService.DoubleToDecimal(smallMatrixWatermarked);

            var bigImageWatermarked = MergeQuarter(smallMatrixPrecisionWatermarked, imageAfterDwt, _iterations, _quarter);

            //var smallImageWatermarked = _imageArrayConverter.MatricesToBitmap(smallArrayWatermarked);

            Debug.WriteLine("");
            Debug.WriteLine($"Value of image Height after dwt / 2* iterations Height: { imageAfterDwt[0].GetLength(1) / Convert.ToInt32(Math.Pow(2, _iterations)) }");
            //Debug.WriteLine($"Value of small image watermarked  Height: { smallImageWatermarked.Height }");
            //for (int i = 0; i < smallImageWatermarked.Height; i++)
            //{
            //    for (int j = 0; j < smallImageWatermarked.Width; j++)
            //    {
            //        Color color = smallImageWatermarked.GetPixel(j, i);
            //        //Debug.WriteLine($"Value of color{ color }");
            //        imageAfterDwt.SetPixel(j + (imageAfterDwt.Width / Convert.ToInt32(Math.Pow(2, _iterations))), i + (imageAfterDwt.Height / Convert.ToInt32(Math.Pow(2, _iterations))), color);
            //    }
            //}

            _dwtHandler.OriginalImage    = null;
            _dwtHandler.TransformedImage = null;
            _dwtHandler.TransformedImage = bigImageWatermarked;
            _dwtHandler.ApplyHaarTransform(false, true, _iterations);
            var newMatrix = _dwtHandler.OriginalImage;

            //_dctHandler = new DctAlgorithm(inputImage.Width, inputImage.Height);
            //var arrayAfterDwt = _dctHandler.BitmapToMatrices(_dwtHandler.OriginalImage);
            //var arrayAfterDct = _dctHandler.DCTMatrices(arrayAfterDwt);

            //var newImage = imageAfterDwt;
            //var newImage = converter.Array2DToBitmap(doubleArray);
            var newImage = _imageArrayConverter.MatricesPrecisionToBitmap(newMatrix);  //IMAGE WATERMARKED

            //var newImage = _dwtHandler.TransformedImage;
            //var newImage = _dctHandler.MatricesToBitmap(arrayAfterDct);
            //var newImage = smallImage;

            Debug.WriteLine($"image with water mark dimensions: {newImage.Width} x {newImage.Height}");

            var areEquals = AreEquals(inputImage, newImage);

            Debug.WriteLine($"Are before and after equals (0 mean equal, -1 different sizes, >0 differences count): {areEquals}");

            //MessageBox.Show($"Meassures : {newImage.Width}, {newImage.Height}");
            _dwtHandler.OriginalImage    = null;
            _dwtHandler.TransformedImage = null;

            return(newImage);
        }
예제 #25
0
        public BitmapImage GetWatermarkedImage(BitmapImage bitmapImage, string payload, IReversibleWatermarkingAlgorithm algorithm, AlgorithmConfiguration configuration)
        {
            Bitmap originalBitmap = BitmapImageToBitmap(bitmapImage);
            Bitmap encodedBitmap  = algorithm.Encode(originalBitmap, payload, configuration);

            return(BitmapToBitmapImage(encodedBitmap));
        }
예제 #26
0
        public Tuple <BitmapImage, string> GetDecodedImage(BitmapImage bitmapImage, IReversibleWatermarkingAlgorithm algorithm, AlgorithmConfiguration configuration)
        {
            Bitmap encodedImage = BitmapImageToBitmap(bitmapImage);
            Tuple <Bitmap, string> decodingResult = algorithm.Decode(encodedImage, configuration);

            return(decodingResult != null ? new Tuple <BitmapImage, string>(BitmapToBitmapImage(decodingResult.Item1), decodingResult.Item2) : null);
        }
 public Bitmap Encode(Bitmap inputImage, string payload, AlgorithmConfiguration configuration)
 {
     throw new NotImplementedException();
 }
예제 #28
0
 public DijkstraAlgorithm(AlgorithmConfiguration cfg)
 {
     _graph   = cfg.Graph;
     _trip    = cfg.Trip;
     _endNode = cfg.LastNode;
 }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataProvider"/> class.
 /// </summary>
 /// <param name="factory">for generating output.</param>
 /// <param name="implementation">Exchange implementation of data provider.</param>
 /// <param name="settings">The settings of the algorithm.</param>
 public DataProvider(ILoggerFactory factory, AbstractDataProvider implementation, AlgorithmConfiguration settings)
 {
     Implementation          = implementation;
     _algorithmConfiguration = settings;
     _logger = factory.CreateLogger(GetType());
 }
 private void BtnConfigHS_Click(object sender, RoutedEventArgs e)
 {
     if (isWatermarkingModeSelected())
     {
         HashSet <EmbeddingChanel> set = new HashSet <EmbeddingChanel>();
         set.Add(EmbeddingChanel.R);
         HistogramShiftingConfiguration config = new HistogramShiftingConfiguration(false, set);
         var dialogBox = new ConfigurationDialogBox.HistogramShiftingConfiguraitonDialogBox(
             config.EmbeddingChanels)
         {
             Owner = this,
         };
         dialogBox.ShowDialog();
         if (dialogBox.DialogResult == true)
         {
             if (dialogBox.cbR.IsChecked == true)
             {
                 HashSet <EmbeddingChanel> embeddingChanels = new HashSet <EmbeddingChanel>();
                 if (dialogBox.cbR.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.R);
                 }
                 if (dialogBox.cbG.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.G);
                 }
                 if (dialogBox.cbB.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.B);
                 }
                 currentEncodingHsConfiguration = new HistogramShiftingConfiguration(false, embeddingChanels);
             }
         }
     }
     if (isAnalyzingModeSelected())
     {
         HashSet <EmbeddingChanel> set = new HashSet <EmbeddingChanel>();
         set.Add(EmbeddingChanel.R);
         HistogramShiftingConfiguration config = new HistogramShiftingConfiguration(false, set);
         var dialogBox = new ConfigurationDialogBox.HistogramShiftingConfiguraitonDecodingDialogBox(
             config.EmbeddingChanels)
         {
             Owner = this,
         };
         dialogBox.ShowDialog();
         if (dialogBox.DialogResult == true)
         {
             if (dialogBox.cbR.IsChecked == true)
             {
                 HashSet <EmbeddingChanel> embeddingChanels = new HashSet <EmbeddingChanel>();
                 if (dialogBox.cbR.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.R);
                 }
                 if (dialogBox.cbG.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.G);
                 }
                 if (dialogBox.cbB.IsChecked == true)
                 {
                     embeddingChanels.Add(EmbeddingChanel.B);
                 }
                 currentDecodingHsConfiguration = new HistogramShiftingConfiguration(dialogBox.cbBruteforce.IsChecked == true, embeddingChanels);
             }
         }
     }
 }