string ICrypto.Encrypt(string textToEncrypt)
        {
            byte[] encryptedBytes;

            // Prepare an AES object.
            using (Aes aes = Aes.Create())
            {
                aes.Key = this.key;
                aes.IV  = this.initializationVector;

                // Create an encryptor for stream transformation.
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                // Prepare necessary streams and encrypt the given text.
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                        {
                            // Write the given text to the stream.
                            streamWriter.Write(textToEncrypt);
                        }
                        // Get the encrypted data from the memory stream.
                        encryptedBytes = memoryStream.ToArray();
                    }
                }
            }

            // Convert the byte array with the encrypted text into a string.
            ConvertService convertService = new ConvertService();
            string         encryptedText  = convertService.EncodeToString(encryptedBytes);

            return(encryptedText);
        }
示例#2
0
        public void GenerateAesKeyAndInitializationVector()
        {
            byte[] aesKey;
            byte[] aesIV;
            using (Aes aes = Aes.Create())
            {
                aesKey = aes.Key;
                aesIV  = aes.IV;
            }

            ConvertService convertService = new ConvertService();

            string aesKeyEncoded = convertService.EncodeToString(aesKey);
            string aesIVEncoded  = convertService.EncodeToString(aesIV);

            //string secretFile = @"..\..\Resources\Database\Secret.txt";
            string       secretFile = @"..\..\..\Resources\Database\Secret.txt";
            StreamWriter sw         = new StreamWriter(secretFile);

            sw.WriteLine(aesKeyEncoded);
            sw.WriteLine(aesIVEncoded);
            sw.Close();
            sw.Dispose();
        }