Пример #1
0
        /// <summary>
        /// Encrpyts the unlocked content with the key of the assigned safe.
        /// </summary>
        /// <param name="unlockedContent">Content to encrypt.</param>
        /// <returns>Encrypted content.</returns>
        public string Lock(string unlockedContent)
        {
            string    encryptionAlgorithm = _settingsService.LoadSettingsOrDefault().SelectedEncryptionAlgorithm;
            SafeModel safe = _safes.FindById(Model.SafeId);

            byte[] binaryContent = CryptoUtils.StringToBytes(unlockedContent);
            byte[] lockedContent = _cryptor.Encrypt(binaryContent, safe.Key, encryptionAlgorithm, null);
            return(CryptoUtils.BytesToBase64String(lockedContent));
        }
        /// <inheritdoc/>
        public string Protect(byte[] unprotectedData)
        {
            // Encrypt the data with a new random key
            ISymmetricEncryptionAlgorithm encryptor = new BouncyCastleXChaCha20();

            byte[] randomKey     = _randomService.GetRandomBytes(encryptor.ExpectedKeySize);
            byte[] nonce         = _randomService.GetRandomBytes(encryptor.ExpectedNonceSize);
            byte[] protectedData = encryptor.Encrypt(unprotectedData, randomKey, nonce);

            // Protect the random key with the OS support
            byte[] encryptedRandomKey;
            try
            {
                if (!KeysExistInKeyStore())
                {
                    CreateKeyPairInKeyStore();
                }
                Cipher cipher    = Cipher.GetInstance("RSA/ECB/PKCS1Padding"); // ECB mode is not used by RSA
                IKey   publicKey = GetPublicKeyFromKeyStore();
                cipher.Init(CipherMode.EncryptMode, publicKey);
                encryptedRandomKey = cipher.DoFinal(randomKey);
            }
            catch (Exception)
            {
                // Seems there are exotic devices, which do not support the keystore properly.
                // The least we can do is obfuscating the key.
                encryptedRandomKey = CryptoUtils.Obfuscate(randomKey, CryptoUtils.StringToSecureString(Obcake), _randomService);
            }

            // Combine the encrypted random key and the encrypted data
            StringBuilder result = new StringBuilder();

            result.Append(CryptoUtils.BytesToBase64String(encryptedRandomKey));
            result.Append(Separator);
            result.Append(CryptoUtils.BytesToBase64String(nonce));
            result.Append(Separator);
            result.Append(CryptoUtils.BytesToBase64String(protectedData));
            return(result.ToString());
        }