Esempio n. 1
1
    protected string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
        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();
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

        StringWriter writer = new StringWriter();
        HttpContext.Current.Server.UrlDecode(plainText, writer);

        return writer.ToString();
    }
Esempio n. 2
0
    public static string Decrypt(string inName, string password)
    {
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, keySalt);

        Rijndael alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);

        using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read))
        using (var fout = new MemoryStream())
        using (var cs = new CryptoStream(fout, alg.CreateDecryptor(), CryptoStreamMode.Write))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            do
            {
                bytesRead = fin.Read(buffer, 0, buffer.Length);
                cs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);

            cs.FlushFinalBlock();
            return Encoding.ASCII.GetString(fout.ToArray());
        }
    }
Esempio n. 3
0
    // Encrypt a string into a string using a password
    //    Uses Encrypt(byte[], byte[], byte[])
    public static string Encrypt(string clearText, string Password)
    {
        // First we need to turn the input string into a byte array.
        byte[] clearBytes =
          System.Text.Encoding.Unicode.GetBytes(clearText);
        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        // Now get the key/IV and do the encryption using the
        // function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] encryptedData = Encrypt(clearBytes,
                 pdb.GetBytes(32), pdb.GetBytes(16));

        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        //It does not work because not all byte values can be
        // represented by characters.
        // We are going to be using Base64 encoding that is designed
        //exactly for what we are trying to do.
        return Convert.ToBase64String(encryptedData);
    }
Esempio n. 4
0
 public static string Encrypt(string clearText, string Password)
 {
     byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     byte[] encryptedData = TEncrypt.Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Convert.ToBase64String(encryptedData);
 }
Esempio n. 5
0
    /// <summary>
    /// Decrypts a previously encrypted string.
    /// </summary>
    /// <param name="inputText">The encrypted string to decrypt.</param>
    /// <returns>A decrypted string.</returns>
    public static string Decrypt(string inputText)
    {
        string decrypted = null;
        try
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        decrypted = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }
        catch (Exception)
        {
        }
        return decrypted;
    }
 protected string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
Esempio n. 7
0
 public static string Decrypt(string cipherText, string Password)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     byte[] decryptedData = TEncrypt.Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
     return Encoding.UTF8.GetString(decryptedData);
 }
Esempio n. 8
0
	/// <summary>
	///		GetBytes with small values
	/// </summary>
	private static bool GetBytesSmall()
	{
		string password = "******";
		byte[] salt		= new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
		int	   c		= 5;

    	PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA1", c);
    	pdb.Salt = salt;

    	byte[] res1 = pdb.GetBytes(1);
    	byte[] res2 = pdb.GetBytes(2);

		return
			res1 != null && res1.Length == 1 &&
			res2 != null && res2.Length == 2;
	}
Esempio n. 9
0
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     try
                     {
                         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                         {
                             byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                             int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                         }
                     }
                     catch
                     {
                         return "ERROR";
                     }
                 }
             }
         }
     }
 }
 /// <summary>
 /// Decrypts a Base64 encoded string previously generated with a specific crypt class, returns a string
 /// </summary>
 /// <param name="cipherText">A base64 encoded string containing encryption information</param>
 /// <param name="passPhrase">The passphrase used to encrypt the inputed text</param>
 /// <returns></returns>
 public string Decrypt(string cipherText, string passPhrase)
 {
     try
         {
             var ciphertextS = DecodeFrom64(cipherText);
             var ciphersplit = Regex.Split(ciphertextS, "-");
             var passsalt = Convert.FromBase64String(ciphersplit[1]);
             var initVectorBytes = Convert.FromBase64String(ciphersplit[0]);
             var cipherTextBytes = Convert.FromBase64String(ciphersplit[2]);
             var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
             var keyBytes = password.GetBytes(256/8);
             var symmetricKey = new RijndaelManaged();
             symmetricKey.Mode = CipherMode.CBC;
             var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
             var memoryStream = new MemoryStream(cipherTextBytes);
             var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
             var plainTextBytes = new byte[cipherTextBytes.Length];
             var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
             memoryStream.Close();
             cryptoStream.Close();
             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
         }
         catch (Exception m)
         {
             return "error";
         }
 }
Esempio n. 11
0
        public static byte[] Decrypt(byte[] cipherText, string passPhrase,bool padding)
        {
            byte[] cipherTextBytes = cipherText;
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    if(!padding)
                        symmetricKey.Padding = PaddingMode.None;
                    using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {

                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                {
                                    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                    cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                    return plainTextBytes;
                                }

                        }
                    }
                }
            }
        }
Esempio n. 12
0
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
Esempio n. 13
0
    /// <summary>
    /// Encrypts any string using the Rijndael algorithm.
    /// </summary>
    /// <param name="inputText">The string to encrypt.</param>
    /// <returns>A Base64 encrypted string.</returns>
    public static string Encrypt(string inputText)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        byte[] plainText = Encoding.Unicode.GetBytes(inputText);
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

        using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainText, 0, plainText.Length);
                    cryptoStream.FlushFinalBlock();
                    return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                }
            }
        }
    }
Esempio n. 14
0
    public static string Crypt(string s_Data, bool b_Encrypt)
    {
        if (!b_Encrypt)
          s_Data = HexToStr(s_Data);
        PasswordDeriveBytes i_Pass = new PasswordDeriveBytes(CryptoPwd(), u8_Salt);

        Rijndael i_Alg = Rijndael.Create();
        i_Alg.Key = i_Pass.GetBytes(32);
        i_Alg.IV = i_Pass.GetBytes(16);

        ICryptoTransform i_Trans = (b_Encrypt) ? i_Alg.CreateEncryptor() : i_Alg.CreateDecryptor();

        MemoryStream i_Mem = new MemoryStream();
        CryptoStream i_Crypt = new CryptoStream(i_Mem, i_Trans, CryptoStreamMode.Write);

        byte[] u8_Data;
        try
        {
          if (b_Encrypt)
        u8_Data = Encoding.Unicode.GetBytes(s_Data);
          else
        u8_Data = Convert.FromBase64String(s_Data);
        }
        catch (Exception)
        {
          return "";
        }

        try
        {
          i_Crypt.Write(u8_Data, 0, u8_Data.Length);
          i_Crypt.Close();
          if (b_Encrypt)
        return StrToHex(Convert.ToBase64String(i_Mem.ToArray()));
          else
        return Encoding.Unicode.GetString(i_Mem.ToArray());
        }
        catch
        {
          return null;
        }
    }
Esempio n. 15
0
 public static void Decrypt(string fileIn, string fileOut, string Password)
 {
     int bytesRead;
     FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
     FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
     PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 73, 118, 97, 110, 32, 77, 101, 100, 118, 101, 100, 101, 118 });
     Rijndael alg = Rijndael.Create();
     alg.Key = pdb.GetBytes(32);
     alg.IV = pdb.GetBytes(16);
     CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);
     int bufferLen = 4096;
     byte[] buffer = new byte[bufferLen];
     do
     {
         bytesRead = fsIn.Read(buffer, 0, bufferLen);
         cs.Write(buffer, 0, bytesRead);
     }
     while (bytesRead != 0);
     cs.Close();
     fsIn.Close();
 }
Esempio n. 16
0
    public static void EncryptFile(string inName, string outName, string password)
    {
        var pdb = new PasswordDeriveBytes(password, keySalt);

        var alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);

        using (var fin = new FileStream(inName, FileMode.Open, FileAccess.Read))
        using (var fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
        using (var cs = new CryptoStream(fout, alg.CreateEncryptor(), CryptoStreamMode.Write))
        {
            var buffer = new byte[4096];
            int bytesRead;

            do
            {
                bytesRead = fin.Read(buffer, 0, buffer.Length);
                cs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead != 0);
        }
    }
Esempio n. 17
0
    /// <summary>
    /// Encrypt a string into a string using a password 
    /// </summary>
    /// <param name="clearText"></param>
    /// <param name="Password"></param>
    /// <returns></returns>
    public static string EncryptString(string clearText)
    {
        string strReturn = null;
        if (clearText == null)
        {
            return strReturn;
        }

        try
        {
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(passCode, saltValueBytes, hashAlgo, pwdIterations);

            byte[] encryptedData = EncryptBytes(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            strReturn = Convert.ToBase64String(encryptedData);
        }
        catch (Exception)
        {
            return strReturn;
        }
        return strReturn;
    }
Esempio n. 18
0
 public string Decrypt(string cipherText, string passPhrase)
 {
     byte[] initVectorBytes = Encoding.ASCII.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);
 }
 //Encrypt
 public string EncryptString(string plainText)
 {
     string passPhrase = "c00ked!n";
     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();
     return Convert.ToBase64String(cipherTextBytes);
 }
 /// <summary>
 /// Encrypts a String with a proivded Passphrase. Returns a base64 encoded string
 /// </summary>
 /// <param name="plainText">Input text to be encrypted</param>
 /// <param name="passPhrase">Password used to encrypt the Plain Text</param>
 /// <returns></returns>
 public string Encrypt(string plainText, string passPhrase)
 {
     var initvector = new byte[16]; //MUST BE 16 Bytes for AES 256
         var passsalt = new byte[16]; //For Salt
         rng.GetBytes(initvector);
         rng.GetBytes(passsalt);
         var initVectorBytes = initvector;
         var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
         var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
         var keyBytes = password.GetBytes(256/8);
         var symmetricKey = new RijndaelManaged();
         symmetricKey.Mode = CipherMode.CBC;
         var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
         var memoryStream = new MemoryStream();
         var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
         cryptoStream.FlushFinalBlock();
         var cipherTextBytes = memoryStream.ToArray();
         memoryStream.Close();
         cryptoStream.Close();
         return
             EncodeTo64(Convert.ToBase64String(initVectorBytes) + "-" + Convert.ToBase64String(passsalt) + "-" +
                        Convert.ToBase64String(cipherTextBytes));
 }
Esempio n. 21
0
        public static byte[] AES_Decrypt(byte[] input, string password)
        {
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            return(AES_Decrypt(input, pdb.GetBytes(32), pdb.GetBytes(16)));
        }
Esempio n. 22
0
        private void btn_DecryptFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Title            = "Select file";
            dialog.InitialDirectory = ".\\";
            dialog.Filter           = "BMP files (*.db)|*.db";
            if (dialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // First we are going to open the file streams
            string fileOut;

            if (dialog.FileName.EndsWith(".db"))
            {
                fileOut = dialog.FileName.Substring(0, dialog.FileName.Length - 4) + ".exe";
            }
            else
            {
                fileOut = dialog.FileName + ".exe";
            }

            FileStream fsIn = new FileStream(dialog.FileName,
                                             FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut,
                                              FileMode.Create, FileAccess.Write);

            // Then we are going to derive a Key and an IV from
            // the Password and create an algorithm
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(FConstants.StringCipherKey,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                           0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            Rijndael alg = Rijndael.Create();

            alg.Key = pdb.GetBytes(32);
            alg.IV  = pdb.GetBytes(16);

            // Now create a crypto stream through which we are going
            // to be pumping data.
            // Our fileOut is going to be receiving the Decrypted bytes.
            CryptoStream cs = new CryptoStream(fsOut,
                                               alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Now will will initialize a buffer and will be
            // processing the input file in chunks.
            // This is done to avoid reading the whole file (which can be
            // huge) into memory.
            int bufferLen = 4096;

            byte[] buffer = new byte[bufferLen];
            int    bytesRead;
            long   bytes = 0;

            do
            {
                // read a chunk of data from the input file
                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // Decrypt it
                cs.Write(buffer, 0, bytesRead);
                richTextBox_EncryptionPlanText.Text = $"Decrypting {bytes += bytesRead} bytes";
            } while (bytesRead != 0);

            // close everything
            cs.Close(); // this will also close the unrelying fsOut stream
            fsIn.Close();
            richTextBox_EncryptionPlanText.Text += "...Done.";
        }
Esempio n. 23
0
        // Decrypt a file into another file using a password

        public static void Decrypt(string fileIn,
                                   string fileOut, string Password)
        {
            // First we are going to open the file streams

            FileStream fsIn = new FileStream(fileIn,
                                             FileMode.Open, FileAccess.Read);
            FileStream fsOut = new FileStream(fileOut,
                                              FileMode.OpenOrCreate, FileAccess.Write);

            // Then we are going to derive a Key and an IV from

            // the Password and create an algorithm

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
                                                              new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
                                                                           0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            Rijndael alg = Rijndael.Create();

            alg.Key = pdb.GetBytes(32);
            alg.IV  = pdb.GetBytes(16);

            // Now create a crypto stream through which we are going

            // to be pumping data.

            // Our fileOut is going to be receiving the Decrypted bytes.

            CryptoStream cs = new CryptoStream(fsOut,
                                               alg.CreateDecryptor(), CryptoStreamMode.Write);

            // Now will will initialize a buffer and will be

            // processing the input file in chunks.

            // This is done to avoid reading the whole file (which can be

            // huge) into memory.

            int bufferLen = 4096;

            byte[] buffer = new byte[bufferLen];
            int    bytesRead;

            do
            {
                // read a chunk of data from the input file

                bytesRead = fsIn.Read(buffer, 0, bufferLen);

                // Decrypt it

                cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);

            // close everything

            cs.Close(); // this will also close the unrelying fsOut stream

            fsIn.Close();
        }
Esempio n. 24
0
        /// <summary>
        /// Use this constructor if you are planning to perform encryption/
        /// decryption with the key derived from the explicitly specified
        /// parameters.
        /// </summary>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived.
        /// The derived password will be used to generate the encryption key
        /// Passphrase can be any string. In this example we assume that the
        /// passphrase is an ASCII string. Passphrase value must be kept in
        /// secret.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long. IV value does not have to be kept
        /// in secret.
        /// </param>
        /// <param name="minSaltLen">
        /// Min size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is less than 4, the default min value will be used (currently 4
        /// bytes).
        /// </param>
        /// <param name="maxSaltLen">
        /// Max size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is negative or greater than 255, the default max value will be
        /// used (currently 8 bytes). If max value is 0 (zero) or if it is smaller
        /// than the specified min value (which can be adjusted to default value),
        /// salt will not be used and plain text value will be encrypted as is.
        /// In this case, salt will not be processed during decryption either.
        /// </param>
        /// <param name="keySize">
        /// Size of symmetric key (in bits): 128, 192, or 256.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hashing algorithm: "MD5" or "SHA1". SHA1 is recommended.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used for password hashing during key generation. This is
        /// not the same as the salt we will use during encryption. This parameter
        /// can be any string.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to hash password. More iterations are
        /// considered more secure but may take longer.
        /// </param>
        public EncryptionClass(string passPhrase,
                               string initVector,
                               int minSaltLen,
                               int maxSaltLen,
                               int keySize,
                               string hashAlgorithm,
                               string saltValue,
                               int passwordIterations)
        {
            // Save min salt length; set it to default if invalid value is passed.
            if (minSaltLen < MIN_ALLOWED_SALT_LEN)
            {
                this.minSaltLen = DEFAULT_MIN_SALT_LEN;
            }
            else
            {
                this.minSaltLen = minSaltLen;
            }

            // Save max salt length; set it to default if invalid value is passed.
            if (maxSaltLen < 0 || maxSaltLen > MAX_ALLOWED_SALT_LEN)
            {
                this.maxSaltLen = DEFAULT_MAX_SALT_LEN;
            }
            else
            {
                this.maxSaltLen = maxSaltLen;
            }

            // Set the size of cryptographic key.
            if (keySize <= 0)
            {
                keySize = DEFAULT_KEY_SIZE;
            }

            // Set the name of algorithm. Make sure it is in UPPER CASE and does
            // not use dashes, e.g. change "sha-1" to "SHA1".
            if (hashAlgorithm == null)
            {
                hashAlgorithm = DEFAULT_HASH_ALGORITHM;
            }
            else
            {
                hashAlgorithm = hashAlgorithm.ToUpper().Replace("-", "");
            }

            // Initialization vector converted to a byte array.
            byte[] initVectorBytes = null;

            // Salt used for password hashing (to generate the key, not during
            // encryption) converted to a byte array.
            byte[] saltValueBytes = null;

            // Get bytes of initialization vector.
            if (initVector == null)
            {
                initVectorBytes = new byte[0];
            }
            else
            {
                initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            }

            // Get bytes of salt (used in hashing).
            if (saltValue == null)
            {
                saltValueBytes = new byte[0];
            }
            else
            {
                saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
            }

            // Generate password, which will be used to derive the key.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Convert key to a byte array adjusting the size from bits to bytes.
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Initialize Rijndael key object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // If we do not have initialization vector, we cannot use the CBC mode.
            // The only alternative is the ECB mode (which is not as good).
            if (initVectorBytes.Length == 0)
            {
                symmetricKey.Mode = CipherMode.ECB;
            }
            else
            {
                symmetricKey.Mode = CipherMode.CBC;
            }

            // Create encryptor and decryptor, which we will use for cryptographic
            // operations.
            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        }
Esempio n. 25
0
        public static string DecryptString(string strToDecrypt, ref bool result, bool WriteErrorsToLog = true)
        {
            try
            {
                //Convert strings defining encryption key characteristics into byte arrays
                byte[] _initVectorBytes = Encoding.UTF8.GetBytes(INIT_VECTOR);
                byte[] _saltValueBytes  = Encoding.UTF8.GetBytes(SALT_VALUE);

                // Create a password, from which the key will be derived
                PasswordDeriveBytes _password = new PasswordDeriveBytes(PASS_PHRASE, _saltValueBytes, HASH_ALGORITHM, PASSWORD_ITERATIONS);

                // Use the password to generate pseudo-random bytes for the encryption key
                byte[] _keyBytes = _password.GetBytes(KEY_SIZE / 8);

                // Create uninitialized Rijndael Object
                RijndaelManaged _rijndaelObject = new RijndaelManaged();

                //check strToEncrypt is not empty
                if ((strToDecrypt == null) || (strToDecrypt == string.Empty))
                {
                    return(strToDecrypt);
                }
                else
                {
                    // Convert strToEncrypt into a byte array.
                    byte[] strToDecryptBytes = Convert.FromBase64String(strToDecrypt);

                    // Set encryption mode to Cipher Block Chaining(CBC)
                    _rijndaelObject.Mode = CipherMode.CBC;

                    // Generate encryptor from the existing key bytes and initializationvector
                    ICryptoTransform decryptor = _rijndaelObject.CreateDecryptor(_keyBytes, _initVectorBytes);

                    // Define memory stream which will be used to hold encrypted data.
                    MemoryStream memoryStream = new MemoryStream(strToDecryptBytes);

                    // Define cryptographic stream
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                    // allocate the buffer long enough to hold ciphertext;
                    byte[] plainTextBytes = new byte[strToDecryptBytes.Length];

                    // Start decrypting
                    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

                    // Close both streams
                    memoryStream.Close();
                    cryptoStream.Close();

                    // Convert decrypted data into a string.
                    string decryptedStr = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

                    // Return decrypted string.
                    result = true;
                    return(decryptedStr);
                }
            }
            catch (Exception ex)
            {
                if (WriteErrorsToLog)
                {
                    Reporter.ToLog(eLogLevel.ERROR, string.Format("Failed to Decrypt the value: '{0}'", strToDecrypt), ex);
                }
                result = false;
                return(string.Empty);
            }
        }
Esempio n. 26
0
        public static void GetBytes_StreamLike_ExtraBytes()
        {
            byte[] first;

            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                // SHA1 default
                Assert.Equal("SHA1", deriveBytes.HashName);

                // Request double of SHA1 hash size
                first = deriveBytes.GetBytes(40);
            }

            byte[] second = new byte[first.Length];

            // Reset
            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                // Make two passes over the hash
                byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2);
                // Since we requested 20 bytes there are no 'extra' bytes left over to cause the "_extraCount" bug
                // in GetBytes(); that issue is tested in GetBytes_StreamLike_Bug_Compat.

                // Request 20 'extra' bytes in one call
                byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length);

                Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length);
                Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length);
            }

            Assert.Equal(first, second);
        }
Esempio n. 27
0
        byte[] Decrypt(byte[] encrypted)
        {
            var keyGenerator = new PasswordDeriveBytes(resourcePassword, Encoding.ASCII.GetBytes(resourceSalt));

            return(DeobUtils.Inflate(DeobUtils.AesDecrypt(encrypted, keyGenerator.GetBytes(32), keyGenerator.GetBytes(16)), false));
        }
Esempio n. 28
0
        public string Encrypt(string plainText, EncryptionInfo info)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(info.InitVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(info.SaltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and
            // salt value. The password will be created using the specified hash
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                info.PassPhrase,
                saltValueBytes,
                info.HashAlgorithm,
                info.Iterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(info.KeySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate encryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         encryptor,
                                                         CryptoStreamMode.Write);

            // Start encrypting.
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] cipherTextBytes = memoryStream.ToArray();

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string cipherText = Convert.ToBase64String(cipherTextBytes);

            // Return encrypted string.
            return(cipherText);
        }
Esempio n. 29
0
        public static void GetBytes_Boundary()
        {
            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                // Boundary case success
                deriveBytes.GetBytes(1000 * 20);

                // Boundary case failure
                Assert.Throws<CryptographicException>(() => deriveBytes.GetBytes(1));
            }
        }
        /// <summary>
        /// This method is used to encrypte file using Rijndael algorithm.
        /// </summary>
        /// <param name="inputFile">non-encrypted file path.</param>
        /// <param name="outputFile">encrypted file saving path.</param>
        /// <param name="RijndaelManagedKey">RijndaelManagedKey.</param>
        public static void EncryptFile(string inputFile, string outputFile, string RijndaelManagedKey)
        {
            if (inputFile == null)
            {
                throw new ArgumentException("inputFile");
            }
            if (outputFile == null)
            {
                throw new ArgumentException("outputFile");
            }
            if (RijndaelManagedKey == null)
            {
                throw new ArgumentException("RijndaelManagedKey");
            }

            PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(RijndaelManagedKey, new byte[13]
            {
                (byte)73,
                (byte)118,
                (byte)97,
                (byte)110,
                (byte)32,
                (byte)77,
                (byte)101,
                (byte)100,
                (byte)118,
                (byte)101,
                (byte)100,
                (byte)101,
                (byte)118
            });
            FileStream      fileStream1     = new FileStream(outputFile, FileMode.Create);
            RijndaelManaged rijndaelManaged = new RijndaelManaged();
            CryptoStream    cryptoStream    = new CryptoStream((Stream)fileStream1, rijndaelManaged.CreateEncryptor(passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16)), CryptoStreamMode.Write);
            FileStream      fileStream2     = new FileStream(inputFile, FileMode.Open);
            int             num;

            while ((num = fileStream2.ReadByte()) != -1)
            {
                cryptoStream.WriteByte((byte)num);
            }
            fileStream2.Close();
            cryptoStream.Close();
            fileStream1.Close();
        }
        public void TooShort()
        {
            PasswordDeriveBytes pd = new PasswordDeriveBytes("password", null, "SHA1", 1);

            byte[] key = pd.GetBytes(0);
        }
Esempio n. 32
0
        public static string Decrypt(string encodedText, string decryptKey = null)
        {
            if (string.IsNullOrEmpty(decryptKey))
            {
                decryptKey = ConfigurationManager.AppSettings["EncryptDecryptKey"];
            }
            if (encodedText != null)
            {
                string passPhrase         = "Pas5pr@se";
                int    passwordIterations = 2;
                string hashAlgorithm      = "SHA1";
                string initVector         = "@1B2c3D4e5F6g7H8";
                int    keySize            = 128;

                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes  = Encoding.ASCII.GetBytes(decryptKey);


                string stringToDecrypt = encodedText.Replace(" ", "+");
                byte[] cipherTextBytes = Convert.FromBase64String(stringToDecrypt);

                PasswordDeriveBytes password = new PasswordDeriveBytes(
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations);

                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();

                string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                           0,
                                                           decryptedByteCount);


                return(plainText);
            }
            return(decryptKey);
        }
Esempio n. 33
0
    public static string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings into byte arrays.
        // Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // First, we must create a password, from which the key will be derived.
        // This password will be generated from the specified passphrase and
        // salt value. The password will be created using the specified hash
        // algorithm. Password creation can be done in several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate encryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes,
                                                         initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();

        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                     encryptor,
                                                     CryptoStreamMode.Write);
        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);

        // Return encrypted string.
        return cipherText;
    }
        /// <summary>
        /// This method is used to decrypte file encrypted using Rijndael algorithm.
        /// </summary>
        /// <param name="inputFile">encrypted file path</param>
        /// <param name="fileStream">destination file FileStream object. </param>
        /// <param name="RijndaelManagedKey">RijndaelManagedKey.</param>
        public static void DecryptFile(string inputFile, ref FileStream fileStream, string RijndaelManagedKey)
        {
            if (inputFile == null)
            {
                throw new ArgumentException("inputFile");
            }
            if (RijndaelManagedKey == null)
            {
                throw new ArgumentException("RijndaelManagedKey");
            }

            PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(RijndaelManagedKey, new byte[13]
            {
                (byte)73,
                (byte)118,
                (byte)97,
                (byte)110,
                (byte)32,
                (byte)77,
                (byte)101,
                (byte)100,
                (byte)118,
                (byte)101,
                (byte)100,
                (byte)101,
                (byte)118
            });
            CryptoStream cryptoStream = new CryptoStream((Stream) new FileStream(inputFile, FileMode.Open), new RijndaelManaged().CreateDecryptor(passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16)), CryptoStreamMode.Read);
            int          num;

            while ((num = cryptoStream.ReadByte()) != -1)
            {
                fileStream.WriteByte((byte)num);
            }
            fileStream.Close();
            cryptoStream.Close();
        }
Esempio n. 35
0
        public static string Decrypt(string cipherText, string password, string salt = "Kosher",
                                     string hashAlgorithm   = "SHA1",
                                     int passwordIterations = 2,
                                     int keySize            = 256)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(password))
            {
                return(null);
            }

            byte[] initialVectorBytes;
            byte[] saltValueBytes;
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // Extract metadata from file
            AESMetadata metadata = new AESMetadata();

            if (!metadata.GetMetadata(cipherTextBytes))
            {
                // Metadata parsing error
                DialogResult result = MessageBox.Show("Unable to parse file metadata.\nAttempt to open anyway?\n(May result in a \'Incorrect Key\' error if the salt is wrong.)",
                                                      "Missing or Corrupted Metadata", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                if (result == DialogResult.Yes)
                {
                    // Default initialization vector from builds v1.1.2 and older
                    const string default_IV = "16CHARSLONG12345";

                    initialVectorBytes = Encoding.ASCII.GetBytes(default_IV);
                    saltValueBytes     = Encoding.ASCII.GetBytes(salt);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                saltValueBytes     = metadata.Salt;
                initialVectorBytes = metadata.InitialVector;
                metadata.DeleteMetadataFromBuffer(ref cipherTextBytes);
            }

            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
                                                      (password, saltValueBytes, hashAlgorithm, passwordIterations);

            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);

            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;

            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int    byteCount      = 0;

            using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
            {
                using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor
                                                        (keyBytes, initialVectorBytes))
                {
                    using (CryptoStream cryptoStream
                               = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }

                symmetricKey.Dispose();
            }

            derivedPassword.Dispose();
            return(Encoding.UTF8.GetString(plainTextBytes, 0, byteCount));
        }
Esempio n. 36
0
    // Encrypt a file into another file using a password
    public static void Encrypt(string fileIn, string fileOut, string Password)
    {
        // First we are going to open the file streams

        FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);

        FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);

        // Then we are going to derive a Key and an IV from the Password and create an algorithm

        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,

                    new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

        Rijndael alg = Rijndael.Create();

        alg.Key = pdb.GetBytes(32);

        alg.IV = pdb.GetBytes(16);

        // Now create a crypto stream through which we are going to be pumping data.

        // Our fileOut is going to be receiving the encrypted bytes.

        CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write);

        // Now will will initialize a buffer and will be processing the input file in chunks.

        // This is done to avoid reading the whole file (which can be huge) into memory.

        int bufferLen = 4096;

        byte[] buffer = new byte[bufferLen];

        int bytesRead;

        do
        {

            // read a chunk of data from the input file

            bytesRead = fsIn.Read(buffer, 0, bufferLen);

            // encrypt it

            cs.Write(buffer, 0, bytesRead);

        } while (bytesRead != 0);

        // close everything

        cs.Close(); // this will also close the unrelying fsOut stream

        fsIn.Close();
    }
Esempio n. 37
0
        public static string Encrypt(string plainText, string password,
                                     string salt            = null, string hashAlgorithm = "SHA1",
                                     int passwordIterations = 2, int keySize             = 256)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(password))
            {
                return(null);
            }

            byte[] plainTextBytes;
            byte[] saltValueBytes;

            // In case user wants a random salt or salt is null/empty for some other reason
            if (string.IsNullOrEmpty(salt))
            {
                saltValueBytes = new byte[64]; // Nice and long
                saltValueBytes = GenerateSecureNonZeroByteArray(saltValueBytes.Length);
            }
            else
            {
                saltValueBytes = Encoding.ASCII.GetBytes(salt);
            }

            plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes
                                                      (password, saltValueBytes, hashAlgorithm, passwordIterations);

            // Null password; adds *some* memory dump protection
            password = null;

            byte[]          keyBytes     = derivedPassword.GetBytes(keySize / 8);
            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;

            // Generate IV
            symmetricKey.IV = GenerateSecureNonZeroByteArray(symmetricKey.IV.Length);

            byte[] cipherTextBytes = null;

            using (MemoryStream memStream = new MemoryStream())
            {
                AESMetadata.WriteMetadata(memStream, symmetricKey.IV, saltValueBytes);

                using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor
                                                        (keyBytes, symmetricKey.IV))
                {
                    using (CryptoStream cryptoStream = new CryptoStream
                                                           (memStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memStream.ToArray();
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }

            symmetricKey.Dispose();
            derivedPassword.Dispose();
            return(Convert.ToBase64String(cipherTextBytes));
        }
Esempio n. 38
0
    /// <summary>
    /// Use this constructor if you are planning to perform encryption/
    /// decryption with the key derived from the explicitly specified
    /// parameters.
    /// </summary>
    /// <param name="passPhrase">
    /// Passphrase from which a pseudo-random password will be derived.
    /// The derived password will be used to generate the encryption key
    /// Passphrase can be any string. In this example we assume that the
    /// passphrase is an ASCII string. Passphrase value must be kept in
    /// secret.
    /// </param>
    /// <param name="initVector">
    /// Initialization vector (IV). This value is required to encrypt the
    /// first block of plaintext data. For RijndaelManaged class IV must be
    /// exactly 16 ASCII characters long. IV value does not have to be kept
    /// in secret.
    /// </param>
    /// <param name="minSaltLen">
    /// Min size (in bytes) of randomly generated salt which will be added at
    /// the beginning of plain text before encryption is performed. When this
    /// value is less than 4, the default min value will be used (currently 4
    /// bytes).
    /// </param>
    /// <param name="maxSaltLen">
    /// Max size (in bytes) of randomly generated salt which will be added at
    /// the beginning of plain text before encryption is performed. When this
    /// value is negative or greater than 255, the default max value will be
    /// used (currently 8 bytes). If max value is 0 (zero) or if it is smaller
    /// than the specified min value (which can be adjusted to default value),
    /// salt will not be used and plain text value will be encrypted as is.
    /// In this case, salt will not be processed during decryption either.
    /// </param>
    /// <param name="keySize">
    /// Size of symmetric key (in bits): 128, 192, or 256.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Hashing algorithm: "MD5" or "SHA1". SHA1 is recommended.
    /// </param>
    /// <param name="saltValue">
    /// Salt value used for password hashing during key generation. This is
    /// not the same as the salt we will use during encryption. This parameter
    /// can be any string.
    /// </param>
    /// <param name="passwordIterations">
    /// Number of iterations used to hash password. More iterations are
    /// considered more secure but may take longer.
    /// </param>
    public RijndaelEnhanced(string passPhrase,
                            string initVector,
                            int minSaltLen,
                            int maxSaltLen,
                            int keySize,
                            string hashAlgorithm,
                            string saltValue,
                            int passwordIterations)
    {
        // Save min salt length; set it to default if invalid value is passed.
        if (minSaltLen < MIN_ALLOWED_SALT_LEN)
            this.minSaltLen = DEFAULT_MIN_SALT_LEN;
        else
            this.minSaltLen = minSaltLen;

        // Save max salt length; set it to default if invalid value is passed.
        if (maxSaltLen < 0 || maxSaltLen > MAX_ALLOWED_SALT_LEN)
            this.maxSaltLen = DEFAULT_MAX_SALT_LEN;
        else
            this.maxSaltLen = maxSaltLen;

        // Set the size of cryptographic key.
        if (keySize <= 0)
            keySize = DEFAULT_KEY_SIZE;

        // Set the name of algorithm. Make sure it is in UPPER CASE and does
        // not use dashes, e.g. change "sha-1" to "SHA1".
        if (hashAlgorithm == null)
            hashAlgorithm = DEFAULT_HASH_ALGORITHM;
        else
            hashAlgorithm = hashAlgorithm.ToUpper().Replace("-", "");

        // Initialization vector converted to a byte array.
        byte[] initVectorBytes = null;

        // Salt used for password hashing (to generate the key, not during
        // encryption) converted to a byte array.
        byte[] saltValueBytes = null;

        // Get bytes of initialization vector.
        if (initVector == null)
            initVectorBytes = new byte[0];
        else
            initVectorBytes = Encoding.ASCII.GetBytes(initVector);

        // Get bytes of salt (used in hashing).
        if (saltValue == null)
            saltValueBytes = new byte[0];
        else
            saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Generate password, which will be used to derive the key.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                   passPhrase,
                                                   saltValueBytes,
                                                   hashAlgorithm,
                                                   passwordIterations);

        // Convert key to a byte array adjusting the size from bits to bytes.
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Initialize Rijndael key object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // If we do not have initialization vector, we cannot use the CBC mode.
        // The only alternative is the ECB mode (which is not as good).
        if (initVectorBytes.Length == 0)
            symmetricKey.Mode = CipherMode.ECB;
        else
            symmetricKey.Mode = CipherMode.CBC;

        // Create encryptor and decryptor, which we will use for cryptographic
        // operations.
        encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
    }
Esempio n. 39
0
        public static void GetBytes_StreamLike_Bug_Compat()
        {
            byte[] first;

            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                Assert.Equal("SHA1", deriveBytes.HashName);

                // Request 20 bytes (SHA1 hash size) plus 12 extra bytes
                first = deriveBytes.GetBytes(32);
            }

            byte[] second = new byte[first.Length];

            // Reset
            using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
            {
                // Ask for half now (16 bytes)
                byte[] firstHalf = deriveBytes.GetBytes(first.Length / 2);

                // Ask for the other half now (16 bytes)
                byte[] lastHalf = deriveBytes.GetBytes(first.Length - firstHalf.Length);

                // lastHalf should contain the last 4 bytes from the SHA1 hash plus 12 extra bytes
                // but due to the _extraCount bug it doesn't.

                // Merge the two buffers into the second array
                Buffer.BlockCopy(firstHalf, 0, second, 0, firstHalf.Length);
                Buffer.BlockCopy(lastHalf, 0, second, firstHalf.Length, lastHalf.Length);
            }

            // Fails due to _extraCount bug (the bug is fixed in Rfc2898DeriveBytes)
            Assert.NotEqual(first, second);

            // However, the first 16 bytes will be equal because the _extraCount bug does
            // not affect the first call, only the subsequent GetBytes() call.
            byte[] first_firstHalf = new byte[first.Length / 2];
            byte[] second_firstHalf = new byte[first.Length / 2];
            Buffer.BlockCopy(first, 0, first_firstHalf, 0, first_firstHalf.Length);
            Buffer.BlockCopy(second, 0, second_firstHalf, 0, second_firstHalf.Length);
            Assert.Equal(first_firstHalf, second_firstHalf);
        }
Esempio n. 40
0
        public string Decrypt(string cipherText, EncryptionInfo info)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(info.InitVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(info.SaltValue);

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                info.PassPhrase,
                saltValueBytes,
                info.HashAlgorithm,
                info.Iterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(info.KeySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         decryptor,
                                                         CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data into a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return(plainText);
        }
Esempio n. 41
0
        private static void TestKnownValue_GetBytes(HashAlgorithmName hashName, string password, byte[] salt, int iterationCount, byte[] expected)
        {
            byte[] output;

            using (var deriveBytes = new PasswordDeriveBytes(password, salt, hashName.Name, iterationCount))
            {
                output = deriveBytes.GetBytes(expected.Length);
            }

            Assert.Equal(expected, output);
        }
Esempio n. 42
0
        public static string Decrypt(

            string cipherText,

            string passPhrase,

            string saltValue,

            string hashAlgorithm,

            int passwordIterations,

            string initVector,

            int keySize)
        {
            try
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);

                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

                PasswordDeriveBytes password = new PasswordDeriveBytes(
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations);

                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();

                string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                           0,
                                                           decryptedByteCount);
                return(plainText);
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
 public string EncryptionMethod(string role)
 {
     RijndaelManaged RijndaelCipher = new RijndaelManaged();
     string encryptionkey = "delicate";
     byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(role);
     byte[] Salt = System.Text.Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());
     PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(encryptionkey, Salt);
     ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
     cryptoStream.Write(PlainText, 0, PlainText.Length);
     cryptoStream.FlushFinalBlock();
     byte[] CipherBytes = memoryStream.ToArray();
     memoryStream.Close();
     cryptoStream.Close();
     string EncryptedData = Convert.ToBase64String(CipherBytes);
     return EncryptedData;
 }
Esempio n. 44
0
        public static string EncryptString(string strToEncrypt, ref bool result)
        {
            try
            {
                //Convert strings defining encryption key characteristics into byte arrays
                byte[] _initVectorBytes = Encoding.UTF8.GetBytes(INIT_VECTOR);
                byte[] _saltValueBytes  = Encoding.UTF8.GetBytes(SALT_VALUE);

                // Create a password, from which the key will be derived
                PasswordDeriveBytes _password =
                    new PasswordDeriveBytes(PASS_PHRASE, _saltValueBytes, HASH_ALGORITHM, PASSWORD_ITERATIONS);

                // Use the password to generate pseudo-random bytes for the encryption key
                byte[] _keyBytes = _password.GetBytes(KEY_SIZE / 8);

                // Create uninitialized Rijndael Object
                RijndaelManaged _rijndaelObject = new RijndaelManaged();

                //check strToEncrypt is not empty
                if ((strToEncrypt == null) || (strToEncrypt == string.Empty))
                {
                    return(strToEncrypt);
                }
                else
                {
                    // Convert strToEncrypt into a byte array.
                    byte[] strToEncryptBytes = Encoding.UTF8.GetBytes(strToEncrypt);

                    // Set Rijndael Object mode to Cipher Block Chaining(CBC)
                    _rijndaelObject.Mode = CipherMode.CBC;

                    // Generate encryptor from the existing key bytes and initializationvector
                    ICryptoTransform encryptor = _rijndaelObject.CreateEncryptor(_keyBytes, _initVectorBytes);

                    // Define memory stream which will be used to hold encrypted data.
                    MemoryStream memoryStream = new MemoryStream();

                    // Define cryptographic stream
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

                    // Start encrypting
                    cryptoStream.Write(strToEncryptBytes, 0, strToEncryptBytes.Length);

                    // Finish encrypting
                    cryptoStream.FlushFinalBlock();

                    // Convert our encrypted data from a memory stream into a byte array
                    byte[] encryptedStrBytes = memoryStream.ToArray();

                    // Close both streams
                    memoryStream.Close();
                    cryptoStream.Close();

                    // Convert encrypted data into a base64-encoded string.
                    string encryptedStr = Convert.ToBase64String(encryptedStrBytes);

                    // Return encrypted string
                    result = true;
                    return(encryptedStr);
                }
            }
            catch (Exception ex)
            {
                Reporter.ToLog(eLogLevel.ERROR, string.Format("Failed to Encrypt the value: '{0}'", strToEncrypt), ex);
                result = false;
                return(string.Empty);
            }
        }
Esempio n. 45
0
    public static string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        // First, we must create a password, from which the key will be
        // derived. This password will be generated from the specified
        // passphrase and salt value. The password will be created using
        // the specified hash algorithm. Password creation can be done in
        // several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate decryptor from the existing key bytes and initialization
        // vector. Key size will be defined based on the number of the key
        // bytes.
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                         keyBytes,
                                                         initVectorBytes);

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

        // Define cryptographic stream (always use Read mode for encryption).
        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                      decryptor,
                                                      CryptoStreamMode.Read);

        // Since at this point we don't know what the size of decrypted data
        // will be, allocate the buffer long enough to hold ciphertext;
        // plaintext is never longer than ciphertext.
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        // Start decrypting.
        int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                   0,
                                                   plainTextBytes.Length);

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert decrypted data into a string.
        // Let us assume that the original plaintext string was UTF8-encoded.
        string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                   0,
                                                   decryptedByteCount);

        // Return decrypted string.
        return plainText;
    }
Esempio n. 46
0
        public static string Encrypt(string InputText)
        {
            string Password = CryptoKey;

            if (!EncryptionEnabled)
            {
                return(InputText);
            }

            if (InputText == null)
            {
                return(InputText);
            }

            // We are now going to create an instance of the
            // Rihndael class.
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            // First we need to turn the input strings into a byte array.
            byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(InputText);


            // We are using salt to make it harder to guess our key
            // using a dictionary attack.
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());


            // The (Secret Key) will be generated from the specified
            // password and salt.
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);


            // Create a encryptor from the existing SecretKey bytes.
            // We use 32 bytes for the secret key
            // (the default Rijndael key length is 256 bit = 32 bytes) and
            // then 16 bytes for the IV (initialization vector),
            // (the default Rijndael IV length is 128 bit = 16 bytes)
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));


            // Create a MemoryStream that is going to hold the encrypted bytes
            MemoryStream memoryStream = new MemoryStream();


            // Create a CryptoStream through which we are going to be processing our data.
            // CryptoStreamMode.Write means that we are going to be writing data
            // to the stream and the output will be written in the MemoryStream
            // we have provided. (always use write mode for encryption)
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

            // Start the encryption process.
            cryptoStream.Write(PlainText, 0, PlainText.Length);


            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memoryStream into a byte array.
            byte[] CipherBytes = memoryStream.ToArray();



            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();



            // Convert encrypted data into a base64-encoded string.
            // A common mistake would be to use an Encoding class for that.
            // It does not work, because not all byte values can be
            // represented by characters. We are going to be using Base64 encoding
            // That is designed exactly for what we are trying to do.
            string EncryptedData = Convert.ToBase64String(CipherBytes);



            // Return encrypted string.
            return(EncryptedData);
        }
Esempio n. 47
0
    public static byte[] Encrypt(byte[] clearData, string Password)
    {
        // We need to turn the password into Key and IV. 
        // We are using salt to make it harder to guess our key
        // using a dictionary attack - 
        // trying to guess a password by enumerating all possible words. 
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

        // Now get the key/IV and do the encryption using the function
        // that accepts byte arrays. 
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key 
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV. 
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael. 
        // If you are using DES/TripleDES/RC2 the block size is 8
        // bytes and so should be the IV size. 
        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes. 
        return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));

    }
Esempio n. 48
0
        public static string Encrypt(string textValue, string encryptKey = null)
        {
            if (string.IsNullOrEmpty(encryptKey))
            {
                encryptKey = ConfigurationManager.AppSettings["EncryptDecryptKey"];
            }
            if (textValue != null)
            {
                string passPhrase         = "Pas5pr@se";
                int    passwordIterations = 2;
                string hashAlgorithm      = "SHA1";
                string initVector         = "@1B2c3D4e5F6g7H8";
                int    keySize            = 128;

                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes  = Encoding.ASCII.GetBytes(encryptKey);

                byte[] plainTextBytes = Encoding.UTF8.GetBytes(textValue);

                PasswordDeriveBytes password = new PasswordDeriveBytes(
                    passPhrase,
                    saltValueBytes,
                    hashAlgorithm,
                    passwordIterations);

                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();


                string cipherText = Convert.ToBase64String(cipherTextBytes);


                return(cipherText);
            }
            return(textValue);
        }