public string Decrypt(string encrypted, string salt)
        {
            RijndaelManaged aesAlg = null;
            string          plaintext;

            try
            {
                aesAlg = GetManager(salt);
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                var bytes = Convert.FromBase64String(encrypted);
                using (var msDecrypt = new MemoryStream(bytes))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        using (var srDecrypt = new StreamReader(csDecrypt))
                            plaintext = srDecrypt.ReadToEnd();
                }
            }
            catch (Exception)
            {
                return("");
            }
            finally
            {
                aesAlg?.Clear();
            }

            return(plaintext);
        }
        public string Encrypt(string value, string salt)
        {
            string          outStr;
            RijndaelManaged aesAlg = null;

            try
            {
                aesAlg = GetManager(salt);

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                            swEncrypt.Write(value);

                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                aesAlg?.Clear();
            }

            return(outStr);
        }
Esempio n. 3
0
        /// <summary>
        /// Зашифровать массив байт
        /// </summary>
        public static byte[] EncryptBytes(byte[] bytes, byte[] secretKey, byte[] iv)
        {
            RijndaelManaged alg = null;

            try
            {
                alg = new RijndaelManaged()
                {
                    Key = secretKey, IV = iv
                };

                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream =
                               new CryptoStream(memStream, alg.CreateEncryptor(secretKey, iv), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                    }

                    return(memStream.ToArray());
                }
            }
            finally
            {
                alg?.Clear();
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Дешифровать массив байт
        /// </summary>
        public static byte[] DecryptBytes(byte[] bytes, byte[] secretKey, byte[] iv)
        {
            RijndaelManaged alg = null;

            try
            {
                alg = new RijndaelManaged()
                {
                    Key = secretKey, IV = iv
                };

                using (MemoryStream memStream = new MemoryStream(bytes))
                {
                    using (CryptoStream cryptoStream =
                               new CryptoStream(memStream, alg.CreateDecryptor(secretKey, iv), CryptoStreamMode.Read))
                    {
                        return(ReadToEnd(cryptoStream));
                    }
                }
            }
            finally
            {
                alg?.Clear();
            }
        }
Esempio n. 5
0
        public string EncryptStringAES(string plainText, string sharedSecret)
        {
            string          outStr = null;
            RijndaelManaged aesAlg = null;

            try {
                var key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (var msEncrypt = new MemoryStream()) {
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
                        using (var swEncrypt = new StreamWriter(csEncrypt)) {
                            swEncrypt.Write(plainText);
                        }
                    }

                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            } finally {
                aesAlg?.Clear();
            }

            return(outStr);
        }
Esempio n. 6
0
        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAes(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException(nameof(cipherText));
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException(nameof(sharedSecret));
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext;

            try
            {
                // generate the key from the shared secret and the salt
                var key = new Rfc2898DeriveBytes(sharedSecret, Salt);

                // Create the streams used for decryption.
                var bytes = Convert.FromBase64String(cipherText);

                using (var msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object with the specified key and IV.
                    aesAlg = new RijndaelManaged();

                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                    // Get the initialization vector from the encrypted stream
                    aesAlg.IV = ReadByteArray(msDecrypt);

                    // Create a decrytor to perform the stream transform.
                    var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }

            return(plaintext);
        }
Esempio n. 7
0
        static string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged {
                    Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = key, IV = iv
                };

                // Create a decrytor to perform the stream transform.
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (var msDecrypt = new MemoryStream(cipherText))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                            // srDecrypt.Close();
                        }
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }

            return(plaintext);
        }
Esempio n. 8
0
        static byte[] EncryptStringToBytesAes(string plainText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("iv");
            }

            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            RijndaelManaged aesAlg = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged {
                    Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = key, IV = iv
                };

                // Create an encryptor to perform the stream transform.
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                        //                        swEncrypt.Flush();
                        //                        swEncrypt.Close();
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return(msEncrypt.ToArray());
        }
Esempio n. 9
0
        /// <summary>
        /// Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAes(string plainText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(plainText);
            }

            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException(nameof(sharedSecret));
            }

            string          outStr;              // Encrypted string to return
            RijndaelManaged aesAlg = null;       // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, Salt);

                // Create a RijndaelManaged object
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            catch (Exception)
            {
                outStr = plainText;
            }
            finally
            {
                // Clear the Rijndael Managed object.
                aesAlg?.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return(outStr);
        }
Esempio n. 10
0
    private ICryptoTransform InitDecrypt(string a_key)
    {
        byte[] keyBytes = Encoding.Unicode.GetBytes(a_key);
        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(a_key, keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
        ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();
        rijndaelCSP.Clear();
        return decryptor;
    }
Esempio n. 11
0
    /// <summary> 
    /// Decrypt the given string.  Assumes the string was encrypted using  
    /// EncryptStringAES(), using an identical sharedSecret. 
    /// </summary> 
    /// <param name="cipherText">The text to decrypt.</param> 
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param> 
    public static string DecryptStringAES( string cipherText, string sharedSecret )
    {
        if ( string.IsNullOrEmpty( cipherText ) )
            throw new ArgumentNullException( "cipherText" );
        if ( string.IsNullOrEmpty( sharedSecret ) )
            throw new ArgumentNullException( "sharedSecret" );

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes( sharedSecret, _salt );

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String( cipherText );
            using ( MemoryStream msDecrypt = new MemoryStream( bytes ) )
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes( aesAlg.KeySize / 8 );
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray( msDecrypt );
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor( aesAlg.Key, aesAlg.IV );
                using ( CryptoStream csDecrypt = new CryptoStream( msDecrypt, decryptor, CryptoStreamMode.Read ) )
                {
                    using ( StreamReader srDecrypt = new StreamReader( csDecrypt ) )

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if ( aesAlg != null )
                aesAlg.Clear();
        }

        return plaintext;
    }
Esempio n. 12
0
 private string decryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
 {
     if (cipherText == null || cipherText.Length <= 0)
     {
         throw new ArgumentNullException("cipherText");
     }
     if (Key == null || Key.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     if (IV == null || IV.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     MemoryStream memoryStream = null;
     CryptoStream cryptoStream = null;
     StreamReader streamReader = null;
     RijndaelManaged rijndaelManaged = null;
     string result = null;
     try
     {
         rijndaelManaged = new RijndaelManaged();
         rijndaelManaged.Key = Key;
         rijndaelManaged.IV = IV;
         var transform = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
         memoryStream = new MemoryStream(cipherText);
         cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
         streamReader = new StreamReader(cryptoStream);
         result = streamReader.ReadToEnd();
     }
     finally
     {
         if (streamReader != null)
         {
             streamReader.Close();
         }
         if (cryptoStream != null)
         {
             cryptoStream.Close();
         }
         if (memoryStream != null)
         {
             memoryStream.Close();
         }
         if (rijndaelManaged != null)
         {
             rijndaelManaged.Clear();
         }
     }
     return result;
 }
Esempio n. 13
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptedText">密文</param>
        /// <param name="error">错误信息</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量值(传入该值时使用CBC模式解密,否则使用ECB模式解密)</param>
        /// <param name="encodingName">编码名称</param>
        /// <returns>明文</returns>
        public static string Decrypt(string encryptedText, out string error,
                                     string key = DEFAULT_KEY, byte[] vector = null, string encodingName = "UTF-8")
        {
            error = null;
            RijndaelManaged aes = null;

            try
            {
                var encoding       = Encoding.GetEncoding(encodingName);
                var encryptedBytes = Convert.FromBase64String(encryptedText);

                aes = new RijndaelManaged
                {
                    Padding = PaddingMode.PKCS7,
                    KeySize = 128,
                    Key     = encoding.GetBytes(key)
                };

                if (vector.IsEmpty())
                {
                    aes.Mode = CipherMode.ECB;
                }
                else
                {
                    aes.Mode = CipherMode.CBC;
                    aes.IV   = vector;
                }

                using (var mStream = new MemoryStream(encryptedBytes))
                    using (var cryptoStream = new CryptoStream(mStream
                                                               , aes.CreateDecryptor()
                                                               , CryptoStreamMode.Read))
                    {
                        var tmp = new byte[encryptedBytes.Length + 32];
                        int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                        var ret = new byte[len];
                        Array.Copy(tmp, 0, ret, 0, len);
                        return(encoding.GetString(ret));
                    }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(string.Empty);
            }
            finally
            {
                aes?.Clear();
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Decrypts the string.
        /// </summary>
        /// <param name="cipherText">The cipher text.</param>
        /// <param name="keyBytes">The key bytes.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">DataEncryptionKey must be specified in configuration file</exception>
        private static string DecryptString(string cipherText, byte[] keyBytes)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                return(string.Empty);
            }

            if (keyBytes == null || keyBytes.Length == 0)
            {
                throw new ArgumentNullException("DataEncryptionKey must be specified in configuration file");
            }

            string          plaintext = null;
            RijndaelManaged aesAlg    = null;

            try
            {
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
                {
                    // Create a RijndaelManaged object with the specified key and the IV from the encrypted stream.
                    aesAlg = new RijndaelManaged
                    {
                        Key = keyBytes,
                        IV  = ReadByteArray(msDecrypt)
                    };

                    // Create a decryptor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    // Read the decrypted bytes from the decrypting stream and place them in a string.
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                }
            }
            catch
            {
                // Intentionally ignore so the caller can try another key when it gets a null value back.
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }

            return(plaintext);
        }
Esempio n. 15
0
        // ReSharper disable once InconsistentNaming
        public static string EncryptStringAES(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException(nameof(plainText));
            }

            RijndaelManaged aesAlgorithm = null;           // RijndaelManaged object used to encrypt the data.

            try
            {
                // Generate the key from a shared secret and initilization vector.
                var key = new Rfc2898DeriveBytes("https://github.com/R-Smith/vmPing" + Environment.MachineName, Encoding.ASCII.GetBytes(Environment.UserName + "@@vmping-salt@@"));

                // Create a RijndaelManaged object.
                aesAlgorithm = new RijndaelManaged {
                    Padding = PaddingMode.PKCS7
                };
                aesAlgorithm.Key = key.GetBytes(aesAlgorithm.KeySize / 8);

                key.Dispose();

                // Create a decryptor to perform the stream transform.
                var encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV);

                // Create the streams used for encryption.
                using (var memoryStream = new MemoryStream())
                {
                    // Prepend the IV.
                    memoryStream.Write(BitConverter.GetBytes(aesAlgorithm.IV.Length), 0, sizeof(int));
                    memoryStream.Write(aesAlgorithm.IV, 0, aesAlgorithm.IV.Length);
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                        using (var streamWriter = new StreamWriter(cryptoStream))
                        {
                            // Write all data to the stream.
                            streamWriter.Write(plainText);
                        }

                    // Return the encrypted bytes from the memory stream.
                    return(Convert.ToBase64String(memoryStream.ToArray()));
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlgorithm?.Clear();
                aesAlgorithm?.Dispose();
            }
        }
Esempio n. 16
0
        public static string Decrypt(string crypttxt, string password)
        {
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, _salt);

                // Create the streams used for decryption.
                byte[] bytes = Convert.FromBase64String(crypttxt);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object
                    // with the specified key and IV.
                    aesAlg     = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    // Get the initialization vector from the encrypted stream
                    byte[] rawLength = new byte[sizeof(int)];
                    if (msDecrypt.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
                    {
                        throw new SystemException("Stream did not contain properly formatted byte array");
                    }
                    byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
                    if (msDecrypt.Read(buffer, 0, buffer.Length) != buffer.Length)
                    {
                        throw new SystemException("Did not read byte array properly");
                    }
                    aesAlg.IV = buffer;
                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            return(srDecrypt.ReadToEnd());
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }
        }
Esempio n. 17
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="error">错误信息</param>
        /// <param name="key">密钥</param>
        /// <param name="vector">向量值(传入该值时使用CBC模式加密,否则使用ECB模式加密)</param>
        /// <param name="encodingName">编码名称</param>
        /// <returns>密文</returns>
        public static string Encrypt(string plainText, out string error,
                                     string key = DEFAULT_KEY, byte[] vector = null, string encodingName = "UTF-8")
        {
            error = null;
            RijndaelManaged aes = null;

            try
            {
                var encoding   = Encoding.GetEncoding(encodingName);
                var plainBytes = encoding.GetBytes(plainText);

                aes = new RijndaelManaged
                {
                    Padding = PaddingMode.PKCS7,
                    KeySize = 128,
                    Key     = encoding.GetBytes(key)
                };

                if (vector.IsEmpty())
                {
                    aes.Mode = CipherMode.ECB;
                }
                else
                {
                    aes.Mode = CipherMode.CBC;
                    aes.IV   = vector;
                }

                using (var mStream = new MemoryStream())
                    using (var cryptoStream = new CryptoStream(mStream
                                                               , aes.CreateEncryptor()
                                                               , CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        return(Convert.ToBase64String(mStream.ToArray()));
                    }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(string.Empty);
            }
            finally
            {
                aes?.Clear();
            }
        }
Esempio n. 18
0
        /// <summary>Criptografar o Texto.</summary>
        /// <param name="textoLimpo">Texto Limpo para criptografar</param>
        /// <param name="chaveAplicacao">A Chave secreta da aplicação </param>
        /// <returns>The <see cref="string"/>.</returns>
        public static string Criptografar(string textoLimpo, string chaveAplicacao)
        {
            if (string.IsNullOrEmpty(textoLimpo))
            {
                throw new ArgumentNullException(nameof(textoLimpo));
            }

            if (string.IsNullOrEmpty(chaveAplicacao))
            {
                throw new ArgumentNullException(nameof(chaveAplicacao));
            }

            string          outStr = null;
            RijndaelManaged aesAlg = null;

            try
            {
                var key = new Rfc2898DeriveBytes(chaveAplicacao, ChaveSecreta);

                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                var memoryStream = new MemoryStream();

                memoryStream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                memoryStream.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                var encrypt = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

                using (var streamWriter = new StreamWriter(encrypt))
                {
                    streamWriter.Write(textoLimpo);
                }

                outStr = Convert.ToBase64String(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                throw new CryptographicException("Erro ao descriptografar", ex);
            }
            finally
            {
                aesAlg?.Clear();
            }

            return(outStr);
        }
	// Protect a block of memory.
	internal static void Protect
				(byte[] userData, byte[] optionalEntropy,
				 MemoryProtectionScope scope, byte[] output)
			{
				// Get the key to use.
				byte[] key = GetScopeKey(scope, optionalEntropy);

				// Encrypt the block of memory using AES.
				Rijndael alg = new RijndaelManaged();
				alg.Mode = CipherMode.CFB;
				ICryptoTransform transform = alg.CreateEncryptor(key, null);
				transform.TransformBlock
					(userData, 0, userData.Length, output, 0);
				transform.Dispose();
				alg.Clear();
				Array.Clear(key, 0, key.Length);
			}
Esempio n. 20
0
        // ReSharper disable once InconsistentNaming
        public static string DecryptStringAES(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException(nameof(cipherText));
            }

            // Declare the RijndaelManaged object used to decrypt the data.
            RijndaelManaged aesAlgorithm = null;

            try
            {
                // Generate the key from a shared secret and initilization vector.
                var key = new Rfc2898DeriveBytes("https://github.com/R-Smith/vmPing" + Environment.MachineName, Encoding.ASCII.GetBytes(Environment.UserName + "@@vmping-salt@@"));

                // Create the streams used for decryption.
                var bytes = Convert.FromBase64String(cipherText);
                using (var memoryStream = new MemoryStream(bytes))
                {
                    // Create a RijndaelManaged object with the specified key and IV.
                    aesAlgorithm = new RijndaelManaged {
                        Padding = PaddingMode.PKCS7
                    };
                    aesAlgorithm.Key = key.GetBytes(aesAlgorithm.KeySize / 8);

                    // Get the initialization vector from the encrypted stream.
                    aesAlgorithm.IV = ReadByteArray(memoryStream);

                    // Create a decrytor to perform the stream transform.
                    var decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV);
                    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        using (var streamReader = new StreamReader(cryptoStream))
                        {
                            // Read the decrypted bytes from the decrypting stream and place them in a string.
                            var plaintext = streamReader.ReadToEnd();
                            return(plaintext);
                        }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlgorithm?.Clear();
            }
        }
Esempio n. 21
0
        public string Encrypt(string plainText, string sharedSecret)
        {
            if (plainText == null)
            {
                throw new ArgumentNullException(nameof(plainText));
            }

            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException(nameof(sharedSecret));
            }

            string          outStr = null;              // Encrypted string to return
            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, Salt);
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream memoryEncrypt = new MemoryStream())
                {
                    memoryEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    memoryEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream cryptoEncrypt = new CryptoStream(memoryEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter writerEncrypt = new StreamWriter(cryptoEncrypt))
                        {
                            writerEncrypt.Write(plainText);
                        }
                    }

                    outStr = Convert.ToBase64String(memoryEncrypt.ToArray());
                }
            }
            finally
            {
                aesAlg?.Clear();
            }

            return(outStr);
        }
Esempio n. 22
0
        /// <summary>
        ///     Encrypt the given string using AES.  The string can be decrypted using
        ///     DecryptStringAES().  The sharedSecret parameters must match.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        public static string EncryptStringAES(string plainText, string sharedSecret)
        {
            string          outStr = null; // Encrypted string to return
            RijndaelManaged aesAlg = null; // RijndaelManaged object used to encrypt the data.

            try
            {
                // generate the key from the shared secret and the salt
                var key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                // Create a RijndaelManaged object
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                // Create a decryptor to perform the stream transform.
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (var msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                    }

                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                aesAlg?.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return(outStr);
        }
Esempio n. 23
0
        public string EncryptString(string plainText, string sharedSecret, byte[] salt)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            string          outStr = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);
                aesAlg         = new RijndaelManaged();
                aesAlg.KeySize = 256;
                aesAlg.Key     = key.GetBytes(aesAlg.KeySize / 8);
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    // prepend the IV
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            return(outStr);
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            //<snippet2>
            RijndaelManaged key = null;

            try
            {
                // Create a new Rijndael key.
                key = new RijndaelManaged();
                //</snippet2>
                //<snippet3>
                // Load an XML document.
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load("test.xml");
                //</snippet3>

                // Encrypt the "creditcard" element.
                Encrypt(xmlDoc, "creditcard", key);

                Console.WriteLine("The element was encrypted");

                Console.WriteLine(xmlDoc.InnerXml);

                Decrypt(xmlDoc, key);

                Console.WriteLine("The element was decrypted");

                Console.WriteLine(xmlDoc.InnerXml);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                // Clear the key.
                if (key != null)
                {
                    key.Clear();
                }
            }
        }
Esempio n. 25
0
        //шифрование
        public static string Encript(string plainText, string password)
        {
            string salt               = "Alcatraz";
            string hashAlgoritm       = "SHA1";
            int    passwordIterations = 2;
            string initialVector      = "QFRna74m*awe01xU";
            int    keySize            = 256;

            if (string.IsNullOrEmpty(plainText))
            {
                return("");
            }
            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValuesBytes    = Encoding.ASCII.GetBytes(salt);
            byte[] plainTextBytes     = Encoding.UTF8.GetBytes(plainText);

            PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes(password, saltValuesBytes, hashAlgoritm, passwordIterations);

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

            symetricKey.Mode = CipherMode.CBC;

            byte[] cipherTextBytes = null;

            using (ICryptoTransform encriptor = symetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encriptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memoryStream.ToArray();
                        memoryStream.Close();
                        cryptoStream.Close();
                    }
                }
            }

            symetricKey.Clear();
            return(Convert.ToBase64String(cipherTextBytes));
        }
Esempio n. 26
0
        public string Encrypt(string strToEncrypt, SecureString strSecret)
        {
            if (strToEncrypt == "" || strSecret.Length == 0)
            {
                return(strToEncrypt);
            }

            try
            {
                var rd = new RijndaelManaged();

                var md5 = new MD5CryptoServiceProvider();
                var key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString()));

                md5.Clear();
                rd.Key = key;
                rd.GenerateIV();

                var iv = rd.IV;
                var ms = new MemoryStream();

                ms.Write(iv, 0, iv.Length);

                var cs   = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write);
                var data = Encoding.UTF8.GetBytes(strToEncrypt);

                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();

                var encdata = ms.ToArray();
                cs.Close();
                rd.Clear();

                return(Convert.ToBase64String(encdata));
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
                                                    string.Format(Language.strErrorEncryptionFailed, ex.Message));
            }

            return(strToEncrypt);
        }
Esempio n. 27
0
        public string Encrypt(string value)
        {
            byte[]           array;
            ICryptoTransform cryptoTransform = null;
            MemoryStream     memoryStream    = null;
            CryptoStream     cryptoStream    = null;
            var bytes           = Encoding.Unicode.GetBytes(value);
            var rijndaelManaged = new RijndaelManaged();

            using (rijndaelManaged)
            {
                try
                {
                    cryptoTransform = rijndaelManaged.CreateEncryptor(PasskeyBytes, InitVectorBytes);
                    memoryStream    = new MemoryStream();
                    cryptoStream    = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write);
                    cryptoStream.Write(bytes, 0, bytes.Length);
                    cryptoStream.FlushFinalBlock();
                    array = memoryStream.ToArray();
                    cryptoStream.Close();
                    cryptoStream = null;
                    memoryStream = null;
                }
                finally
                {
                    if (cryptoStream != null)
                    {
                        cryptoStream.Dispose();
                        memoryStream = null;
                    }
                    if (memoryStream != null)
                    {
                        memoryStream.Dispose();
                    }
                    if (cryptoTransform != null)
                    {
                        cryptoTransform.Dispose();
                    }
                    rijndaelManaged.Clear();
                }
            }
            return(Convert.ToBase64String(array));
        }
Esempio n. 28
0
        public string de_code_text(string value)
        {
            string password           = "******";
            string salt               = "NEPIMSHCH";
            string hashAlgorithm      = "SHA1";
            int    passwordIterations = 2;
            string initialVector      = "OFRna73m*aze01xY";
            int    KeySize            = 256;

            if (string.IsNullOrEmpty(value))
            {
                return("");
            }

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes     = Encoding.ASCII.GetBytes(salt);
            byte[] cipherTextBytes    = Convert.FromBase64String(value);

            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 (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(KeyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();
            return(Encoding.UTF8.GetString(plainTextBytes, 0, byteCount));
        }
Esempio n. 29
0
        public string DecryptString(string cipherText, string sharedSecret, byte[] salt)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            RijndaelManaged aesAlg    = null;
            string          plaintext = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

                byte[] bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    aesAlg         = new RijndaelManaged();
                    aesAlg.KeySize = 256;
                    aesAlg.Key     = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV      = ReadByteArray(msDecrypt);
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(plaintext);
        }
Esempio n. 30
0
        private string EncryptStringAES(string plainText)
        {
            string                     Secret = "";
            ManagementClass            Class  = new ManagementClass("win32_processor");
            ManagementObjectCollection Collec = Class.GetInstances();

            foreach (ManagementObject Obj in Collec)
            {
                if (Secret == "")
                {
                    Secret = Obj.Properties["processorID"].Value.ToString().Substring(0, 8);
                    break;
                }
            }
            if (!string.IsNullOrEmpty(plainText) & !string.IsNullOrEmpty(Secret))
            {
                string          outStr = null;
                RijndaelManaged aesAlg = null;
                try
                {
                    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Secret, _salt);
                    aesAlg     = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                    using (MemoryStream msEncrypt = new MemoryStream())
                    {
                        msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                        msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) swEncrypt.Write(plainText);
                        outStr = Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
                finally
                {
                    if (aesAlg != null)
                    {
                        aesAlg.Clear();
                    }
                }
                return(outStr);
            }
            return("");
        }
Esempio n. 31
0
        public string EncryptString(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }


            string          outStr = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV  = key.GetBytes(aesAlg.BlockSize / 8);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    }
                    outStr = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(outStr);
        }
Esempio n. 32
0
        //дешифровка
        public static string Decript(string chiperTextm, string password)
        {
            string salt               = "Alcatraz";
            string hashAlgoritm       = "SHA1";
            int    passwordIterations = 2;
            string initialVector      = "QFRna74m*awe01xU";
            int    keySize            = 256;

            if (string.IsNullOrEmpty(chiperTextm))
            {
                return("");
            }

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes     = Encoding.ASCII.GetBytes(salt);
            byte[] chipherTextBytes   = Convert.FromBase64String(chiperTextm);

            PasswordDeriveBytes drivePassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgoritm, passwordIterations);

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

            RijndaelManaged symetricKey = new RijndaelManaged();

            symetricKey.Mode = CipherMode.CBC;

            byte[] plaintextBytes = new byte[chipherTextBytes.Length];
            int    byteCount      = 0;

            using (ICryptoTransform decriptor = symetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memoryStream = new MemoryStream(chipherTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decriptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plaintextBytes, 0, plaintextBytes.Length);
                        memoryStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symetricKey.Clear();
            return(Encoding.UTF8.GetString(plaintextBytes, 0, byteCount));
        }
Esempio n. 33
0
        public static string AESDecript(string stringa)
        {
            if (string.IsNullOrEmpty(stringa))
            {
                throw new ArgumentNullException("sifreliMetin");
            }
            if (string.IsNullOrEmpty(loki_decrypt()))
            {
                throw new ArgumentNullException("sifre");
            }

            RijndaelManaged aes           = null;
            string          cozulmusMetin = null;

            try
            {
                var key = new Rfc2898DeriveBytes(loki_decrypt(), _salt);

                byte[] bytes = Convert.FromBase64String(stringa);
                using (var msDecrypt = new MemoryStream(bytes))
                {
                    aes     = new RijndaelManaged();
                    aes.Key = key.GetBytes(aes.KeySize / 8);
                    aes.IV  = ReadByteArray(msDecrypt);

                    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (var srDecrypt = new StreamReader(csDecrypt))

                            cozulmusMetin = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                if (aes != null)
                {
                    aes.Clear();
                }
            }
            return(cozulmusMetin);
        }
Esempio n. 34
0
        public byte[] symmetricEncryption(byte[] plainText, byte[] Key, byte[] IV)
        {
            RijndaelManaged  rm        = null;
            MemoryStream     ms        = null;
            ICryptoTransform Encryptor = null;
            //Crypto streams allow encryption in memory
            CryptoStream cs = null;

            //Just get bytes from plain text
            byte[] plainBytes = plainText;

            try
            {
                rm           = new RijndaelManaged();
                rm.Key       = Key;
                rm.IV        = IV;
                rm.Mode      = CipherMode.CBC;
                rm.Padding   = PaddingMode.PKCS7;
                rm.BlockSize = 128;


                ms = new MemoryStream();

                //Creates the method to Encrypt, inputs are the Symmetric Key & IV
                Encryptor = rm.CreateEncryptor(rm.Key, rm.IV);

                //Writes the data to memory to perform the transformation
                cs = new CryptoStream(ms, Encryptor, CryptoStreamMode.Write);

                //Takes in string to be encrypted, offset value, & length of string to be encrypted
                cs.Write(plainBytes, 0, plainBytes.Length);
                cs.FlushFinalBlock();
            }
            finally
            {
                if (rm != null)
                {
                    rm.Clear();
                }
            }
            //Returns the memory byte array
            return(ms.ToArray());
        }
Esempio n. 35
0
    /// <summary>
    /// Encrypt the given string using AES.  The string can be decrypted using 
    /// DecryptStringAES().  The sharedSecret parameters must match.
    /// </summary>
    /// <param name="plainText">The text to encrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        string outStr = null;                       // Encrypted string to return
        RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

        try {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            aesAlg = new RijndaelManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

            // Create a decryptor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream()) {
                // prepend the IV
                msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }
        } finally {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return outStr;
    }
Esempio n. 36
0
            private void encryptTitleKey()
            {
                commonKeyIndex = newKeyIndex;
                byte[] ckey = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                byte[] iv = BitConverter.GetBytes(Shared.Swap(titleId));
                Array.Resize(ref iv, 16);

                RijndaelManaged rm = new RijndaelManaged();
                rm.Mode = CipherMode.CBC;
                rm.Padding = PaddingMode.None;
                rm.KeySize = 128;
                rm.BlockSize = 128;
                rm.Key = ckey;
                rm.IV = iv;

                ICryptoTransform encryptor = rm.CreateEncryptor();

                MemoryStream ms = new MemoryStream(decryptedTitleKey);
                CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Read);

                cs.Read(encryptedTitleKey, 0, encryptedTitleKey.Length);

                cs.Dispose();
                ms.Dispose();
                encryptor.Dispose();
                rm.Clear();
            }
	public static String DecryptRJ256(byte[] cypher, string KeyString, string IVString)
	{
		UTF8Encoding encoding = new UTF8Encoding();
		
		byte[] Key = encoding.GetBytes(KeyString);
        byte[] IV = encoding.GetBytes(IVString);
	
	    string sRet = "";
	    RijndaelManaged rj = new RijndaelManaged();

      // rj.Padding = PaddingMode.Zeros;
        rj.Mode = CipherMode.CBC;
        rj.KeySize = 256;
        rj.BlockSize = 256;
        rj.Key = Key;
        rj.IV = IV;
		
	    try
	    {
	        
	        MemoryStream ms = new MemoryStream(cypher);
	
	        using (CryptoStream cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
            {
                using (StreamReader sr = new StreamReader(cs))
                {
                    sRet = sr.ReadLine();
                }
                cs.Close();
            }
	
	    }
	    finally
	    {
	        rj.Clear();
	    }
	
	    return sRet;
	}
	 public static string EncryptString(string message, string KeyString, string IVString)
    {
        byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
        byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);

        string encrypted = null;
        RijndaelManaged rj = new RijndaelManaged();
		
		rj.BlockSize = 256;
        rj.Key = Key;
        rj.IV = IV;
        rj.Mode = CipherMode.CBC;

        try
        {
            MemoryStream ms = new MemoryStream();

            using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(message);
                    sw.Close();
                }
                cs.Close();
            }
            byte[] encoded = ms.ToArray();
            encrypted = Convert.ToBase64String(encoded);

            ms.Close();
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: {0}", e.Message);
        }
        finally
        {
            rj.Clear();
        }

        return encrypted;
    }
Esempio n. 39
0
 private byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
 {
     if (plainText == null || plainText.Length <= 0)
     {
         throw new ArgumentNullException("plainText");
     }
     if (Key == null || Key.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     if (IV == null || IV.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     MemoryStream memoryStream = null;
     CryptoStream cryptoStream = null;
     StreamWriter streamWriter = null;
     RijndaelManaged rijndaelManaged = null;
     try
     {
         rijndaelManaged = new RijndaelManaged();
         rijndaelManaged.Key = Key;
         rijndaelManaged.IV = IV;
         var transform = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
         memoryStream = new MemoryStream();
         cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
         streamWriter = new StreamWriter(cryptoStream);
         streamWriter.Write(plainText);
     }
     finally
     {
         if (streamWriter != null)
         {
             streamWriter.Close();
         }
         if (cryptoStream != null)
         {
             cryptoStream.Close();
         }
         if (memoryStream != null)
         {
             memoryStream.Close();
         }
         if (rijndaelManaged != null)
         {
             rijndaelManaged.Clear();
         }
     }
     return memoryStream.ToArray();
 }