Esempio n. 1
0
        public IAppConfiguration GetAppConfiguration(string baseBath, DecryptionService decryptionService, string environmentName = "")
        {
            var appConfig = BuildAppConfiguration(baseBath, environmentName);

            DecryptEncryptedValues(appConfig, decryptionService);
            return(appConfig);
        }
Esempio n. 2
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Add(new WebConfigProvider())
                                .Build();
            var _certificateService = new WindowsCertificateService();
            var decryptionService   = new DecryptionService(_certificateService);

            var appConfig = new AppConfiguration();

            ConfigurationBinder.Bind(configuration, appConfig);

            var provider = new IdentityProviderSearchServiceConfigurationProvider(appConfig.EncryptionCertificateSettings, decryptionService);

            provider.GetAppConfiguration(appConfig);

            var logger = LogFactory.CreateTraceLogger(new LoggingLevelSwitch(), appConfig.ApplicationInsights);

            logger.Information("IdentityProviderSearchService is starting up...");

            appConfig.ConfigureIdentityServiceUrl();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = appConfig.IdentityServerConfidentialClientSettings.Authority,
                RequiredScopes = appConfig.IdentityServerConfidentialClientSettings.Scopes
            });

            app.UseNancy(opt => opt.Bootstrapper = new Bootstrapper(appConfig, logger));
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        public void GetAppConfiguration_ReturnsAppConfig_Success()
        {
            // Arrange
            var privateKey      = GetPrivateKey();
            var clientSecret    = Guid.NewGuid().ToString();
            var appSettingsJson = GetAppSettingsJson(privateKey, clientSecret);
            var directory       = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "test"));

            File.WriteAllText(Path.Combine(directory.FullName, "appsettings.json"), appSettingsJson);
            var mockCertificateService = GetMockCertificateService(privateKey);
            var decryptionService      = new DecryptionService(mockCertificateService);
            var config = new ConfigurationBuilder()
                         .AddJsonFile(Path.Combine(directory.FullName, "appsettings.json"))
                         .Build();
            var identityConfigurationProvider = new IdentityConfigurationProvider(config);


            // Act
            var appConfig = identityConfigurationProvider.GetAppConfiguration(decryptionService);

            // Assert
            Assert.NotNull(appConfig);
            Assert.Equal(clientSecret, appConfig.IdentityServerConfidentialClientSettings.ClientSecret);
            Assert.Equal(clientSecret, appConfig.AzureActiveDirectorySettings.ClientSecret);
            Assert.Equal("InMemory", appConfig.HostingOptions.StorageProvider);
            Assert.Equal("HQCATALYST", appConfig.FilterSettings.GroupFilterSettings.Prefixes[0]);
            Assert.Equal(clientSecret, appConfig.AzureActiveDirectoryClientSettings.ClientAppSettings[0].ClientSecret);
            Assert.Equal(clientSecret, appConfig.AzureActiveDirectoryClientSettings.ClientAppSettings[1].ClientSecret);
        }
Esempio n. 4
0
        protected async Task <bool> IsUserValidAsync()
        {
            var userIsValid = await UserModel.CheckUserExistsByIdAsync(
                ExtractUserIdFromToken(), RepositoryManager.UserRepository);

            if (userIsValid)
            {
                var user = await UserModel.GetUserByIdAsync(
                    ExtractUserIdFromToken(), RepositoryManager.UserRepository);

                if (user.UserSecret != null)
                {
                    var decryptedUserSecret = DecryptionService.DecryptString(user.UserSecret);

                    if (decryptedUserSecret == ExtractUserSecretFromToken())
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(userIsValid);
            }
        }
Esempio n. 5
0
        public IAppConfiguration GetAppConfiguration(DecryptionService decryptionService)
        {
            var appConfig = BuildAppConfiguration();

            DecryptEncryptedValues(appConfig, decryptionService);
            return(appConfig);
        }
Esempio n. 6
0
        private void DecryptEncryptedValues(IAppConfiguration appConfiguration, DecryptionService decryptionService)
        {
            if (appConfiguration.ElasticSearchSettings != null)
            {
                appConfiguration.ElasticSearchSettings.Password = decryptionService.DecryptString(
                    appConfiguration.ElasticSearchSettings.Password, appConfiguration.SigningCertificateSettings);
            }

            if (appConfiguration.CouchDbSettings != null)
            {
                appConfiguration.CouchDbSettings.Password = decryptionService.DecryptString(
                    appConfiguration.CouchDbSettings.Password, appConfiguration.SigningCertificateSettings);
            }

            if (appConfiguration.LdapSettings != null)
            {
                appConfiguration.LdapSettings.Password = decryptionService.DecryptString(
                    appConfiguration.LdapSettings.Password, appConfiguration.SigningCertificateSettings);
            }

            if (appConfiguration.IdentityServerConfidentialClientSettings != null)
            {
                appConfiguration.IdentityServerConfidentialClientSettings.ClientSecret =
                    decryptionService.DecryptString(
                        appConfiguration.IdentityServerConfidentialClientSettings.ClientSecret,
                        appConfiguration.SigningCertificateSettings);
            }

            if (appConfiguration.AzureActiveDirectorySettings?.ClientSecret != null)
            {
                appConfiguration.AzureActiveDirectorySettings.ClientSecret = decryptionService.DecryptString(
                    appConfiguration.AzureActiveDirectorySettings.ClientSecret,
                    appConfiguration.SigningCertificateSettings);
            }
        }
Esempio n. 7
0
        private TestServer CreateTestServer(string storageProvider, Action <IWebHostBuilder> customizeWebHost)
        {
            var loggerConfiguration = new LoggerConfiguration();

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json")
                                .AddEnvironmentVariables()
                                .AddDockerSecrets(typeof(IAppConfiguration))
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .Build();

            var certificateService = IdentityConfigurationProvider.MakeCertificateService();
            var decryptionService  = new DecryptionService(certificateService);
            var appConfig          = new IdentityConfigurationProvider(configuration).GetAppConfiguration(decryptionService);

            LogFactory.ConfigureTraceLogger(loggerConfiguration, appConfig.ApplicationInsights);

            Log.Logger = loggerConfiguration.CreateLogger();



            var hostingOptions = new HostingOptions
            {
                UseIis          = false,
                UseTestUsers    = true,
                StorageProvider = storageProvider
            };

            var apiBuilder = WebHost.CreateDefaultBuilder();

            apiBuilder.ConfigureServices(c => c.AddSingleton(LdapSettings)
                                         .AddSingleton(Log.Logger)
                                         .AddSingleton(CouchDbSettings)
                                         .AddSingleton(hostingOptions)
                                         .AddSingleton(ConnectionStrings)
                                         .AddSingleton(GraphApi)
                                         .AddSingleton(ADProxy)
                                         .AddTransient <IExternalIdentityProviderSearchService, ActiveDirectoryProviderService>()
                                         .AddTransient <IExternalIdentityProviderSearchService, AzureDirectoryProviderService>()
                                         );

            customizeWebHost?.Invoke(apiBuilder);

            apiBuilder
            .ConfigureAppConfiguration((hostContext, config) =>
            {
                config.AddDockerSecrets(typeof(IAppConfiguration));
                config.SetBasePath(Directory.GetCurrentDirectory());
            })
            .UseUrls(RegistrationApiServerUrl)
            .ConfigureKestrel((context, kestrelOptions) =>
            {
            })
            .UseSerilog()
            .UseStartup <Startup>();

            return(new TestServer(apiBuilder));
        }
Esempio n. 8
0
        public Startup(IConfiguration configuration)
        {
            _certificateService = IdentityConfigurationProvider.MakeCertificateService();
            var decryptionService = new DecryptionService(_certificateService);

            _appConfig =
                new IdentityConfigurationProvider(configuration).GetAppConfiguration(decryptionService);
        }
Esempio n. 9
0
 public AmqpConsumerFactory(ISendHandler sendHandler, IDokumentlagerHandler dokumentlagerHandler, KontoConfiguration kontoConfiguration)
 {
     _dokumentlagerHandler = dokumentlagerHandler;
     _fileWriter           = new FileWriter();
     _decrypter            = new AsicDecrypter(DecryptionService.Create(kontoConfiguration.PrivatNokkel));
     _sendHandler          = sendHandler;
     _accountId            = kontoConfiguration.KontoId;
 }
Esempio n. 10
0
        public Startup(IHostingEnvironment env)
        {
            _certificateService = MakeCertificateService();
            var decryptionService = new DecryptionService(_certificateService);

            _appConfig =
                new IdentityConfigurationProvider().GetAppConfiguration(env.ContentRootPath, decryptionService, env.EnvironmentName);
            _loggingLevelSwitch = new LoggingLevelSwitch();
            _logger             = LogFactory.CreateTraceLogger(_loggingLevelSwitch, _appConfig.ApplicationInsights);
        }
Esempio n. 11
0
        public static async Task QueueAlbumAsync(
            string albumId,
            Guid userId,
            IRepositoryManager repositoryManager,
            SpotifyAPICredentials spotifyAPICredentials)
        {
            try
            {
                var user = await repositoryManager.UserRepository.GetByIdAsync(userId);

                if (user != null)
                {
                    if (user.SpotifyRefreshToken != null)
                    {
                        var spotifyAuthRefreshRequest = new AuthorizationCodeRefreshRequest
                                                        (
                            spotifyAPICredentials.ClientId,
                            spotifyAPICredentials.ClientSecret,
                            DecryptionService.DecryptString(user.SpotifyRefreshToken)
                                                        );

                        var spotifyAuthResponse = await new OAuthClient().RequestToken(spotifyAuthRefreshRequest);
                        var spotifyToken        = spotifyAuthResponse.AccessToken;

                        var spotifyClient = new SpotifyClient(spotifyToken);

                        var activeDevices = await spotifyClient.Player.GetAvailableDevices();

                        if (activeDevices.Devices.Count > 0)
                        {
                            var album = await spotifyClient.Albums.Get(albumId);

                            foreach (var track in album.Tracks.Items)
                            {
                                var trackQueueRequest = new PlayerAddToQueueRequest(track.Uri);

                                await spotifyClient.Player.AddToQueue(trackQueueRequest);
                            }
                        }
                        else
                        {
                            throw new SpotifyNoActiveDevicesException("No Active Devices Found", "No Active Devices Found");
                        }
                    }
                    else
                    {
                        throw new SpotifyNotLinkedException("Spotify Account not Linked", "Spotify Account not Linked");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 12
0
        private string GenerateJwtToken(string userId, string userSecret)
        {
            var decryptedUserSecret = DecryptionService.DecryptString(userSecret);

            SecurityTokenDescriptor tokenDescriptor = GetTokenDescriptor(userId, decryptedUserSecret);

            var           tokenHandler  = new JwtSecurityTokenHandler();
            SecurityToken securityToken = tokenHandler.CreateToken(tokenDescriptor);
            string        token         = tokenHandler.WriteToken(securityToken);

            return(token);
        }
Esempio n. 13
0
        public static async Task <bool> ValidatePasswordResetTokenAsync(
            string passwordResetToken,
            IPasswordResetRepository passwordResetRepository)
        {
            var decryptedResetToken   = DecryptionService.DecryptString(passwordResetToken);
            var hashedResetIdentifier = HashingHelper.HashIdentifier(decryptedResetToken);

            var(existsAndValid, _) = await CheckPasswordResetIdentifierExistsAndIsValidAsync(
                hashedResetIdentifier,
                passwordResetRepository).ConfigureAwait(false);

            return(existsAndValid);
        }
        public void DecryptString_HandlesNullOrEmptyString(string stringToDecrypt)
        {
            // Arrange
            var privateKey                 = GetPrivateKey();
            var mockCertificateService     = GetMockCertificateService(privateKey);
            var signingCertificateSettings = new SigningCertificateSettings();
            var decryptionService          = new DecryptionService(mockCertificateService);

            // Act
            var decryptedString = decryptionService.DecryptString(stringToDecrypt, signingCertificateSettings);

            // Assert
            Assert.Equal(stringToDecrypt, decryptedString);
        }
        public void DecryptString_ThrowsFormatException_InvalidBase64String()
        {
            // Arrange
            var privateKey      = GetPrivateKey();
            var stringToEncrypt = Guid.NewGuid().ToString();
            var encryptedString = $"{DecryptionService.EncryptionPrefix}{EncryptString(privateKey, stringToEncrypt).Substring(1)}";

            var mockCertificateService     = GetMockCertificateService(privateKey);
            var signingCertificateSettings = new SigningCertificateSettings();
            var decryptionService          = new DecryptionService(mockCertificateService);

            // Act & Assert
            Assert.Throws <FormatException>(
                () => decryptionService.DecryptString(encryptedString, signingCertificateSettings));
        }
        public void DecryptString_ReturnsNonEncryptedString()
        {
            // Arrange
            var privateKey = GetPrivateKey();
            var clearTextstringToDecrypt = Guid.NewGuid().ToString();

            var mockCertificateService     = GetMockCertificateService(privateKey);
            var signingCertificateSettings = new SigningCertificateSettings();
            var decryptionService          = new DecryptionService(mockCertificateService);

            // Act
            var decryptedString = decryptionService.DecryptString(clearTextstringToDecrypt, signingCertificateSettings);

            // Assert
            Assert.Equal(clearTextstringToDecrypt, decryptedString);
        }
        private async void FetchAndSetView(object sender, EventArgs e)
        {
            if (mRecyclerView.GetAdapter() != null)
            {
                await Task.Delay(2000);
            }
            var TempAllNotes = await NotesDatabase.GetAllNotesList();

            AllNotes = new List <NoteModel>();
            if (TempAllNotes != null)
            {
                string password = await SecureStorage.GetAsync("AppPassword");

                if (password == null)
                {
                    return;
                }
                for (int i = 0; i < TempAllNotes.Count; i++)
                {
                    try
                    {
                        var DecryptionResult = DecryptionService.DecryptText(TempAllNotes[i].NoteContent, password);
                        if (DecryptionResult.Result)
                        {
                            TempAllNotes[i].NoteContent = DecryptionResult.DecryptedString;
                            AllNotes.Add(TempAllNotes[i]);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            AllNotes                = AllNotes.OrderByDescending(i => i.NoteLastModifiedTime.Ticks).ToList();
            notesAdapter            = new NotesAdapter(AllNotes);
            notesAdapter.ItemClick += NotesAdapter_ItemClick;
            if (mRecyclerView.GetAdapter() == null)
            {
                mRecyclerView.SetAdapter(notesAdapter);
            }
            else
            {
                mRecyclerView.SwapAdapter(notesAdapter, false);
            }
            IsLoading = false;
            swipeContainer.Refreshing = false;
        }
        public void DecryptString_DecryptsEncryptedString()
        {
            // Arrange
            var privateKey      = GetPrivateKey();
            var stringToEncrypt = Guid.NewGuid().ToString();
            var encryptedString = $"{DecryptionService.EncryptionPrefix}{EncryptString(privateKey, stringToEncrypt)}";

            var mockCertificateService     = GetMockCertificateService(privateKey);
            var signingCertificateSettings = new SigningCertificateSettings();
            var decryptionService          = new DecryptionService(mockCertificateService);

            // Act
            var decryptedString = decryptionService.DecryptString(encryptedString, signingCertificateSettings);

            // Assert
            Assert.Equal(stringToEncrypt, decryptedString);
        }
Esempio n. 19
0
        public static async Task <IEnumerable <SimplePlaylist> > GetUserPlaylistsAsync(
            SpotifyAPICredentials spotifyAPICredentials,
            Guid userId,
            int page,
            int pageSize,
            IRepositoryManager repositoryManager)
        {
            try
            {
                var user = await repositoryManager.UserRepository.GetByIdAsync(userId);

                if (user.SpotifyRefreshToken != null)
                {
                    var spotifyAuthRefreshRequest = new AuthorizationCodeRefreshRequest
                                                    (
                        spotifyAPICredentials.ClientId,
                        spotifyAPICredentials.ClientSecret,
                        DecryptionService.DecryptString(user.SpotifyRefreshToken)
                                                    );

                    var spotifyAuthResponse = await new OAuthClient().RequestToken(spotifyAuthRefreshRequest);
                    var spotifyToken        = spotifyAuthResponse.AccessToken;

                    var spotifyClient = new SpotifyClient(spotifyToken);

                    var playlistsRequest = new PlaylistCurrentUsersRequest
                    {
                        Limit  = pageSize,
                        Offset = page * pageSize
                    };

                    var playlists = await spotifyClient.Playlists.CurrentUsers(playlistsRequest);

                    return(playlists.Items);
                }
                else
                {
                    throw new SpotifyNotLinkedException("Spotify Account not Linked", "Spotify Account not Linked");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 20
0
        public static void Main(string[] args)
        {
            var loggerConfiguration = new LoggerConfiguration();

            //Create a builder just so that we can read the app insights instrumentation key from the config
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                                .Build();

            var certificateService = IdentityConfigurationProvider.MakeCertificateService();
            var decryptionService  = new DecryptionService(certificateService);
            var appConfig          = new IdentityConfigurationProvider(configuration).GetAppConfiguration(decryptionService);

            LogFactory.ConfigureTraceLogger(loggerConfiguration, appConfig.ApplicationInsights);

            Log.Logger = loggerConfiguration.CreateLogger();

            try
            {
                Log.Information("Starting web host");
                CreateWebHostBuilder(args).Build().Run();

                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");

                Environment.Exit(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Esempio n. 21
0
        public static async Task ResetPasswordAsync(
            string passwordResetToken,
            string newPassword,
            string requesterAddress,
            IRepositoryManager repositoryManager)
        {
            var decryptedResetToken   = DecryptionService.DecryptString(passwordResetToken);
            var hashedResetIdentifier = HashingHelper.HashIdentifier(decryptedResetToken);

            var(existsAndValid, passwordReset) = await CheckPasswordResetIdentifierExistsAndIsValidAsync(
                hashedResetIdentifier,
                repositoryManager.PasswordResetRepository).ConfigureAwait(false);

            if (existsAndValid)
            {
                var userId = Guid.Parse(DecryptionService.DecryptString(passwordReset.UserId));
                var user   = await repositoryManager.UserRepository.GetByIdAsync(userId);

                user.Password      = HashingHelper.HashPassword(newPassword);
                user.UserSecret    = EncryptionService.EncryptString(ModelHelpers.GenerateUniqueIdentifier(IdentifierConsts.UserIdentifierLength));
                user.LastUpdatedOn = DateTime.Now;
                user.LastUpdatedBy = userId;

                passwordReset.Active        = false;
                passwordReset.UsedOn        = DateTime.Now;
                passwordReset.UsedByAddress = requesterAddress;
                passwordReset.LastUpdatedOn = DateTime.Now;

                await repositoryManager.UserRepository.UpdateAsync(user);

                await repositoryManager.PasswordResetRepository.UpdateAsync(passwordReset);
            }
            else
            {
                throw new InvalidTokenException(InvalidTokenType.TokenNotFound, "The Password Reset Token is invalid");
            }
        }
        public void ConfigurationProvider_DecryptsSecret_Successfully(int count)
        {
            var privateKey      = GetPrivateKey();
            var clientSecret    = Guid.NewGuid().ToString();
            var appSettingsJson = GetEncryptedAppSettings(privateKey, clientSecret, count);
            var directory       = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "test"));

            File.WriteAllText(Path.Combine(directory.FullName, "appsettings.json"), appSettingsJson);
            var mockCertificateService = GetMockCertificateService(privateKey);
            var decryptionService      = new DecryptionService(mockCertificateService);

            var appConfig      = GetAppConfiguration();
            var configProvider = new IdentityProviderSearchServiceConfigurationProvider(new EncryptionCertificateSettings(), decryptionService);

            // Act
            configProvider.GetAppConfiguration(appConfig);

            // Assert
            Assert.NotNull(appConfig);
            for (int i = 0; i < count; i++)
            {
                Assert.Equal(clientSecret, appConfig.AzureActiveDirectoryClientSettings.ClientAppSettings[i].ClientSecret);
            }
        }
 public IdentityProviderSearchServiceConfigurationProvider(EncryptionCertificateSettings encryptionCertificateSettings, DecryptionService decryptionService)
 {
     _encryptionCertificateSettings = encryptionCertificateSettings ?? throw new ArgumentNullException(nameof(encryptionCertificateSettings));
     _decryptionService             = decryptionService ?? throw new ArgumentNullException(nameof(decryptionService));
 }
Esempio n. 24
0
        private async void DecryptButton_Click(object sender, EventArgs e)
        {
            var RemoveButtonState = DisableAllControls();

            if (String.IsNullOrEmpty(TextInputEditor.Text) && fileData == null)
            {
                RestoreAllControls(RemoveButtonState);
                ShowDialog("Error", "Choose file or write/paste text to encrypt!");
                DecryptButton.Enabled = false;
                return;
            }
            if (!String.IsNullOrEmpty(TextInputEditor.Text) && fileData != null)
            {
                RestoreAllControls(RemoveButtonState);
                ShowDialog("Error", "You can encrypt either file or text at a time!");
                return;
            }
            string password = "";

            try
            {
                password = await SecureStorage.GetAsync("AppPassword");

                if (password == null)
                {
                    ShowDialog("Error", "App's password is missing. Close application and try again!");
                    return;
                }
            }
            catch (Exception)
            {
                ShowDialog("Error", "App's password is missing. Close application and try again!");
                return;
            }
            if (!PasswordSwitch.Checked)
            {
                if (String.IsNullOrEmpty(CustomPasswordEntry.Text) || CustomPasswordEntry.Text.Length < 6 || CustomPasswordEntry.Text.Length > 16)
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Error", "Custom Password length should be at least 6 and at most 16");
                    return;
                }
                password = CustomPasswordEntry.Text;
            }
            if (fileData == null)
            {
                DecryptionResult decryptionResult = null;
                await Task.Run(() =>
                {
                    decryptionResult = DecryptionService.DecryptText(TextInputEditor.Text, password);
                });

                if (decryptionResult.Result)
                {
                    ClipboardManager clipboardManager = (ClipboardManager)this.GetSystemService(Context.ClipboardService);
                    clipboardManager.PrimaryClip = ClipData.NewPlainText("Decrypted Text", decryptionResult.DecryptedString);
                    Toast.MakeText(this, "Decrypted text copied to clipboard", ToastLength.Long);
                    fileData = null;
                    RestoreAllControls(ViewStates.Invisible);
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.Checked   = true;
                    ShowDialog("Decrypted Text", decryptionResult.DecryptedString);
                }
                else
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Failed", "Decryption failed. This text can not be encrypted. Error: \"" + decryptionResult.Error + "\"");
                }
            }
            else
            {
                DecryptionResult decryptionResult = null;
                await Task.Run(() =>
                {
                    decryptionResult = DecryptionService.DecryptFile(fileData, password);
                });

                if (decryptionResult.Result)
                {
                    RestoreAllControls(ViewStates.Invisible);
                    ShowDialog("Success", "File decrypted. Decrypted filename is \"" + decryptionResult.DecryptedString + "\" and stored at \"Crypto App" + "\" folder.");
                    fileData = null;
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.Checked   = true;
                }
                else if (decryptionResult.Result == false && decryptionResult.Error == "Password")
                {
                    RestoreAllControls(RemoveButtonState);
                    PasswordSwitch.Checked         = false;
                    CustomPasswordEntry.Visibility = ViewStates.Visible;
                    ShowDialog("Error", "Password is wrong. Enter correct password to decrypt.");
                    return;
                }
                else
                {
                    RestoreAllControls(RemoveButtonState);
                    ShowDialog("Failed", "File decryption failed. This file can not be decrypted.Error: \"" + decryptionResult.Error + "\"");
                }
            }
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            int option = 99999;

            do
            {
                try
                {
                    //Iniciando a aplicacao
                    Console.WriteLine("Insira a opção desejada:");
                    Console.WriteLine("1 - CRIPTOGRAFIA");
                    Console.WriteLine("2 - DESCRIPTOGRAFIA");
                    Console.WriteLine("0 - SAIR");
                    option = Convert.ToInt32(Console.ReadLine());

                    switch (option)
                    {
                    case 1:

                        bool repeat = false;

                        do
                        {
                            Console.WriteLine("Insira uma palavra!(6 dígitos)");
                            string word   = Console.ReadLine();
                            int    length = word.Length;

                            //Verificando se a palavra possui 6 digitos
                            if (length == 6)
                            {
                                var cryptographer = new CryptographyService();

                                word = word.ToUpper();
                                Console.WriteLine("Palavra inserida: " + word + "\n");

                                //Convertendo e exibindo a matriz numerica da palavra
                                var matrix = cryptographer.ConverterWordToMatrix(word);
                                Console.WriteLine("Matriz convertida:\n");
                                for (int l = 0; l < 3; l++)
                                {
                                    for (int c = 0; c < 2; c++)
                                    {
                                        if (c != 1)
                                        {
                                            Console.Write(matrix[l, c] + " - ");
                                        }
                                        else
                                        {
                                            Console.Write(matrix[l, c] + "\n");
                                        }
                                    }
                                }

                                //Convertendo e exibindo a matriz criptografada
                                var mc = cryptographer.CryptographyMatrix(matrix);
                                Console.WriteLine("\nMatriz criptografada:\n");
                                for (int l = 0; l < 3; l++)
                                {
                                    for (int c = 0; c < 2; c++)
                                    {
                                        if (c != 1)
                                        {
                                            Console.Write(mc[l, c] + " - ");
                                        }
                                        else
                                        {
                                            Console.Write(mc[l, c] + "\n");
                                        }
                                    }
                                }

                                break;
                            }
                            else
                            {
                                Console.WriteLine("****** INSIRA UMA PALAVRA DE 6 DÍGITOS ******\n");
                                repeat = true;
                            }
                        } while (repeat);

                        break;

                    case 2:

                        int[,] mcForDecryptography = new int[3, 2];
                        int i = 1;

                        //Indicando modo de insercao da matrix
                        Console.WriteLine("\nInsira a MC na ordem a seguir:");
                        Console.WriteLine("1 - 6");
                        Console.WriteLine("2 - 5");
                        Console.WriteLine("3 - 4\n");

                        for (int c = 0; c < 2; c++)
                        {
                            for (int l = 0; l < 3; l++)
                            {
                                Console.Write("Insira o " + i + "º número:");
                                mcForDecryptography[l, c] = Convert.ToInt32(Console.ReadLine());
                                i++;
                            }
                        }

                        var decrypter = new DecryptionService();

                        //Descriptografando a matriz inserida
                        var matrixDecrypted = decrypter.DecryptionMatrix(mcForDecryptography);

                        //Convertendo a matriz em numero
                        var wordDecrypted = decrypter.ConverterMatrixToWord(matrixDecrypted);

                        //Aqui verifica se a matriz inserida é valida, vaso nao seja válida, retornará null do metodo ConverterMatrixToWord e entrará no if
                        if (wordDecrypted == null)
                        {
                            Console.WriteLine("\n****** A MATRIZ INSERIDA NÃO É VÁLIDA ******\n");
                            Console.ReadLine();
                            break;
                        }


                        //Exibindo matriz inserida
                        Console.WriteLine("\nMatriz inserida:\n");
                        for (int l = 0; l < 3; l++)
                        {
                            for (int c = 0; c < 2; c++)
                            {
                                if (c != 1)
                                {
                                    Console.Write(mcForDecryptography[l, c] + " - ");
                                }
                                else
                                {
                                    Console.Write(mcForDecryptography[l, c] + "\n");
                                }
                            }
                        }

                        //Exibindo a matriz sem criptografia
                        Console.WriteLine("Matriz sem criptografia:\n");
                        for (int l = 0; l < 3; l++)
                        {
                            for (int c = 0; c < 2; c++)
                            {
                                if (c != 1)
                                {
                                    Console.Write(matrixDecrypted[l, c] + " - ");
                                }
                                else
                                {
                                    Console.Write(matrixDecrypted[l, c] + "\n");
                                }
                            }
                        }

                        //Exibindo a palavra resultado
                        Console.WriteLine("A matriz inserida representa a palavra: " + wordDecrypted);
                        Console.ReadLine();

                        break;

                    case 0:
                        break;

                    default:
                        Console.WriteLine("****** INSIRA UMA OPÇÃO VÁLIDA ******\n");
                        break;
                    }
                }
                catch (FormatException e)
                {
                    Console.WriteLine("****** INSIRA UM NÚMERO ******\n");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            } while (option != 0);
        }
Esempio n. 26
0
        public void ConfigureServices(IServiceCollection services)
        {
            DecryptionService.Decrypt(Arg.Any <string>()).Returns(x => "[decrypted] " + x.ArgAt <string>(0));

            services.AddSingleton(DecryptionService);
        }
Esempio n. 27
0
        private async void EncryptButton_Click(object sender, RoutedEventArgs e)
        {
            bool RemoveButtonState = DisableAllControls();

            if (String.IsNullOrEmpty(TextInputEditor.Text) && fileData == null)
            {
                RestoreAllControls(RemoveButtonState);
                await new ContentDialog()
                {
                    Title = "Error", Content = "Choose file or paste text to decrypt!", CloseButtonText = "Okay"
                }.ShowAsync();
                EncryptButton.IsEnabled = false;
                return;
            }
            string password = "******";

            if (!PasswordSwitch.IsOn)
            {
                if (String.IsNullOrEmpty(CustomPasswordEntry.Text) || CustomPasswordEntry.Text.Length < 6 || CustomPasswordEntry.Text.Length > 16)
                {
                    RestoreAllControls(RemoveButtonState);
                    CustomPasswordEntry.Focus(FocusState.Programmatic);
                    await new ContentDialog()
                    {
                        Title = "Error", Content = "Custom Password length should be at least 6 and at most 16", CloseButtonText = "Okay"
                    }.ShowAsync();
                    return;
                }
                password = CustomPasswordEntry.Text;
            }
            if (fileData == null)
            {
                DecryptionResult decryptionResult = null;
                string           plainText        = TextInputEditor.Text;
                await Task.Run(() =>
                {
                    decryptionResult = DecryptionService.DecryptText(plainText, password);
                });

                if (decryptionResult.Result)
                {
                    var FormatedTextSize = DecryptionService.GetFormatedSize(System.Text.Encoding.UTF8.GetByteCount(decryptionResult.DecryptedString));
                    var result           = await new ContentDialog()
                    {
                        Title = "Decrypted Text", Content = decryptionResult.DecryptedString, PrimaryButtonText = "Copy decrypted text", CloseButtonText = "Do not copy"
                    }.ShowAsync();
                    if (result == ContentDialogResult.Primary)
                    {
                        var DP = new DataPackage();
                        DP.SetText(decryptionResult.DecryptedString);
                        Clipboard.SetContent(DP);
                    }
                    fileData = null;
                    RestoreAllControls(false);
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.IsOn      = true;
                }
                else
                {
                    await new ContentDialog()
                    {
                        Title = "Failed", Content = "Decryption failed. This text can not be decrypted. Error: \"" + decryptionResult.Error + "\"", CloseButtonText = "Okay"
                    }.ShowAsync();
                    RestoreAllControls(RemoveButtonState);
                }
            }
            else
            {
                DecryptionResult decryptionResult = null;
                await Task.Run(async() =>
                {
                    decryptionResult = await DecryptionService.DecryptFile(fileData, password);
                });

                if (decryptionResult.Result)
                {
                    ActivityText.Text = "Do not close the application. Saving decrypted file.";
                    FileSavePicker savePicker        = new FileSavePicker();
                    var            FileNameExtension = System.IO.Path.GetExtension(decryptionResult.WritePath);
                    savePicker.FileTypeChoices.Add("Crypto App Decrypted File", new List <string>()
                    {
                        FileNameExtension
                    });
                    savePicker.SuggestedFileName = System.IO.Path.GetFileName(decryptionResult.WritePath);
                    var writeFile = await savePicker.PickSaveFileAsync();

                    if (writeFile != null)
                    {
                        CachedFileManager.DeferUpdates(writeFile);
                        await FileIO.WriteBytesAsync(writeFile, decryptionResult.DecryptedContents);

                        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(writeFile);

                        if (status == FileUpdateStatus.Complete)
                        {
                            await new ContentDialog()
                            {
                                Title = "Success", Content = "File is decrypted and saved as " + writeFile.Name, CloseButtonText = "Okay"
                            }.ShowAsync();
                        }
                        else
                        {
                            await new ContentDialog()
                            {
                                Title = "Failure", Content = "File could not be saved! ", CloseButtonText = "Okay"
                            }.ShowAsync();
                        }
                    }
                    else
                    {
                        await new ContentDialog()
                        {
                            Title = "Cancelled", Content = "File was not saved! ", CloseButtonText = "Okay"
                        }.ShowAsync();
                    }
                    RestoreAllControls(false);
                    fileData = null;
                    RemoveButton_Click(null, null);
                    TextInputEditor.Text     = String.Empty;
                    CustomPasswordEntry.Text = String.Empty;
                    PasswordSwitch.IsOn      = true;
                }
                else if (decryptionResult.Result == false && decryptionResult.Error == "Password")
                {
                    await new ContentDialog()
                    {
                        Title = "Error", Content = "Password is wrong. Enter correct password to decrypt.", CloseButtonText = "Okay"
                    }.ShowAsync();
                    RestoreAllControls(RemoveButtonState);
                    PasswordSwitch.IsOn            = false;
                    CustomPasswordStack.Visibility = Visibility.Visible;
                    CustomPasswordEntry.Focus(FocusState.Programmatic);
                    return;
                }
                else
                {
                    await new ContentDialog()
                    {
                        Title = "Failed", Content = "Decryption failed. This file can not be decrypted. Error: \"" + decryptionResult.Error + "\"", CloseButtonText = "Okay"
                    }.ShowAsync();
                    RestoreAllControls(RemoveButtonState);
                }
            }
        }