示例#1
0
        /// <summary>
        ///     Decrypts a string using the <see cref="Aes"/> algorithm.
        /// </summary>
        /// <param name="s">The string to decrypt.</param>
        /// <param name="parameters">The <see cref="AesParameters"/> structure holding the key and initialization vector.</param>
        /// <returns>Returns the decrypted <see cref="string"/>.</returns>
        public string AesDecrypt(string s, AesParameters parameters)
        {
            var transform    = aes.CreateDecryptor(parameters.AesKey, parameters.AesIV);
            var memoryStream = new MemoryStream(Convert.FromBase64String(s));
            var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
            var reader       = new StreamReader(cryptoStream);
            var decrypted    = reader.ReadToEnd();

            reader.Dispose();
            cryptoStream.Dispose();
            memoryStream.Dispose();
            transform.Dispose();

            return(decrypted);
        }
示例#2
0
        /// <summary>
        ///     Encrypts a string using the <see cref="Aes"/> algorithm.
        /// </summary>
        /// <param name="s">The string to encrypt.</param>
        /// <param name="parameters">The <see cref="AesParameters"/> structure holding the key and initialization vector.</param>
        /// <returns>Returns the encrypted <see cref="string"/>.</returns>
        public string AesEncrypt(string s, AesParameters parameters)
        {
            var transform    = aes.CreateEncryptor(parameters.AesKey, parameters.AesIV);
            var memoryStream = new MemoryStream();

            using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write)) {
                using (var writer = new StreamWriter(cryptoStream)) {
                    writer.Write(s);
                }
            }

            var encrypted = Convert.ToBase64String(memoryStream.ToArray());

            memoryStream.Dispose();
            transform.Dispose();

            return(encrypted);
        }