Пример #1
0
        /// <summary>
        /// Decrypts an encrypted object to get the original text.
        /// </summary>
        /// <param name="cryptoItem">The encrypted object.</param>
        /// <returns>The decrypted text.</returns>
        public string Decrypt(ICryptoItem cryptoItem)
        {
            Ensure.Parameter.IsNotNull(cryptoItem, nameof(cryptoItem));

            string decryptedText;

            using (MemoryStream ms = new MemoryStream(cryptoItem.Value))
            {
                using (CryptoStream cs = GetCryptoStream(ms, CryptoStreamMode.Read, cryptoItem))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        decryptedText = sr.ReadToEnd();
                    }
                }
            }

            return(decryptedText);
        }
Пример #2
0
        /// <summary>
        /// Gets a crypto stream.
        /// </summary>
        /// <param name="memoryStream">The stream to encrypt.</param>
        /// <param name="mode">If the crypto stream is for reading or writing.</param>
        /// <param name="cryptoItem">The encrypted item to read.</param>
        /// <returns>The crypto stream.</returns>
        private CryptoStream GetCryptoStream(MemoryStream memoryStream, CryptoStreamMode mode, ICryptoItem cryptoItem = null)
        {
            var cryptoProvider = new AesCryptoServiceProvider();

            byte[] key = cryptoItem?.Key ?? _cryptoServiceProvider.Key;
            byte[] iv  = cryptoItem?.InitializationVector ?? _cryptoServiceProvider.IV;

            var transform = mode == CryptoStreamMode.Read
                                ? cryptoProvider.CreateDecryptor(key, iv)
                                : cryptoProvider.CreateEncryptor(key, iv);

            return(new CryptoStream(memoryStream, transform, mode));
        }