Example #1
0
        public byte[] Encrypt(string plainText, out byte[] keyBytes, out byte[] ivBytes)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }

            System.IO.MemoryStream memoryStream;

            using (System.Security.Cryptography.AesCryptoServiceProvider csp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                csp.GenerateKey();
                csp.GenerateIV();

                keyBytes = csp.Key;
                ivBytes  = csp.IV;
                //csp.CreateEncryptor

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform cryptoTransformer = csp.CreateEncryptor(csp.Key, csp.IV);

                // Create the streams used for encryption.
                using (memoryStream = new System.IO.MemoryStream())
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransformer, System.Security.Cryptography.CryptoStreamMode.Write))
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cryptoStream))
                        {
                            sw.AutoFlush = true;
                            sw.Write(plainText);
                        }
            }

            return(memoryStream.ToArray());
        }