Example #1
0
        /// <summary>
        /// Generates a random string of a given length, using the random source of
        /// the operating system.The string contains only safe characters of this
        /// alphabet: 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
        /// </summary>
        /// <param name="length">Number of characters the string should have.</param>
        /// <param name="randomSource">Random generator.</param>
        /// <returns>New randomly generated string.</returns>
        public static string GenerateRandomBase62String(int length, ICryptoRandomSource randomSource)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            StringBuilder result          = new StringBuilder();
            int           remainingLength = length;

            do
            {
                // We take advantage of the fast base64 encoding
                int    binaryLength = (int)((remainingLength * 3.0 / 4.0) + 1.0);
                byte[] randomBytes  = randomSource.GetRandomBytes(binaryLength);
                string base64String = Convert.ToBase64String(randomBytes);

                // Remove invalid characters
                result.Append(base64String);
                result.Replace("+", string.Empty);
                result.Replace("/", string.Empty);
                result.Replace("=", string.Empty);

                // If too many characters have been removed, we repeat the procedure
                remainingLength = length - result.Length;
            }while (remainingLength > 0);

            result.Length = length;
            return(result.ToString());
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RecycleBinViewModel"/> class.
        /// </summary>
        public RecycleBinViewModel(
            INavigationService navigationService,
            ILanguageService languageService,
            ISvgIconService svgIconService,
            IThemeService themeService,
            IBaseUrlService webviewBaseUrl,
            IFeedbackService feedbackService,
            ISettingsService settingsService,
            ICryptoRandomSource randomSource,
            IRepositoryStorageService repositoryService)
            : base(navigationService, languageService, svgIconService, themeService, webviewBaseUrl)
        {
            _feedbackService   = feedbackService;
            _settingsService   = settingsService;
            _repositoryService = repositoryService;
            _noteCryptor       = new Cryptor(NoteModel.CryptorPackageName, randomSource);
            RecycledNotes      = new List <NoteViewModel>();

            _repositoryService.LoadRepositoryOrDefault(out NoteRepositoryModel noteRepository);
            Model = noteRepository;

            // Initialize commands
            GoBackCommand          = new RelayCommand(GoBack);
            RestoreNoteCommand     = new RelayCommand <object>(RestoreNote);
            EmptyRecycleBinCommand = new RelayCommand(EmptyRecycleBin);
        }
Example #3
0
        /// <summary>
        /// This function can be used, if an API key must be stored inside the application code,
        /// so it doesn't show up in plain text.
        /// </summary>
        /// <param name="plainMessage">The text to hide.</param>
        /// <param name="obfuscationKey">Key to use for obfuscation, this key is usually hard coded
        /// in the application.</param>
        /// <param name="randomSource">A cryptographically random source.</param>
        /// <returns>Obfuscated message.</returns>
        public static byte[] Obfuscate(byte[] plainMessage, string obfuscationKey, ICryptoRandomSource randomSource)
        {
            EncryptorDecryptor encryptor = new EncryptorDecryptor("obfuscation");

            return(encryptor.Encrypt(
                       plainMessage,
                       obfuscationKey,
                       KeyDerivationCostType.Low,
                       randomSource,
                       "twofish_gcm"));
        }
Example #4
0
        public void EncryptedKeyCanBeDecrypted()
        {
            byte[]              key          = new byte[] { 88, 99, 11 };
            SecureString        password     = CryptoUtils.StringToSecureString("testpassword");
            ICryptoRandomSource randomSource = CommonMocksAndStubs.CryptoRandomService();

            string encryptedKey = SafeModel.EncryptKey(key, password, randomSource, BouncyCastleAesGcm.CryptoAlgorithmName);
            bool   res          = SafeModel.TryDecryptKey(encryptedKey, password, out byte[] decryptedKey);

            Assert.IsTrue(res);
            Assert.IsTrue(key.SequenceEqual(decryptedKey));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NoteRepositoryViewModel"/> class.
        /// </summary>
        public NoteRepositoryViewModel(
            INavigationService navigationService,
            ILanguageService languageService,
            ISvgIconService svgIconService,
            IThemeService themeService,
            IBaseUrlService webviewBaseUrl,
            IStoryBoardService storyBoardService,
            IFeedbackService feedbackService,
            ISettingsService settingsService,
            IEnvironmentService environmentService,
            ICryptoRandomSource randomSource,
            IRepositoryStorageService repositoryService)
            : base(navigationService, languageService, svgIconService, themeService, webviewBaseUrl)
        {
            _storyBoardService       = storyBoardService;
            _repositoryService       = repositoryService;
            _feedbackService         = feedbackService;
            _settingsService         = settingsService;
            _environmentService      = environmentService;
            _noteCryptor             = new Cryptor(NoteModel.CryptorPackageName, randomSource);
            _searchableTextConverter = new SearchableHtmlConverter();
            AllNotes      = new List <NoteViewModel>();
            FilteredNotes = new ObservableCollection <NoteViewModel>();

            _repositoryService.LoadRepositoryOrDefault(out NoteRepositoryModel noteRepository);
            Model = noteRepository;

            // Initialize commands and events
            ShowNoteCommand           = new RelayCommand <object>(ShowNote);
            NewNoteCommand            = new RelayCommand(NewNote);
            NewChecklistCommand       = new RelayCommand(NewChecklist);
            DeleteNoteCommand         = new RelayCommand <object>(DeleteNote);
            ClearFilterCommand        = new RelayCommand(ClearFilter);
            SynchronizeCommand        = new RelayCommand(Synchronize);
            ShowTransferCodeCommand   = new RelayCommand(ShowTransferCode);
            ShowSettingsCommand       = new RelayCommand(ShowSettings);
            ShowRecycleBinCommand     = new RelayCommand(ShowRecycleBin);
            ShowExportCommand         = new RelayCommand(ShowExport);
            ShowInfoCommand           = new RelayCommand(ShowInfo);
            OpenSafeCommand           = new RelayCommand(OpenSafe);
            CloseSafeCommand          = new RelayCommand(CloseSafe);
            ChangeSafePasswordCommand = new RelayCommand(ChangeSafePassword);

            Modified = false;

            // If a filter was set before e.g. opening a note, set the same filter again.
            if (!string.IsNullOrEmpty(_lastFilter))
            {
                Filter = _lastFilter;
            }
        }
        /// <summary>
        /// Encrypts a message with a user password, and adds a header containing all information
        /// necessary for the decryption (algorithm, nonce, salt, ...).
        /// </summary>
        /// <param name="message">Plain text message to encrypt.</param>
        /// <param name="password">Password to use for encryption, minimum length is 7 characters.</param>
        /// <param name="costType">The cost type to use for encryption.</param>
        /// <param name="randomSource">A cryptographically safe random source.</param>
        /// <param name="encryptorName">The name of an encryption algorithm which shall be used to
        /// do the encryption.</param>
        /// <param name="kdfName">The name of a key derivation function, which can convert the
        /// password to a key.</param>
        /// <returns>A binary array containing the cipher.</returns>
        public byte[] Encrypt(
            byte[] message,
            string password,
            KeyDerivationCostType costType,
            ICryptoRandomSource randomSource,
            string encryptorName,
            string kdfName = Pbkdf2.CryptoKdfName)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            ValidatePassword(password);
            if (randomSource == null)
            {
                throw new ArgumentNullException("randomSource");
            }
            if (string.IsNullOrWhiteSpace(encryptorName))
            {
                encryptorName = BouncyCastleAesGcm.CryptoAlgorithmName;
            }
            if (string.IsNullOrWhiteSpace(kdfName))
            {
                encryptorName = Pbkdf2.CryptoKdfName;
            }
            ISymmetricEncryptionAlgorithm encryptor = new SymmetricEncryptionAlgorithmFactory().CreateAlgorithm(encryptorName);
            IKeyDerivationFunction        kdf       = new KeyDerivationFactory().CreateKdf(kdfName);

            // Prepare header
            CryptoHeader header = new CryptoHeader();

            header.AppName       = _appName;
            header.AlgorithmName = encryptor.Name;
            header.Nonce         = randomSource.GetRandomBytes(encryptor.ExpectedNonceSize);
            header.KdfName       = kdf.Name;
            header.Salt          = randomSource.GetRandomBytes(kdf.ExpectedSaltSizeBytes);
            int cost = kdf.RecommendedCost(costType);

            header.Cost = cost.ToString();

            try
            {
                byte[] key    = kdf.DeriveKeyFromPassword(password, encryptor.ExpectedKeySize, header.Salt, cost);
                byte[] cipher = encryptor.Encrypt(message, key, header.Nonce);
                return(CryptoHeaderPacker.PackHeaderAndCypher(header, cipher));
            }
            catch (Exception ex)
            {
                throw new CryptoException("An unexpected error occured, while encrypting the message.", ex);
            }
        }
Example #7
0
        public void MeasureTime()
        {
            IKeyDerivationFunction kdf          = new Pbkdf2();
            ICryptoRandomSource    randomSource = CommonMocksAndStubs.CryptoRandomService();
            SecureString           password     = CryptoUtils.StringToSecureString("candidate");

            byte[] salt       = randomSource.GetRandomBytes(kdf.ExpectedSaltSizeBytes);
            int    iterations = 10000;

            Stopwatch watch = new Stopwatch();

            watch.Start();
            kdf.DeriveKeyFromPassword(password, 32, salt, iterations);
            watch.Stop();
            Console.WriteLine("Pbkdf2 time for {0} iterations: {1}ms", iterations, watch.ElapsedMilliseconds);
        }
        public NoteRepositoryViewModel(
            INavigationService navigationService,
            ILanguageService languageService,
            ISvgIconService svgIconService,
            IThemeService themeService,
            IBaseUrlService webviewBaseUrl,
            IStoryBoardService storyBoardService,
            IFeedbackService feedbackService,
            ISettingsService settingsService,
            IEnvironmentService environmentService,
            ICryptoRandomSource randomSource,
            IRepositoryStorageService repositoryService)
            : base(navigationService, languageService, svgIconService, themeService, webviewBaseUrl)
        {
            _storyBoardService       = storyBoardService;
            _repositoryService       = repositoryService;
            _feedbackService         = feedbackService;
            _settingsService         = settingsService;
            _environmentService      = environmentService;
            _noteCryptor             = new Cryptor(NoteModel.CryptorPackageName, randomSource);
            _searchableTextConverter = new SearchableHtmlConverter();
            AllNotes      = new List <NoteViewModel>();
            FilteredNotes = new ObservableCollection <NoteViewModel>();

            _repositoryService.LoadRepositoryOrDefault(out NoteRepositoryModel noteRepository);
            Model = noteRepository;

            // Initialize commands and events
            ShowNoteCommand           = new RelayCommand <Guid>(ShowNote);
            NewNoteCommand            = new RelayCommand(NewNote);
            NewChecklistCommand       = new RelayCommand(NewChecklist);
            DeleteNoteCommand         = new RelayCommand <Guid>(DeleteNote);
            ClearFilterCommand        = new RelayCommand(ClearFilter);
            SynchronizeCommand        = new RelayCommand(Synchronize);
            ShowTransferCodeCommand   = new RelayCommand(ShowTransferCode);
            ShowSettingsCommand       = new RelayCommand(ShowSettings);
            ShowRecycleBinCommand     = new RelayCommand(ShowRecycleBin);
            ShowInfoCommand           = new RelayCommand(ShowInfo);
            OpenSafeCommand           = new RelayCommand(OpenSafe);
            CloseSafeCommand          = new RelayCommand(CloseSafe);
            ChangeSafePasswordCommand = new RelayCommand(ChangeSafePassword);

            OnPropertyChanged(nameof(FilterButtonMagnifierVisible));
            OnPropertyChanged(nameof(FilterButtonCancelVisible));
            Modified = false;
        }
Example #9
0
        public ExportViewModel(
            INavigationService navigationService,
            ILanguageService languageService,
            ISvgIconService svgIconService,
            IThemeService themeService,
            IBaseUrlService webviewBaseUrl,
            IFeedbackService feedbackService,
            ICryptoRandomSource randomSource,
            IRepositoryStorageService repositoryService,
            IFolderPickerService folderPickerService)
            : base(navigationService, languageService, svgIconService, themeService, webviewBaseUrl)
        {
            _feedbackService     = feedbackService;
            _repositoryService   = repositoryService;
            _folderPickerService = folderPickerService;
            _noteCryptor         = new Cryptor(NoteModel.CryptorPackageName, randomSource);

            GoBackCommand          = new RelayCommand(GoBack);
            CancelCommand          = new RelayCommand(Cancel);
            OkCommand              = new RelayCommand(Ok);
            ExportUnprotectedNotes = true;
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Cryptor"/> class.
 /// </summary>
 /// <param name="packageName">Sets the <see cref="PackageName"/> property.</param>
 /// <param name="randomSource">A cryptographically safe random generator. It is required to
 /// encrypt data, if the cryptor is exclusively used for decryption, null can be passed.</param>
 public Cryptor(string packageName, ICryptoRandomSource randomSource)
 {
     PackageName   = packageName;
     _randomSource = randomSource;
 }
Example #11
0
 /// <summary>
 /// This function can be used, if an API key must be stored inside the application code,
 /// so it doesn't show up in plain text.
 /// </summary>
 /// <param name="plainText">The text to hide.</param>
 /// <param name="obfuscationKey">Key to use for obfuscation, this key is usually hard coded
 /// in the application.</param>
 /// <param name="randomSource">A cryptographically random source.</param>
 /// <returns>Obfuscated text.</returns>
 public static string Obfuscate(string plainText, SecureString obfuscationKey, ICryptoRandomSource randomSource)
 {
     return(BytesToBase64String(Obfuscate(StringToBytes(plainText), obfuscationKey, randomSource)));
 }
Example #12
0
        /// <summary>
        /// This function can be used, if an API key must be stored inside the application code,
        /// so it doesn't show up in plain text.
        /// </summary>
        /// <param name="plainMessage">The text to hide.</param>
        /// <param name="obfuscationKey">Key to use for obfuscation, this key is usually hard coded
        /// in the application.</param>
        /// <param name="randomSource">A cryptographically random source.</param>
        /// <returns>Obfuscated message.</returns>
        public static byte[] Obfuscate(byte[] plainMessage, SecureString obfuscationKey, ICryptoRandomSource randomSource)
        {
            ICryptor encryptor = new Cryptor(CryptorObfuscationPackageName, randomSource);

            return(encryptor.Encrypt(
                       plainMessage,
                       obfuscationKey,
                       KeyDerivationCostType.Low,
                       "xchacha20_poly1305"));
        }