Example #1
0
        public static EncryptedBundle EncryptString(string plainText, int keyLength, string initVector)
        {
            string passPhrase = GenerateKey(keyLength);

            byte[] initVectorBytes       = Encoding.UTF8.GetBytes(initVector);
            byte[] plainTextBytes        = Encoding.UTF8.GetBytes(plainText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);

            byte[]          keyBytes     = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor    = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            MemoryStream     memoryStream = new MemoryStream();
            CryptoStream     cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] cipherTextBytes = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            EncryptedBundle eb = new EncryptedBundle();

            eb.EncryptedString = Convert.ToBase64String(cipherTextBytes);
            eb.EncryptedKey    = Convert.ToBase64String(Encoding.UTF8.GetBytes(EncryptKey(passPhrase)));
            return(eb);
        }
Example #2
0
        public static string DecryptString(EncryptedBundle eb, string initVector)
        {
            string passPhrase = DecryptKey(Encoding.UTF8.GetString(Convert.FromBase64String(eb.EncryptedKey)));
            string cipherText = eb.EncryptedString;

            byte[] initVectorBytes       = Encoding.UTF8.GetBytes(initVector);
            byte[] cipherTextBytes       = Convert.FromBase64String(cipherText);
            PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);

            byte[]          keyBytes     = password.GetBytes(keysize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform decryptor    = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
            MemoryStream     memoryStream = new MemoryStream(cipherTextBytes);
            CryptoStream     cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

            byte[] plainTextBytes     = new byte[cipherTextBytes.Length];
            int    decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

            memoryStream.Close();
            cryptoStream.Close();
            return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
        }