Example #1
0
        public static string Encrypt(string clearText, string password, string salt, SymmetricAlgorithm algorithm = null)
        {
            try
            {
                algorithm = algorithm ?? new RijndaelManaged();

                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt.PadRight(8)));
                algorithm.Key = key.GetBytes(algorithm.KeySize / 8);
                algorithm.IV  = key.GetBytes(algorithm.BlockSize / 8);

                string cypherText = null;
                using (MemoryStream output = new MemoryStream())
                {
                    using (CryptoStream crypto = new CryptoStream(output, algorithm.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        var bytes = Encoding.UTF8.GetBytes(clearText);
                        crypto.Write(bytes, 0, bytes.Length);
                    }

                    cypherText = Convert.ToBase64String(output.ToArray());
                }

                return(cypherText);
            }
            catch
            {
                return(string.Empty);
            }
            finally
            {
                algorithm?.Clear();
            }
        }
Example #2
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="CMAC"/> class when a key change
        /// is legitimate and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">
        /// <c>true</c> to release both managed and unmanaged resources;
        /// <c>false</c> to release only unmanaged resources.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
#if NETCOREAPP1_0
                _symmetricAlgorithm?.Dispose();
#elif NET45
                _symmetricAlgorithm?.Clear();
#endif
                _encryptor?.Dispose();
                EraseData(ref _subkey1);
                EraseData(ref _subkey2);
                EraseData(ref _buffer);
                EraseData(ref _temp);
            }

            base.Dispose(disposing);
        }
Example #3
0
        /// <summary>バイト配列を暗号化する</summary>
        /// <param name="source">暗号化するバイト配列</param>
        /// <param name="password">暗号化に使用するパスワード</param>
        /// <returns>暗号化されたバイト配列</returns>
        public byte[] EncryptBytes(byte[] source, string password)
        {
            // 暗号化サービスプロバイダを生成
            SymmetricAlgorithm sa = this.CreateSymmetricAlgorithm(this.Algorithm);

            // パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;

            this.GenerateKeyFromPassword(
                password, sa.KeySize, out key, sa.BlockSize, out iv, this.Salt, this.Stretching);

            sa.Key = key;
            sa.IV  = iv;

            // 暗号化
            byte[] temp = sa.CreateEncryptor().TransformFinalBlock(source, 0, source.Length);
            sa.Clear(); // devps(1725)
            return(temp);
        }
        /// <summary>
        /// 3des解密函数(ECB加密模式,PaddingMode.PKCS7,无IV)
        /// </summary>
        /// <param name="decryptString">解密字符</param>
        /// <param name="key">解密key(24字符)</param>
        /// <returns>解密后字符</returns>
        public static string DecryptString1(string decryptString, string key)
        {
            string           destring = "解密字符失败!";
            ICryptoTransform ct;
            MemoryStream     ms;
            CryptoStream     cs;

            byte[] byt;

            SymmetricAlgorithm des3 = SymmetricAlgorithm.Create("TripleDES");

            des3.Mode = CipherMode.ECB;
            des3.Key  = Encoding.UTF8.GetBytes(splitStringLen(key, 24, '0'));
            //des3.KeySize = 192;
            des3.Padding = PaddingMode.PKCS7;

            ct = des3.CreateDecryptor();

            byt = Convert.FromBase64String(decryptString);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            try
            {
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                destring = Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                destring = ex.ToString();
            }
            finally
            {
                ms.Close();
                cs.Close();
                ms.Dispose();
                cs.Dispose();
                ct.Dispose();
                des3.Clear();
            }
            return(destring);
        }
Example #5
0
 /// <summary>
 /// Encrypts the specified data.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="key">The key.</param>
 /// <param name="initialVector">The initial vector. 16 ASCII characters long.</param>
 /// <param name="keySize">
 /// Size of the key. Can be 64 (DES only), 128 (AES), 192 (AES and Triple DES), or 256 (AES)
 /// </param>
 /// <returns>The encrypted data.</returns>
 public byte[] Encrypt(byte[] data, PasswordDeriveBytes key, byte[] initialVector, int keySize)
 {
     using SymmetricAlgorithm SymmetricKey = GetAlgorithm();
     byte[] CipherTextBytes = Array.Empty <byte>();
     if (SymmetricKey != null)
     {
         SymmetricKey.Mode = CipherMode.CBC;
         using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(key.GetBytes(keySize / 8), initialVector))
         {
             using MemoryStream MemStream    = new MemoryStream();
             using CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);
             CryptoStream.Write(data, 0, data.Length);
             CryptoStream.FlushFinalBlock();
             CipherTextBytes = MemStream.ToArray();
         }
         SymmetricKey.Clear();
     }
     return(CipherTextBytes);
 }
Example #6
0
        /// <summary>
        /// Decrypts a byte array
        /// </summary>
        /// <param name="Data">Data to be decrypted</param>
        /// <param name="Key">Password to decrypt with</param>
        /// <param name="AlgorithmUsing">Algorithm to use for decryption</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 64 (DES only), 128 (AES), 192 (AES and Triple DES), or 256 (AES)</param>
        /// <returns>A decrypted byte array</returns>
        public static byte[] Decrypt(this byte[] Data, string Key,
                                     SymmetricAlgorithm AlgorithmUsing = null, string Salt  = "Kosher",
                                     string HashAlgorithm = "SHA1", int PasswordIterations  = 2,
                                     string InitialVector = "OFRna73m*aze01xY", int KeySize = 256)
        {
            if (Data == null)
            {
                return(null);
            }
            if (AlgorithmUsing == null)
            {
                AlgorithmUsing = new RijndaelManaged();
            }

            //Key.ThrowIfNullOrEmpty("Key");
            //Salt.ThrowIfNullOrEmpty("Salt");
            //HashAlgorithm.ThrowIfNullOrEmpty("HashAlgorithm");
            //InitialVector.ThrowIfNullOrEmpty("InitialVector");
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Key, Salt.ToByteArray(), HashAlgorithm, PasswordIterations);

            using (SymmetricAlgorithm SymmetricKey = AlgorithmUsing)
            {
                SymmetricKey.Mode = CipherMode.CBC;
                byte[] PlainTextBytes = new byte[Data.Length];
                int    ByteCount      = 0;
                using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(DerivedPassword.GetBytes(KeySize / 8), InitialVector.ToByteArray()))
                {
                    using (MemoryStream MemStream = new MemoryStream(Data))
                    {
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                        {
                            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                Array.Resize(ref PlainTextBytes, ByteCount);
                return(PlainTextBytes);
            }
        }
        // -------------------------------------------------------------------------------

        /// <summary>
        /// SimpleDecrypt the ciphertext.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to be decrypted.</param>
        /// <returns>The decrypted ciphertext (-> plaintext).</returns>
        private byte[] SimpleDecrypt(byte[] ciphertext)
        {
            byte[] plaintext = null;

            string base64String = ByteArrayToAnsiString(ciphertext);

            byte[] binaryData = Convert.FromBase64String(base64String);

            MemoryStream memoryStream = new MemoryStream(binaryData, 16, binaryData.Length - 16);

            byte[] IV = new byte[16];

            // get the initialization vector
            for (int i = 0; i < 16; i++)
            {
                IV[i] = binaryData[i];
            }

            //Creates the default implementation, which is RijndaelManaged.
            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
            // creates a symmetric decryptor object with the specified Key and initialization vector (IV).
            ICryptoTransform decryptor = rijn.CreateDecryptor(this.key, IV);

            // prepare the Crypto Stream
            CryptoStream encryptedData = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

            // decrypt ciphertext
            MemoryStream decryptedData = this.GetBytes(encryptedData);

            decryptedData.Position = 0;

            plaintext = decryptedData.ToArray();

            // Speicher frei geben
            memoryStream.Close();
            decryptedData.Close();
            encryptedData.Close();
            decryptor.Dispose();
            rijn.Clear();

            return(plaintext);
        }
Example #8
0
        /// <summary>暗号化されたバイト配列を復号化する</summary>
        /// <param name="source">暗号化されたバイト配列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <param name="esa">
        /// 対称アルゴリズムによる
        /// 暗号化サービスプロバイダの種類
        /// </param>
        /// <param name="salt">ソルト</param>
        /// <param name="stretching">ストレッチング</param>
        /// <returns>
        /// 対称アルゴリズムで
        /// 復号化されたバイト配列
        /// </returns>
        public static byte[] DecryptBytes(
            byte[] source, string password, EnumSymmetricAlgorithm esa, byte[] salt, int stretching)
        {
            // 暗号化サービスプロバイダを生成
            SymmetricAlgorithm sa = SymmetricCryptography.CreateSymmetricAlgorithm(esa);

            // パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;

            SymmetricCryptography.GenerateKeyFromPassword(
                password, sa.KeySize, out key, sa.BlockSize, out iv, salt, stretching);

            sa.Key = key;
            sa.IV  = iv;

            // 復号化
            byte[] temp = sa.CreateDecryptor().TransformFinalBlock(source, 0, source.Length);
            sa.Clear(); // devps(1725)
            return(temp);
        }
Example #9
0
        /// <summary>
        /// Encrypts a byte array
        /// </summary>
        /// <param name="Data">Data to be encrypted</param>
        /// <param name="Key">Password to encrypt with</param>
        /// <param name="AlgorithmUsing">Algorithm to use for encryption (defaults to AES)</param>
        /// <param name="Salt">Salt to encrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 64 (DES only), 128 (AES), 192 (AES and Triple DES), or 256 (AES)</param>
        /// <returns>An encrypted byte array</returns>
        public static byte[] Encrypt(this byte[] Data, string Key,
                                     SymmetricAlgorithm AlgorithmUsing = null, string Salt  = "Kosher",
                                     string HashAlgorithm = "SHA1", int PasswordIterations  = 2,
                                     string InitialVector = "OFRna73m*aze01xY", int KeySize = 256)
        {
            if (Data == null)
            {
                return(null);
            }
            if (AlgorithmUsing == null)
            {
                AlgorithmUsing = new RijndaelManaged();
            }
            //Key.ThrowIfNullOrEmpty("Key");
            //Salt.ThrowIfNullOrEmpty("Salt");
            //HashAlgorithm.ThrowIfNullOrEmpty("HashAlgorithm");
            //InitialVector.ThrowIfNullOrEmpty("InitialVector");
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Key, Salt.ToByteArray(), HashAlgorithm, PasswordIterations);

            using (SymmetricAlgorithm SymmetricKey = AlgorithmUsing)
            {
                SymmetricKey.Mode = CipherMode.CBC;
                byte[] CipherTextBytes = null;
                using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(KeySize / 8), InitialVector.ToByteArray()))
                {
                    using (MemoryStream MemStream = new MemoryStream())
                    {
                        using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                        {
                            CryptoStream.Write(Data, 0, Data.Length);
                            CryptoStream.FlushFinalBlock();
                            CipherTextBytes = MemStream.ToArray();
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                return(CipherTextBytes);
            }
        }
Example #10
0
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="data">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecrypt(String data, String key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(data);
            Byte[] bKey           = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );

            //RijndaelManaged aes = new RijndaelManaged();
            SymmetricAlgorithm aes = Aes.Create();

            aes.Mode    = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key     = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);

            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int    len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return(Encoding.UTF8.GetString(ret));
            }
            finally
            {
#if NET35 || NET40 || NET45
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
#else
                //cryptoStream.();
                //mStream.Close();
                //aes.Clear();
#endif
            }
        }
Example #11
0
        /// <summary> Symmetrical function to Encrypt
        /// </summary>
        /// <param name="provider">Type of provider</param>
        /// <param name="encText">To be encrypted content</param>
        /// <param name="key">Type key</param>
        /// <param name="keySize">Size of key</param>
        /// <returns>Array of byte</returns>
        private byte[] SymmetricEncrypt(SymmetricAlgorithm provider, byte[] plainText, string key, int keySize)
        {
            //All symmetric algorithms inherit from the SymmetricAlgorithm base class, to which we can cast from the original crypto service provider
            byte[] ivBytes = GetInitializationVector(keySize);
            provider.KeySize = keySize;

            //Generate a secure key based on the original password by using SALT
            byte[] keyStream = DerivePassword(key, keySize / 8);

            //Initialize our encryptor object
            ICryptoTransform trans = provider.CreateEncryptor(keyStream, ivBytes);

            //Perform the encryption on the textStream byte array
            byte[] result = trans.TransformFinalBlock(plainText, 0, plainText.GetLength(0));

            //Release cryptographic resources
            provider.Clear();
            trans.Dispose();

            return(result);
        }
Example #12
0
 /// <summary>
 /// 通用 SymmetricAlgorithm 解密函數. 可指定 (AES, DES, RC2, Rijndael, TripleDES) 演算法解密.
 /// </summary>
 /// <param name="symAlg"></param>
 /// <param name="baEncrypt"></param>
 /// <returns></returns>
 public static byte[] Decrypt(SymmetricAlgorithm symAlg, byte[] baEncrypt)
 {
     // usage:
     //AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
     //aesCSP.GenerateKey();
     //aesCSP.GenerateIV();
     //byte[] baEncrypt1 = Encrypt(aesCSP, baPlainText);
     //byte[] baDecrypt1 = Decrypt(aesCSP, baPlainText);
     try
     {
         ICryptoTransform transform1 = symAlg.CreateDecryptor();
         byte[]           baDecrypt  = transform1.TransformFinalBlock(baEncrypt, 0, baEncrypt.Length);
         symAlg.Clear();
         return(baDecrypt);
     }
     catch (Exception e1)
     {
         msError = e1.Message;
         return(null);
     }
 }
Example #13
0
        public static string AESDecrypt(this byte[] data)
        {
            SymmetricAlgorithm aes = Rijndael.Create();

            aes.Key     = keyArray;
            aes.IV      = ivArray;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            byte[] decryptBytes = new byte[data.Length];
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cs.Read(decryptBytes, 0, decryptBytes.Length);
                    cs.Close();
                    ms.Close();
                }
            }
            aes.Clear();
            return(System.Text.Encoding.Unicode.GetString(decryptBytes).Replace("\0", " "));
        }
Example #14
0
        public static string EncryptSymmetric(this string CryptString, SymmetricProvider netSelected, byte[] Key, byte[] IV)
        {
            string             str;
            SymmetricAlgorithm symmetricCryptoService = GetSymmetricCryptoService(netSelected);

            try
            {
                symmetricCryptoService.Key = Key;
                symmetricCryptoService.IV  = IV;
                byte[] bytes = Encoding.UTF8.GetBytes(CryptString);
                return(Convert.ToBase64String(symmetricCryptoService.CreateEncryptor(Key, IV).TransformFinalBlock(bytes, 0, bytes.Length)));
            }
            catch
            {
                str = string.Empty;
            }
            finally
            {
                symmetricCryptoService.Clear();
            }
            return(str);
        }
Example #15
0
        /// <summary>
        ///     Decrypts the selected cipher text.
        /// </summary>
        /// <param name="cipherText">Cipher Text to Decrypt.</param>
        /// <returns><c>String</c> containing the plain text.</returns>
        public string Decrypt(string cipherText)
        {
            SymmetricAlgorithm symmetricAlgorithm = CreateAlgorithm(this.EncryptionAlgorithm);
            Encoding           textConverter      = Encoding.GetEncoding(this.CharacterEncoding);

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

            int ivLength = symmetricAlgorithm.IV.Length;

            byte[] ivBytes = new byte[ivLength];
            Array.Copy(cipherTextBytes, ivBytes, ivLength);

            int onlyCipherTextLength = cipherTextBytes.Length - ivLength;

            byte[] onlyCipherTextBytes = new byte[onlyCipherTextLength];
            Array.Copy(cipherTextBytes, ivLength, onlyCipherTextBytes, 0, onlyCipherTextLength);

            ICryptoTransform decryptor = symmetricAlgorithm.CreateDecryptor(this.CreateSecretKeyBytes(), ivBytes);

            MemoryStream msDecrypt = new MemoryStream(onlyCipherTextBytes);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
            string       result;

            try {
                byte[] plaintextBytes = new byte[onlyCipherTextLength];
                int    decryptedBytes = csDecrypt.Read(plaintextBytes, 0, onlyCipherTextLength);

                string plaintext = textConverter.GetString(plaintextBytes, 0, decryptedBytes);

                result = plaintext;
            } finally {
                symmetricAlgorithm.Clear();
                msDecrypt.Close();
                csDecrypt.Close();
            }

            return(result);
        }
Example #16
0
        public static byte[] Encrypt(this byte[] data,
                                     DeriveBytes key,
                                     SymmetricAlgorithm algorithmUsing = null,
                                     string initialVector = "OFRna73m*aze01xY",
                                     int keySize          = 256)
        {
            if (data.IsNull())
            {
                return(null);
            }
            algorithmUsing = algorithmUsing.NullCheck(() => new RijndaelManaged());

            Guard.NotEmpty(initialVector, "initialVector");
            using (DeriveBytes derivedPassword = key)
            {
                using (SymmetricAlgorithm symmetricKey = algorithmUsing)
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    byte[] cipherTextBytes;
                    using (
                        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(derivedPassword.GetBytes(keySize / 8),
                                                                                  initialVector.ToByteArray()))
                    {
                        using (var memStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(data, 0, data.Length);
                                cryptoStream.FlushFinalBlock();
                                cipherTextBytes = memStream.ToArray();
                            }
                        }
                    }
                    symmetricKey.Clear();
                    return(cipherTextBytes);
                }
            }
        }
Example #17
0
        public static byte[] AESEncrypt(this string text)
        {
            byte[]             data = Encoding.Unicode.GetBytes(text);
            SymmetricAlgorithm aes  = Rijndael.Create();

            aes.Key     = keyArray;
            aes.IV      = ivArray;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();
                    byte[] cipherBytes = ms.ToArray(); // 得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                    aes.Clear();
                    return(cipherBytes);
                }
            }
        }
Example #18
0
 /// <summary>
 /// AES解密
 /// </summary>
 /// <param name="encrypt">解密原文</param>
 /// <param name="secret">密钥</param>
 /// <returns></returns>
 public static string AESDecrypt(string encrypt, string secret)
 {
     try
     {
         byte[]             encryptBytes = Convert.FromBase64String(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(encrypt)));
         SymmetricAlgorithm aes          = Rijndael.Create();
         aes.Mode    = CipherMode.ECB;
         aes.Padding = PaddingMode.Zeros;
         aes.Key     = Encoding.UTF8.GetBytes(secret);
         byte[]       decryptBytes = new byte[encryptBytes.Length];
         MemoryStream memoryStream = new MemoryStream(encryptBytes);
         CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
         cryptoStream.Read(decryptBytes, 0, decryptBytes.Length);
         cryptoStream.Close();
         memoryStream.Close();
         aes.Clear();
         return(Encoding.UTF8.GetString(decryptBytes));
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Example #19
0
        public static string DecryptSymmetric(this string DecryptString, SymmetricProvider netSelected, byte[] Key, byte[] IV)
        {
            string             str;
            SymmetricAlgorithm symmetricCryptoService = GetSymmetricCryptoService(netSelected);

            try
            {
                symmetricCryptoService.Key = Key;
                symmetricCryptoService.IV  = IV;
                byte[]           inputBuffer = Convert.FromBase64String(DecryptString);
                ICryptoTransform transform   = symmetricCryptoService.CreateDecryptor(Key, IV);
                return(Encoding.UTF8.GetString(transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length)));
            }
            catch
            {
                str = string.Empty;
            }
            finally
            {
                symmetricCryptoService.Clear();
            }
            return(str);
        }
Example #20
0
        /// <summary>
        /// Decrypts a string of data previously encoded with <see cref="Encrypt"/> using
        /// the given key.
        /// </summary>
        /// <param name="data">
        ///		Data that was previously encrypted with <see cref="Encrypt"/>.
        /// </param>
        /// <param name="key">
        ///		Key used when the data was encrypted.
        /// </param>
        public static string Decrypt(string data, string key)
        {
            int len = int.Parse(data.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);

            byte[]             iv        = Convert.FromBase64String(data.Substring(2, len));
            byte[]             dataBytes = Convert.FromBase64String(data.Substring(2 + len));
            MemoryStream       ms        = new MemoryStream();
            SymmetricAlgorithm encoder   = SymmetricAlgorithm.Create("TripleDES");

            //			encoder.Padding	= PaddingMode.Zeros;
            encoder.Key = Encoding.Default.GetBytes(GetLegalKey(key, encoder));
            encoder.IV  = iv;

            CryptoStream cryptStream = new CryptoStream(ms, encoder.CreateDecryptor(), CryptoStreamMode.Write);

            cryptStream.Write(dataBytes, 0, dataBytes.Length);
            cryptStream.FlushFinalBlock();

            encoder.Clear();
            cryptStream.Clear();

            return(Encoding.Default.GetString(ms.ToArray()));
        }
Example #21
0
 /// <summary>
 /// Encrypts a byte array
 /// </summary>
 /// <param name="Data">Data to encrypt</param>
 /// <param name="Key">Key to use to encrypt the data (can use PasswordDeriveBytes, Rfc2898DeriveBytes, etc. Really anything that implements DeriveBytes)</param>
 /// <param name="AlgorithmUsing">Algorithm to use for encryption (defaults to AES)</param>
 /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="KeySize">Can be 64 (DES only), 128 (AES), 192 (AES and Triple DES), or 256 (AES)</param>
 /// <returns>An encrypted byte array</returns>
 public static byte[] Encrypt(this byte[] Data,
                              DeriveBytes Key,
                              SymmetricAlgorithm AlgorithmUsing = null,
                              string InitialVector = "OFRna73m*aze01xY",
                              int KeySize          = 256)
 {
     if (Data.IsNull())
     {
         return(null);
     }
     AlgorithmUsing = AlgorithmUsing.NullCheck(new RijndaelManaged());
     InitialVector.ThrowIfNullOrEmpty("InitialVector");
     using (DeriveBytes DerivedPassword = Key)
     {
         using (SymmetricAlgorithm SymmetricKey = AlgorithmUsing)
         {
             SymmetricKey.Mode = CipherMode.CBC;
             byte[] CipherTextBytes = null;
             using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(KeySize / 8), InitialVector.ToByteArray()))
             {
                 using (MemoryStream MemStream = new MemoryStream())
                 {
                     using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                     {
                         CryptoStream.Write(Data, 0, Data.Length);
                         CryptoStream.FlushFinalBlock();
                         CipherTextBytes = MemStream.ToArray();
                         MemStream.Close();
                         CryptoStream.Close();
                     }
                 }
             }
             SymmetricKey.Clear();
             return(CipherTextBytes);
         }
     }
 }
Example #22
0
 protected override void Dispose(bool disposing)
 {
     cipher.Clear();
 }
Example #23
0
        /// <summary>
        /// Decrypts an string using AES
        /// </summary>
        /// <param name="data">The data to decrypt.</param>
        /// <param name="password">The password to use.</param>
        public static string DecryptString(byte[] data, string password)
        {
            byte[] plainText;

            // Read the salt from the array
            byte[] salt = new byte[32];
            Buffer.BlockCopy(data, 0, salt, 0, salt.Length);

            // Create algorithms
            using (SymmetricAlgorithm encryptator = Aes.Create())
                using (KeyedHashAlgorithm signer = new HMACSHA256())
                {
                    // Extract the signature
                    byte[] signature = new byte[signer.HashSize / 8];
                    Buffer.BlockCopy(data, 32, signature, 0, signer.HashSize / 8);

                    // Grab the rest of the data
                    int    payloadLength = data.Length - 32 - signature.Length;
                    byte[] payload       = new byte[payloadLength];
                    Buffer.BlockCopy(data, 32 + signature.Length, payload, 0, payloadLength);

                    // Check the signature before anything else is done to detect tampering and avoid oracles
                    byte[] computedSignature = SignData(password, payload, salt, encryptator, signer);
                    if (!computedSignature.IsEqualsTo(signature))
                    {
                        throw new CryptographicException("Invalid signature.");
                    }

                    // Clear the signer algorithm
                    signer.Clear();

                    // Extract IV
                    int    ivLength   = encryptator.BlockSize / 8;
                    byte[] iv         = new byte[ivLength];
                    byte[] cipherText = new byte[payload.Length - ivLength];

                    // Extract the data
                    Buffer.BlockCopy(payload, 0, iv, 0, ivLength);
                    Buffer.BlockCopy(payload, ivLength, cipherText, 0, payload.Length - ivLength);

                    // Set encryptation key and IV
                    encryptator.Key = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, KeyDerivationIterationCount, encryptator.KeySize / 8);
                    encryptator.IV  = iv;

                    // Decrypt the data
                    using (var ms = new MemoryStream())
                        using (var crypto = new CryptoStream(ms, encryptator.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            // Write to the stream
                            crypto.Write(cipherText, 0, cipherText.Length);
                            crypto.FlushFinalBlock();

                            // Get plain text
                            plainText = ms.ToArray();
                        }

                    // Clear algorithms
                    encryptator.Clear();
                }

            // Return the decrypted data
            return(Encoding.UTF8.GetString(plainText));
        }
Example #24
0
 public void Dispose()
 {
     mobjCryptoService.Clear();
 }
 public void Clear()
 {
     _algo.Clear();
 }
Example #26
0
 /// <summary>
 ///     Releases all resources used by the symmetric algorithm
 /// </summary>
 public void Dispose()
 {
     _algorithm.Clear();
     _algorithm.Dispose();
 }
Example #27
0
 /// <summary> Disposes of the key </summary>
 protected override void Dispose(bool disposing)
 {
     _key.Clear();
     base.Dispose(disposing);
 }
 /// <summary>When we're done using this, it is safest to clear all security
 /// bits from memory.  That's what this does.</summary>
 public void Clear()
 {
     _sa.Clear();
 }
Example #29
0
 public void Clear()
 {
     _algorithm.Clear();
 }
Example #30
0
 public void Dispose()
 {
     algorithm.Clear();
 }