Exemple #1
0
        /// <summary>
        /// Decrypts a byte array with a password
        /// </summary>
        /// <param name="data">Data to decrypt</param>
        /// <param name="password">Password to use</param>
        /// <param name="paddingMode">Padding mode to use</param>
        /// <returns>Decrypted byte array</returns>
        /// <exception cref="System.ArgumentNullException">
        /// data
        /// or
        /// password
        /// </exception>
        /// <exception cref="ArgumentNullException"></exception>
        public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt"));
            var rm  = new RijndaelManaged {
                Padding = paddingMode
            };
            ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16));

            pdb.Dispose();
            using (var msDecrypt = new MemoryStream(data))
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    // Decrypted bytes will always be less then encrypted bytes, so length of encrypted data will be big enough for buffer.
                    byte[] fromEncrypt = new byte[data.Length];
                    // Read as many bytes as possible.
                    int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
                    if (read < fromEncrypt.Length)
                    {
                        // Return a byte array of proper size.
                        byte[] clearBytes = new byte[read];
                        Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read);
                        return(clearBytes);
                    }
                    return(fromEncrypt);
                }
        }
Exemple #2
0
        /// <summary>
        /// Encrypts a byte array with a password
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <param name="password">Password to use</param>
        /// <param name="paddingMode">Padding mode to use</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="System.ArgumentNullException">
        /// data
        /// or
        /// password
        /// </exception>
        /// <exception cref="ArgumentNullException"></exception>
        public static byte[] EncryptData(byte[] data, string password, PaddingMode paddingMode)
        {
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("data");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt"));
            var rm  = new RijndaelManaged {
                Padding = paddingMode
            };
            ICryptoTransform encryptor = rm.CreateEncryptor(pdb.GetBytes(16), pdb.GetBytes(16));

            pdb.Dispose();
            using (var msEncrypt = new MemoryStream())
                using (var encStream = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    encStream.Write(data, 0, data.Length);
                    encStream.FlushFinalBlock();
                    return(msEncrypt.ToArray());
                }
        }
        public void EncryptFile(PasswordSheet sheet)
        {
            FileStream          stream         = null;
            PasswordDeriveBytes secretKey      = null;
            RijndaelManaged     rijndaelCipher = null;
            ICryptoTransform    encryptor      = null;
            CryptoStream        cryptoStream   = null;

            try
            {
                stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Write);
                stream.SetLength(0);

                secretKey = GetPasswordBytes();

                rijndaelCipher = new RijndaelManaged();
                encryptor      = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));

                // Defines a stream that links data streams to cryptographic transformations
                cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);

                byte[] data = null;
                using (var sheetStream = new MemoryStream())
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(PasswordSheet));
                    serializer.Serialize(sheetStream, sheet);

                    data = sheetStream.GetBuffer();
                }


                cryptoStream.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
            finally
            {
                if (secretKey != null)
                {
                    secretKey.Dispose();
                }

                if (rijndaelCipher != null)
                {
                    rijndaelCipher.Dispose();
                }

                if (cryptoStream != null)
                {
                    cryptoStream.Dispose();
                }
            }
        }
Exemple #4
0
        public PasswordSheet DecryptFile()
        {
            PasswordSheet       decryptedData  = null;
            FileStream          stream         = null;
            PasswordDeriveBytes secretKey      = null;
            RijndaelManaged     rijndaelCipher = null;
            ICryptoTransform    decryptor      = null;
            CryptoStream        cryptoStream   = null;

            try
            {
                rijndaelCipher = new RijndaelManaged();

                // Making of the key for decryption
                secretKey = GetPasswordBytes();

                // Creates a symmetric Rijndael decryptor object.
                decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                stream    = new FileStream(_fileName, FileMode.Open, FileAccess.Read);

                // Defines the cryptographics stream for decryption.THe stream contains decrpted data
                cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);

                XmlSerializer serializer = new XmlSerializer(typeof(PasswordSheet));
                decryptedData = (PasswordSheet)serializer.Deserialize(cryptoStream);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }

                if (secretKey != null)
                {
                    secretKey.Dispose();
                }

                if (rijndaelCipher != null)
                {
                    rijndaelCipher.Dispose();
                }

                if (cryptoStream != null)
                {
                    cryptoStream.Dispose();
                }
            }

            return(decryptedData);
        }
        /// <summary>
        ///  static declerations for this scope only
        /// </summary>
        /// <param name="textToBeDecrypted">this is decrypted text</param>
        /// <returns>it return th string</returns>
        public static string Decrypt(string textToBeDecrypted)
        {
            RijndaelManaged     rijndaelCipher = null;
            const string        Password       = "******";
            string              decryptedData;
            MemoryStream        memoryStream = null;
            PasswordDeriveBytes secretKey    = null;

            try
            {
                byte[] encryptedData = Convert.FromBase64String(textToBeDecrypted);
                rijndaelCipher = new RijndaelManaged();
                byte[] salt = Encoding.ASCII.GetBytes(Password.Length.ToString(CultureInfo.InvariantCulture));
                ////Making of the key for decryption
                secretKey = new PasswordDeriveBytes(Password, salt);
                ////Creates a symmetric Rijndael decryptor object.
                ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));

                memoryStream = new MemoryStream(encryptedData);
                ////Defines the cryptographics stream for decryption.THe stream contains decrpted data
                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

                byte[] plainText      = new byte[encryptedData.Length];
                int    decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);

                ////Converting to string
                decryptedData = Encoding.UTF8.GetString(plainText, 0, decryptedCount);
                return(decryptedData);
            }
            catch
            {
                decryptedData = textToBeDecrypted;
                throw;
            }
            finally
            {
                // cryptoStream.Close();
                if (rijndaelCipher != null)
                {
                    rijndaelCipher.Dispose();
                }

                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }

                if (secretKey != null)
                {
                    secretKey.Dispose();
                }
            }
        }
        void SetupAlgorithm()
        {
            CreateAlgorithm();
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(this._key.GetBytes(), this._key.GetBytes());
            this.Algorithm.Key = pdb.GetBytes(this.Algorithm.KeySize / 8);
            pdb.Dispose();
            pdb = null;

            pdb = new PasswordDeriveBytes(this._iv.GetBytes(), this._iv.GetBytes());
            this.Algorithm.IV = pdb.GetBytes(this.Algorithm.BlockSize / 8);
            pdb.Dispose();
        }
        /// <summary>
        /// Encryption method for the password
        /// </summary>
        /// <param name="textToBeEncrypted">text to encrypt</param>
        /// <returns>it return the string value</returns>
        public static string Encrypt(string textToBeEncrypted)
        {
            RijndaelManaged     rijndaelCipher = null;
            PasswordDeriveBytes secretKey      = null;

            try
            {
                rijndaelCipher = new RijndaelManaged();
                const string Password  = "******";
                byte[]       plainText = System.Text.Encoding.UTF8.GetBytes(textToBeEncrypted);
                byte[]       salt      = Encoding.ASCII.GetBytes(Password.Length.ToString(CultureInfo.InvariantCulture));
                secretKey = new PasswordDeriveBytes(Password, salt);
                ////Creates a symmetric encryptor object.
                ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    ////Defines a stream that links data streams to cryptographic transformations
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
                    cryptoStream.Write(plainText, 0, plainText.Length);
                    ////Writes the final state and clears the buffer
                    cryptoStream.FlushFinalBlock();
                    byte[] cipherBytes = memoryStream.ToArray();

                    ////memoryStream.Close();
                    // cryptoStream.Close();
                    string encryptedData = Convert.ToBase64String(cipherBytes);

                    return(encryptedData);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (rijndaelCipher != null)
                {
                    rijndaelCipher.Dispose();
                }

                if (secretKey != null)
                {
                    secretKey.Dispose();
                }
            }
        }
Exemple #8
0
        public static byte[] Decrypt(byte[] input, byte[] Salt, string givenpassword = null)
        {
            PasswordDeriveBytes pdb =
                new PasswordDeriveBytes((givenpassword == null) ? password : givenpassword, // Change this
                                        Salt);                                              // Change this
            MemoryStream ms  = new MemoryStream();
            Aes          aes = new AesManaged();

            aes.Key     = pdb.GetBytes(aes.KeySize / 8);
            aes.IV      = pdb.GetBytes(aes.BlockSize / 8);
            aes.Padding = PaddingMode.Zeros;
            CryptoStream cs = new CryptoStream(ms,
                                               aes.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(input, 0, input.Length);
            cs.Close();
            pdb.Dispose();
            return(ms.ToArray());
        }
Exemple #9
0
        public static byte[] DecryptWithString(byte[] encryptedData, string key)
        {
            var pdb = new PasswordDeriveBytes(key, Encoding.ASCII.GetBytes(key));
            var ms  = new MemoryStream();

            var aes = new AesManaged();

            aes.Key = pdb.GetBytes(aes.KeySize / 8);
            aes.IV  = pdb.GetBytes(aes.BlockSize / 8);

            var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);

            cs.Write(encryptedData, 0, encryptedData.Length);
            cs.Close();

            aes.Dispose();
            pdb.Dispose();

            return(ms.ToArray());
        }
Exemple #10
0
        public static ConnectionState Disconnect() //zakończenie połączenia
        {
            if (stream == null || tcpClient == null)
            {
                return(ConnectionState.DISCONECT_NOT_SUCCESS);
            }
            try
            {
                if (widgetService != null)
                {
                    widgetService.RemoveWidget();
                }

                if (!sendingPing)
                {
                    pingServer = false;
                }

                stream.Close();
                tcpClient.Close();

                stream.Dispose();
                tcpClient.Dispose();

                if (pass != null)
                {
                    pass.Dispose();
                }

                connected = false;
                readData  = false;

                return(ConnectionState.DISCONECT_SUCCESS);
            }
            catch (Exception error)
            {
                exceptionText = error.ToString();
                connected     = false;
                return(ConnectionState.DISCONECT_NOT_SUCCESS);
            }
        }
Exemple #11
0
        /// <summary>
        ///     Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        ///     Base64-formatted ciphertext value.
        /// </param>
        /// <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 this
        ///     passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        ///     Salt value used along with passphrase to generate password. Salt can
        ///     be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <returns>
        ///     Decrypted string value.
        /// </returns>
        /// <remarks>
        ///     Most of the logic in this function is similar to the Encrypt
        ///     logic. In order for decryption to work, all parameters of this function
        ///     - except cipherText value - must match the corresponding parameters of
        ///     the Encrypt function which was called to generate the
        ///     ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText,
                                     string passPhrase,
                                     string saltValue)
        {
            // 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("@IBAg3D4e5E6g7H5");
            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,
                EncryptorType,
                EncryptIterations);

            // 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);
            password.Dispose();

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged {
                Mode = CipherMode.CBC
            };

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

            // 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 = 0;

            try {
                decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            } catch (Exception) {
                return("");
            }

            // Close both streams.
            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);
        }
Exemple #12
0
        /// <summary>
        ///     Encrypts specified plaintext using Rijndael symmetric key algorithm
        ///     and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        ///     Plaintext value to be encrypted.
        /// </param>
        /// <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 this
        ///     passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        ///     Salt value used along with passphrase to generate password. Salt can
        ///     be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <returns>
        ///     Encrypted value formatted as a base64-encoded string.
        /// </returns>
        public static string Encrypt(string plainText,
                                     string passPhrase,
                                     string saltValue)
        {
            // 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("@IBAg3D4e5E6g7H5");
            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,
                EncryptorType,
                EncryptIterations);

            // 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);
            password.Dispose();

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged {
                Mode = CipherMode.CBC
            };

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

            // 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.
            string       cipherText   = string.Empty;
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = null;

            try {
                // Define cryptographic stream (always use Write mode for encryption).
                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.
                cryptoStream.Close();

                // Convert encrypted data into a base64-encoded string.
                cipherText = Convert.ToBase64String(cipherTextBytes);
            } catch {
                if (cryptoStream != null)
                {
                    cryptoStream.Close();
                }
            }

            // Return encrypted string.
            return(cipherText);
        }
        public static string Decrypt(this string obj, string passPhrase)
        {
            var result = string.Empty;

            var password = (PasswordDeriveBytes)null;

            try
            {
                password = new PasswordDeriveBytes(passPhrase, null);

                var symmetricKey = (RijndaelManaged)null;
                try
                {
                    symmetricKey = new RijndaelManaged();
                    //{ Mode = CipherMode.CBC };
                    symmetricKey.Mode = CipherMode.CBC;
                    var cipherTextBytes = Convert.FromBase64String(obj);

                    var memoryStream = (MemoryStream)null;
                    try
                    {
                        memoryStream = new MemoryStream(cipherTextBytes);

                        var initVectorBytes    = Encoding.ASCII.GetBytes(InitialisationSalt);
                        var keyBytes           = password.GetBytes(KeySize / 8);
                        var decryptor          = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
                        var plainTextBytes     = (byte[])null;
                        var decryptedByteCount = (int)0;

                        var cryptoStream = (CryptoStream)null;
                        try
                        {
                            cryptoStream       = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
                            plainTextBytes     = new byte[cipherTextBytes.Length];
                            decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.Close();
                        }
                        finally
                        {
                            if (cryptoStream != null)
                            {
                                cryptoStream.Dispose();
                            }
                        }
                        memoryStream.Close();
                        result = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                    }
                    finally
                    {
                        if (memoryStream != null)
                        {
                            memoryStream.Dispose();
                        }
                    }
                }
                finally
                {
                    if (symmetricKey != null)
                    {
                        symmetricKey.Dispose();
                    }
                }
            }
            finally
            {
                if (password != null)
                {
                    password.Dispose();
                }
            }
            return(result);
        }
Exemple #14
0
        public static async Task <string> Decrypt(string cipherText, string password, string salt = "Kosher",
                                                  string hashAlgorithm   = "SHA1",
                                                  int passwordIterations = 2,
                                                  int keySize            = 256)
        {
            return(await Task.Run(() =>
            {
                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, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    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
                    {
                        PublicVar.metadataCorrupt = true;
                        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);
            }));
        }
Exemple #15
0
        public static async Task <string> Encrypt(string plainText, string password,
                                                  string salt            = null, string hashAlgorithm = "SHA1",
                                                  int passwordIterations = 2, int keySize             = 256)
        {
            return(await Task.Run(() =>
            {
                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);
            }));
        }