FlushFinalBlock() public method

public FlushFinalBlock ( ) : void
return void
 public static string Encrypt(string plainText, string passPhrase)
 {
     byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                     {
                         cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                         cryptoStream.FlushFinalBlock();
                         byte[] cipherTextBytes = memoryStream.ToArray();
                         return Convert.ToBase64String(cipherTextBytes);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 2
1
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="text">要被解密字符</param>
 /// <param name="sKey">密钥</param>
 /// <returns></returns>
 public static string Decrypt(this string text, string sKey)
 {
     var provider = new DESCryptoServiceProvider();
     int num = text.Length / 2;
     byte[] buffer = new byte[num];
     try
     {
         for (int i = 0; i < num; i++)
         {
             int num3 = Convert.ToInt32(text.Substring(i * 2, 2), 0x10);
             buffer[i] = (byte)num3;
         }
     }
     catch
     {
         return string.Empty;
     }
     provider.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     provider.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
     MemoryStream stream = new MemoryStream();
     CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
     try
     {
         stream2.Write(buffer, 0, buffer.Length);
         stream2.FlushFinalBlock();
     }
     catch
     {
         return string.Empty;
     }
     return Encoding.Default.GetString(stream.ToArray());
 }
Ejemplo n.º 3
1
        public static string EncryptString(
            string plainText,
            string passPhrase,
            string saltValue,
            int passwordIterations,
            string initVector,
            int keySize)
        {

            byte[] initVectorBytes = initVector == null ? new byte[16] : Encoding.ASCII.GetBytes(initVector);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            byte[] keyBytes = GetKeyBytes(passPhrase, saltValue, passwordIterations, keySize);
            RijndaelManaged symmetricKey = new RijndaelManaged();
            symmetricKey.Mode = CipherMode.CBC;
            ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            byte[] cipherTextBytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                }
            }
            string cipherText = Convert.ToBase64String(cipherTextBytes);
            return cipherText;
        }
Ejemplo n.º 4
1
        public static string Encrypt( string strEncryptString, string strEncryptionKey)
        {
            byte[] inputByteArray;

            try
            {
                key = Encoding.UTF8.GetBytes(strEncryptionKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Encoding.UTF8.GetBytes(strEncryptString);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

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

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception eX)
            {

                throw eX;
            }
        }
Ejemplo n.º 5
1
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="pToEncrypt">需要加密字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //把字符串放到byte数组中

                //原来使用的UTF8编码,我改成Unicode编码了,不行
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

                //建立加密对象的密钥和偏移量

                //使得输入密码必须输入英文文本
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }
            catch (Exception ex)
            {

            }

            return "";
        }
Ejemplo n.º 6
1
 public static string Encrypt(string plainText, string passPhrase)
 {
     // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
     // so that the same Salt and IV values can be used when decrypting.
     var saltStringBytes = Generate256BitsOfRandomEntropy();
     var ivStringBytes = Generate256BitsOfRandomEntropy();
     var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
     var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations);
     var keyBytes = password.GetBytes(Keysize / 8);
     using (var symmetricKey = new RijndaelManaged())
     {
         symmetricKey.BlockSize = 256;
         symmetricKey.Mode = CipherMode.CBC;
         symmetricKey.Padding = PaddingMode.PKCS7;
         using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
         {
             using (var memoryStream = new MemoryStream())
             {
                 using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                 {
                     cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                     cryptoStream.FlushFinalBlock();
                     // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                     var cipherTextBytes = saltStringBytes;
                     cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                     cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                     memoryStream.Close();
                     cryptoStream.Close();
                     return Convert.ToBase64String(cipherTextBytes);
                 }
             }
         }
     }
 }
Ejemplo n.º 7
1
        public static string Encode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] bytes = Encoding.UTF8.GetBytes(str);

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            stream2.FlushFinalBlock();

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())
            {

                builder.AppendFormat("{0:X2}", num);

            }

            stream.Close();

            return builder.ToString();
        }
 /// <summary>
 /// 加密字符串
 /// </summary>
 /// <param name="encryptString"></param>
 /// <returns></returns>
 public static string Encrypt(string encryptString)
 {
     System.IO.MemoryStream mStream = null;
     System.Security.Cryptography.CryptoStream cStream = null;
     try
     {
         EncryptUtil des            = new EncryptUtil();
         byte[]      rgbKey         = Encoding.UTF8.GetBytes(des.encryptKey.Substring(0, 8));
         byte[]      rgbIV          = Encoding.UTF8.GetBytes(des.encryptIV.Substring(0, 8));
         byte[]      inputByteArray = Encoding.UTF8.GetBytes(encryptString);
         System.Security.Cryptography.DESCryptoServiceProvider dCSP = new System.Security.Cryptography.DESCryptoServiceProvider();
         mStream = new System.IO.MemoryStream();
         cStream = new System.Security.Cryptography.CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
         cStream.Write(inputByteArray, 0, inputByteArray.Length);
         cStream.FlushFinalBlock();
         return(Convert.ToBase64String(mStream.ToArray()));
     }
     catch (Exception)
     {
         return(encryptString);
     }
     finally
     {
         if (mStream != null)
         {
             mStream.Close(); mStream.Dispose();
         }
         if (cStream != null)
         {
             cStream.Close(); cStream.Dispose();
         }
     }
 }
Ejemplo n.º 9
0
        // ************************************** DEBUT 1 *****************************

        //public static string Encrypt(string original)
        //{
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;

        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(original);

        //    return UnicodeEncoding.Unicode.GetString(
        //    des.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //}

        //public static String Decrypt(String StringToDecrypt)
        //{

        //    String StringDecrypted = "";
        //    MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
        //    byte[] passwordHash = hashMd5.ComputeHash(
        //    UnicodeEncoding.Unicode.GetBytes(clefDuCryptage));

        //    TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
        //    des.Key = passwordHash;
        //    des.Mode = CipherMode.ECB;

        //    byte[] buffer = UnicodeEncoding.Unicode.GetBytes(StringToDecrypt);
        //    StringDecrypted = UnicodeEncoding.Unicode.GetString(
        //    des.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));

        //    return StringDecrypted;
        //}

        // ************************************** FIN 1 *****************************



        // ************************************** DEBUT 2 *****************************
        //public static string Encrypt(string input, string key)
        //{
        //    byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateEncryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        //}

        //public static string Decrypt(string input, string key)
        //{
        //    byte[] inputArray = Convert.FromBase64String(input);
        //    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
        //    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
        //    tripleDES.Mode = CipherMode.ECB;
        //    tripleDES.Padding = PaddingMode.PKCS7;
        //    ICryptoTransform cTransform = tripleDES.CreateDecryptor();
        //    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
        //    tripleDES.Clear();
        //    return UTF8Encoding.UTF8.GetString(resultArray);
        //}
        // **************************************  FIN 2 *****************************

        /// <summary>
        /// Crypte une chaine en utilisant un chiffreur symétrique
        /// </summary>
        /// <param name="plainText">Chaine à crypter</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine cryptée</returns>
        public static string Encrypt(string plainText, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];

            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);

            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);

            using (MemoryStream ms = new MemoryStream(plainText.Length * 2))
            {
                using (System.Security.Cryptography.CryptoStream encStream = new
                                                                             System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(),
                                                                                                                       System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
                    encStream.Write(plainBytes, 0, plainBytes.Length);
                    encStream.FlushFinalBlock();
                    byte[] encryptedBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(encryptedBytes, 0, (int)ms.Length);
                    encStream.Close();
                    ms.Close();
                    result = Convert.ToBase64String(encryptedBytes);
                }
            }
            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="sIn"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public string Encrypt(string sIn, string sKey = "ColtSmart")
        {
            byte[] inputByteArray = System.Text.Encoding.ASCII.GetBytes(sIn);
            using (System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider())
            {
                des.Mode    = CipherMode.ECB;
                des.Padding = PaddingMode.Zeros;
                byte[] keyByteArray      = new byte[8];
                byte[] inputKeyByteArray = ASCIIEncoding.ASCII.GetBytes(sKey);
                for (int i = 0; i < 8; i++)
                {
                    if (inputKeyByteArray.Length > i)
                    {
                        keyByteArray[i] = inputKeyByteArray[i];
                    }
                    else
                    {
                        keyByteArray[i] = 0;
                    }
                }

                des.Key = keyByteArray;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return(str);
            }
        }
Ejemplo n.º 11
0
            public static string Decrypt(string strDecrypt, bool retStrOriginal)
            {
                string result = string.Empty;

                System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
                try
                {
                    byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(Secret.AES.Key);
                    byte[] bytes2 = System.Text.Encoding.UTF8.GetBytes(Secret.AES.IV);
                    byte[] array  = Convert.FromBase64String(strDecrypt);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateDecryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(array, 0, array.Length);
                            cryptoStream.FlushFinalBlock();
                            result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
                        }
                    }
                }
                catch
                {
                    if (retStrOriginal)
                    {
                        result = strDecrypt;
                    }
                    else
                    {
                        result = string.Empty;
                    }
                }
                rijndael.Clear();
                return(result);
            }
Ejemplo n.º 12
0
    public static byte[] InternalEncrypt(byte[] data, out byte[] key, out byte[] IV)
    {
        byte[] bytes = null;
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.ICryptoTransform trans = GetEncServiceProvider(out key, out IV);
        System.Security.Cryptography.CryptoStream     cs    = new System.Security.Cryptography.CryptoStream(ms, trans, System.Security.Cryptography.CryptoStreamMode.Write);

        try
        {
            cs.Write(data, 0, data.Length);

            if (cs != null)
            {
                cs.FlushFinalBlock();
                cs.Close();
            }
            bytes = ms.ToArray();
        }
        finally
        {
            if (cs != null)
            {
                cs.Close();
            }
            if (ms != null)
            {
                ms.Close();
            }
        }

        return(bytes);
    }
        public string Encrypt(string Text)
        {
            string outText = string.Empty;

            System.Security.Cryptography.CryptoStream myCryptoStream = null;
            try
            {
                System.Byte[]          bufferRead     = System.Text.Encoding.ASCII.GetBytes(Text);
                System.IO.MemoryStream myOutMemStream = new System.IO.MemoryStream(1024);

                myrijManaged.Key = keyByte;
                myrijManaged.IV  = IVByte;
                System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateEncryptor();
                myCryptoStream = new System.Security.Cryptography.CryptoStream(myOutMemStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Write);
                myCryptoStream.Write(bufferRead, 0, bufferRead.Length);
                myCryptoStream.FlushFinalBlock();
                System.Byte[] result = new byte[(int)myOutMemStream.Position];
                myOutMemStream.Position = 0;
                myOutMemStream.Read(result, 0, result.Length);
                outText = System.Convert.ToBase64String(result);
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (myCryptoStream != null)
                {
                    myCryptoStream.Close();
                }
            }

            return(outText);
        }
Ejemplo n.º 14
0
 public static byte[] EncryptToByteArray(string str)
 {
     byte[] bytes = new System.Text.UTF8Encoding().GetBytes(str);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     byte[] result;
     try
     {
         System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, new System.Security.Cryptography.TripleDESCryptoServiceProvider().CreateEncryptor(StringUtils.Key(), StringUtils.Iv()), System.Security.Cryptography.CryptoStreamMode.Write);
         try
         {
             cryptoStream.Write(bytes, 0, bytes.Length);
             cryptoStream.FlushFinalBlock();
             result = memoryStream.ToArray();
         }
         finally
         {
             cryptoStream.Dispose();
         }
     }
     finally
     {
         memoryStream.Dispose();
     }
     return(result);
 }
Ejemplo n.º 15
0
        public static string AESEncrypt(string encryptStr, string encryptKey)
        {
            string result;

            if (string.IsNullOrWhiteSpace(encryptStr))
            {
                result = string.Empty;
            }
            else
            {
                encryptKey = StringHelper.SubString(encryptKey, 32);
                encryptKey = encryptKey.PadRight(32, ' ');
                System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create();
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(encryptStr);
                symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(encryptKey);
                symmetricAlgorithm.IV  = SecureHelper._aeskeys;
                byte[] inArray = null;
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytes, 0, bytes.Length);
                        cryptoStream.FlushFinalBlock();
                        inArray = memoryStream.ToArray();
                        cryptoStream.Close();
                        memoryStream.Close();
                    }
                }
                result = System.Convert.ToBase64String(inArray);
            }
            return(result);
        }
Ejemplo n.º 16
0
Archivo: Des.cs Proyecto: Fun33/code
    ///    <summary>
    /// 字串解密
    /// </summary>
    public static string Decrypt(string pToDecrypt)
    {
        if (pToDecrypt == string.Empty)
        {
            return(string.Empty);
        }

        try
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            //'把字符串放入byte數組
            int len = 0;
            len = pToDecrypt.Length / 2 - 1;
            byte[] inputByteArray = new byte[len + 1];
            int    x = 0;
            int    i = 0;
            for (x = 0; x <= len; x++)
            {
                i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
                inputByteArray[x] = Convert.ToByte(i);
            }
            //'建立加密對象的密鑰和偏移量,此值重要,不能修改
            des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(skey);
            des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(skey);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return(System.Text.Encoding.Default.GetString(ms.ToArray()));
        }
        catch (Exception ex)
        {
            return(ex.Message);
        }
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Décrypte une chaine cryptée à partir d'un chiffreur symétrique
        /// </summary>
        /// <param name="base64String">chaine cryptée</param>
        /// <param name="pass">Mot de passe utilisé pour dériver la clé</param>
        /// <returns>Chaine décryptée</returns>
        private static string Decrypt(string base64String, string pass)
        {
            string result = string.Empty;

            System.Security.Cryptography.TripleDESCryptoServiceProvider des =
                new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            des.IV = new byte[8];
            System.Security.Cryptography.PasswordDeriveBytes pdb =
                new System.Security.Cryptography.PasswordDeriveBytes(pass, new byte[0]);
            des.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, new byte[8]);
            byte[] encryptedBytes = Convert.FromBase64String(base64String);

            using (MemoryStream ms = new MemoryStream(base64String.Length))
            {
                using (System.Security.Cryptography.CryptoStream decStream =
                           new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(),
                                                                         System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                    decStream.FlushFinalBlock();
                    byte[] plainBytes = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(plainBytes, 0, (int)ms.Length);
                    result = Encoding.UTF8.GetString(plainBytes);
                }
            }
            return(result);
        }
Ejemplo n.º 18
0
            public static string Encrypt(string Text, string sKey)
            {
                string result;

                if (string.IsNullOrEmpty(Text))
                {
                    result = "";
                }
                else
                {
                    string text = SecretCommon.Md5Hex.Encrypt(sKey, false);
                    System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
                    byte[] bytes = System.Text.Encoding.Default.GetBytes(Text);
                    dESCryptoServiceProvider.Key = System.Text.Encoding.ASCII.GetBytes(text.Substring(8, 8));
                    dESCryptoServiceProvider.IV  = System.Text.Encoding.ASCII.GetBytes(text.Substring(0, 8));
                    MemoryStream memoryStream = new MemoryStream();
                    System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                    cryptoStream.Write(bytes, 0, bytes.Length);
                    cryptoStream.FlushFinalBlock();
                    System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                    byte[] array = memoryStream.ToArray();
                    for (int i = 0; i < array.Length; i++)
                    {
                        byte b = array[i];
                        stringBuilder.AppendFormat("{0:X2}", b);
                    }
                    result = stringBuilder.ToString();
                }
                return(result);
            }
Ejemplo n.º 19
0
        // AES加密
        public static string AESEncrypt(string plainStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(Key);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

            string encrypt = null;
            Rijndael aes = Rijndael.Create();
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(mStream.ToArray());
                    }
                }
            }
            catch { }
            aes.Clear();

            return encrypt;
        }
Ejemplo n.º 20
0
        public static string DESEnCode(string pToEncrypt, string sKey)
        {
            // string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);   
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);

            //建立加密对象的密钥和偏移量    
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法    
            //使得输入密码必须输入英文文本    
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

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

            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
Ejemplo n.º 21
0
        public static string DESDeCode(string pToDecrypt, string sKey)
        {
            //    HttpContext.Current.Response.Write(pToDecrypt + "<br>" + sKey);   
            //    HttpContext.Current.Response.End();   
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            // return HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(ms.ToArray()));
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
Ejemplo n.º 22
0
        public static string TripleDESDecrypt(string pToDecrypt, string key = "")
        {
            string result;

            try
            {
                key = (string.IsNullOrWhiteSpace(key) ? EncryptHelper.strKey : key);
                byte[] array = new byte[pToDecrypt.Length / 2];
                for (int i = 0; i < pToDecrypt.Length / 2; i++)
                {
                    int num = System.Convert.ToInt32(pToDecrypt.Substring(i * 2, 2), 16);
                    array[i] = (byte)num;
                }
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key  = System.Text.Encoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cryptoStream.Write(array, 0, array.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                memoryStream.Close();
                result = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// 加密字符串
 /// </summary>
 /// <param name="inputStr">输入字符串</param>
 /// <param name="keyStr">密码,可以为“”</param>
 /// <returns>输出加密后字符串</returns>
 public string EncryptString(string inputStr, string keyStr)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     if (keyStr == "")
         keyStr = key;
     byte[] inputByteArray = Encoding.Default.GetBytes(inputStr);
     byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
     SHA1 ha = new SHA1Managed();
     byte[] hb = ha.ComputeHash(keyByteArray);
     sKey = new byte[8];
     sIV = new byte[8];
     for (int i = 0; i < 8; i++)
         sKey[i] = hb[i];
     for (int i = 8; i < 16; i++)
         sIV[i - 8] = hb[i];
     des.Key = sKey;
     des.IV = sIV;
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         ret.AppendFormat("{0:X2}", b);
     }
     cs.Close();
     ms.Close();
     return ret.ToString();
 }
 /// <summary>
 /// DES加密
 /// </summary>
 /// <param name="str"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string DESEncrypt(string str, string key)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     //把字符串放到byte数组中 
     byte[] inputByteArray = Encoding.Default.GetBytes(str);
     //建立加密对象的密钥和偏移量  
     //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
     //使得输入密码必须输入英文文本  
     des.Key = ASCIIEncoding.ASCII.GetBytes(key);
     des.IV = ASCIIEncoding.ASCII.GetBytes(key);
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     //Write  the  byte  array  into  the  crypto  stream  
     //(It  will  end  up  in  the  memory  stream)  
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         //Format  as  hex  
         ret.AppendFormat("{0:X2}", b);
     }
     ret.ToString();
     return ret.ToString();
 }
Ejemplo n.º 25
0
        public static string TripleDESEncrypt(string pToEncrypt, string key = "")
        {
            string result;

            try
            {
                key = string.IsNullOrWhiteSpace(key) ? EncryptHelper.strKey : key;
                StringBuilder stringBuilder = new StringBuilder();
                TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
                tripleDESCryptoServiceProvider.Key  = System.Text.Encoding.ASCII.GetBytes(key);
                tripleDESCryptoServiceProvider.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, tripleDESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(pToEncrypt);
                cryptoStream.Write(bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock();
                byte[] array = memoryStream.ToArray();
                for (int i = 0; i < array.Length; i++)
                {
                    byte b = array[i];
                    stringBuilder.AppendFormat("{0:X2}", b);
                }
                result = stringBuilder.ToString();
            }
            catch (Exception ex)
            {
                result = ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 26
0
        public static string Encrypt(string plainText)
        {
            var registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            var plainTextBytes = Encoding.Unicode.GetBytes(plainText);

            using (var memoryStream = new MemoryStream())
            {
                using (Rijndael rijndael = Rijndael.Create())
                {
                    using (
                        ICryptoTransform cryptoTransform = rijndael.CreateEncryptor(passwordDerivedBytes.GetBytes(32), rgbIV: passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            return Convert.ToBase64String(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public static string Decode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] buffer = new byte[str.Length / 2];

            for (int i = 0; i < (str.Length / 2); i++)
            {

                int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);

                buffer[i] = (byte)num2;

            }

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);

            stream2.Write(buffer, 0, buffer.Length);

            stream2.FlushFinalBlock();

            stream.Close();

            return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
        }
Ejemplo n.º 28
0
 public static string Decrypt(string strText)
 {
     string text1;
     if (strText == String.Empty)
     {
         return strText;
     }
     byte[] buffer1;
     byte[] buffer2;
     byte[] buffer3 = GetCryptArr();
     try
     {
         buffer1 = Encoding.UTF8.GetBytes(GetCryptKey().Substring(0,8));
         DESCryptoServiceProvider provider1 =  new DESCryptoServiceProvider();
         buffer2 = Convert.FromBase64String(strText);
         MemoryStream stream2 = new MemoryStream();
         using (CryptoStream stream1 = new CryptoStream(stream2, provider1.CreateDecryptor(buffer1, buffer3), CryptoStreamMode.Write))
         {
             stream1.Write(buffer2, 0, buffer2.Length);
             stream1.FlushFinalBlock();
             text1 = Encoding.UTF8.GetString(stream2.ToArray());
         }
     }
     catch
     {
         return "Error";
     }
     return text1;
 }
Ejemplo n.º 29
0
                /// <summary>
                /// Método para encriptar em AES
                /// </summary>
                /// <param name="plaintext"></param>
                /// <param name="text"></param>
                /// <returns></returns>
                public static byte[] Encrypt(byte[] plaintext, string text)
                {
                    /*
                     * Block Length: 128bit
                     * Block Mode: ECB
                     * Data Padding: Padded by bytes which Asc() equal for number of padded bytes (done automagically)
                     * Key Padding: 0x00 padded to multiple of 16 bytes
                     * IV: None
                     */
                    byte[] key = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
                    System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
                    AES.BlockSize = 128;
                    AES.Mode      = System.Security.Cryptography.CipherMode.ECB;
                    AES.Key       = key;

                    System.Security.Cryptography.ICryptoTransform encryptor = AES.CreateEncryptor();
                    MemoryStream mem = new MemoryStream();

                    System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(mem, encryptor,
                                                                                                                          System.Security.Cryptography.CryptoStreamMode.Write);

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

                    byte[] cypher = mem.ToArray();

                    cryptStream.Close();
                    cryptStream = null;
                    encryptor.Dispose();
                    AES = null;

                    return(cypher);
                }
Ejemplo n.º 30
0
        /// <summary>
        /// A chave deve possuir 16 com caracteres "1234567890123456"
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetDescriptografiaSimetrica(this string str, string key)
        {
            using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
            {


                provider.Mode = CipherMode.CFB;
                provider.Padding = PaddingMode.PKCS7;
                byte[] inputEquivalent = Convert.FromBase64String(str);

                MemoryStream msDecrypt = new MemoryStream();

                CryptoStream csDecrypt = new CryptoStream(msDecrypt, provider.CreateDecryptor(Encoding.UTF8.GetBytes(key), new byte[] { 138, 154, 251, 188, 64, 108, 167, 121 }), CryptoStreamMode.Write);
                csDecrypt.Write(inputEquivalent, 0, inputEquivalent.Length);
                csDecrypt.FlushFinalBlock();

                csDecrypt.Close();

                str = Encoding.UTF8.GetString(msDecrypt.ToArray());
                msDecrypt.Close();
            }


            return str;
        }
Ejemplo n.º 31
0
        public static string Encrypt(string text)
        {

            byte[] encodedkey;
            byte[] iv = { 0x1F, 0x2E, 0x3D, 0x4C, 0x5B, 0x6A, 0x78, 0xA7 };
            byte[] bytes;

            encodedkey = Encoding.UTF8.GetBytes(EncryptKey);
            DESCryptoServiceProvider csp = new DESCryptoServiceProvider();

            bytes = Encoding.UTF8.GetBytes(text);
            MemoryStream ms = new MemoryStream();

            try
            {
                CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(encodedkey, iv), CryptoStreamMode.Write);

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

            }
            catch (Exception ex)
            {
                return "";
            }

            return Convert.ToBase64String(ms.ToArray());

        }
Ejemplo n.º 32
0
 public string DecryptDES(string encrypt, string iv, string decryptKey)
 {
     string[] sInput = encrypt.Split("-".ToCharArray());
     byte[] data = new byte[sInput.Length];
     for (int i = 0; i < sInput.Length; i++)
     {
         data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
     }
     try
     {
         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
         byte[] rgbIV = Encoding.UTF8.GetBytes(iv);
         byte[] inputByteArray = data;
         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
         MemoryStream mStream = new MemoryStream();
         CryptoStream cStream = new CryptoStream(
             mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
         cStream.Write(inputByteArray, 0, inputByteArray.Length);
         cStream.FlushFinalBlock();
         return Encoding.UTF8.GetString(mStream.ToArray());
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 33
0
        /// <summary> 
        /// �������� 
        /// </summary> 
        /// <param name="Text">ԭ��</param> 
        /// <param name="sKey">��Կ</param> 
        /// <returns>����</returns> 
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider desKey = new DESCryptoServiceProvider();

            byte[] inputByteArray = Encoding.Default.GetBytes(Text);
            byte[] keyByteArray = Encoding.Default.GetBytes(sKey);

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(keyByteArray);

            desKey.Key = HalveByteArray(md5.Hash);
            desKey.IV = HalveByteArray(md5.Hash);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desKey.CreateEncryptor(), CryptoStreamMode.Write);

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

            StringBuilder result = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                result.AppendFormat("{0:X2}", b);
            }

            return result.ToString();
        }
Ejemplo n.º 34
0
		/// <summary>
		/// Encrypts a string
		/// </summary>
		/// <param name="PlainText">Text to be encrypted</param>
		/// <param name="Password">Password to encrypt with</param>
		/// <param name="Salt">Salt to encrypt with</param>
		/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
		/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
		/// <param name="PasswordIterations">Number of iterations to do</param>
		/// <param name="KeySize">Can be 128, 192, or 256</param>
		/// <returns>An encrypted bytes</returns>
		public static byte[] Encrypt(byte[] PlainText, byte[] Password, byte[] InitialVector,
			byte[] Salt)
		{
			PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, Salt, HASH_ALGORITHM, PASSWORDITERATIONS);
			byte[] KeyBytes = DerivedPassword.GetBytes(KEY_SIZE / 8);
			RijndaelManaged SymmetricKey = new RijndaelManaged();
			SymmetricKey.Mode = CipherMode.CBC;
			byte[] CipherTextBytes = null;

			using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVector))
			{
				using (MemoryStream MemStream = new MemoryStream())
				{
					using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
					{
						CryptoStream.Write(PlainText, 0, PlainText.Length);
						CryptoStream.FlushFinalBlock();
						CipherTextBytes = MemStream.ToArray();
						MemStream.Close();
						CryptoStream.Close();
					}
				}
			}

			SymmetricKey.Clear();
			return CipherTextBytes;
			//return Encoding.UTF8.GetBytes(Convert.ToBase64String(CipherTextBytes));
		}
Ejemplo n.º 35
0
Archivo: Des.cs Proyecto: Fun33/code
    ///    <summary>
    /// 字串加密
    /// </summary>
    public static string Encrypt(string pToEncrypt)
    {
        if (pToEncrypt == string.Empty)
        {
            return(string.Empty);
        }

        System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
        byte[] inputByteArray = null;
        inputByteArray = System.Text.Encoding.Default.GetBytes(pToEncrypt);
        //'建立加密對象的密鑰和偏移量
        //'原文使用ASCIIEncoding.ASCII方法的GetBytes方法
        //'使得輸入密碼必須輸入英文文本
        des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(skey);
        des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(skey);
        //'寫二進制數組到加密流
        //'(把內存流中的內容全部寫入)
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        //'寫二進制數組到加密流
        //'(把內存流中的內容全部寫入)
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        //'建立輸出字符串
        System.Text.StringBuilder ret = new System.Text.StringBuilder();
        byte b = 0;

        foreach (byte b_loopVariable in ms.ToArray())
        {
            b = b_loopVariable;
            ret.AppendFormat("{0:X2}", b);
        }
        return(ret.ToString());
    }
        /// <summary>
        /// Encrypt/Decrypt with Read method. Recommended for decrypting only.
        /// </summary>
        /// <param name="cryptor"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private byte[] CipherStreamRead(System.Security.Cryptography.ICryptoTransform cryptor, byte[] input)
        {
            WriteLog("--- Cipher Stream:");
            WriteLog("InputBlockSize: " + cryptor.InputBlockSize.ToString());
            WriteLog("OutputBlockSize: " + cryptor.OutputBlockSize.ToString());
            byte[] inputBuffer  = new byte[input.Length];
            byte[] outputBuffer = new byte[input.Length];
            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the input bytes.
            var stream = new System.IO.MemoryStream(inputBuffer);
            // Create a CryptoStream through which we are going to be processing our data.
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            // Start the crypting process.
            int length = cryptoStream.Read(outputBuffer, 0, outputBuffer.Length);

            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            System.Array.Resize(ref outputBuffer, length);
            // Close both streams.
            stream.Close();
            // cryptoStream.Close();
            WriteEnc(inputBuffer, outputBuffer);
            return(outputBuffer);
        }
Ejemplo n.º 37
0
        public static string Decrypt(string strStringDecrypt, string strEncryptionKey)
        {
            byte[] inputByteArray = new byte[strStringDecrypt.Length];

            try
            {
                key = Encoding.UTF8.GetBytes(strEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                inputByteArray = Convert.FromBase64String(strStringDecrypt.Replace(" ", "+"));

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

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

                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception eX)
            {

                throw eX;
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密匙</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                //建立加密对象的密钥和偏移量,此值重要,不能修改
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {

            }
            return "";
        }
Ejemplo n.º 39
0
        public static string Decrypt(string text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Convert.FromBase64String(text);

                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();

                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                // Handle Exception Here
            }

            return string.Empty;
        }
Ejemplo n.º 40
0
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密匙</param>
        /// <returns>解密后的字符串</returns>
        public static string DESDecrypt(string pToDecrypt)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                //建立加密对象的密钥和偏移量,此值重要,不能修改
                des.Key = Encoding.UTF8.GetBytes(sKey);
                des.IV = Encoding.UTF8.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("读取配置信息失败,详细信息:" + ex.Message.Replace("\r\n", "").Replace("'", ""));
            }
            return "";
        }
Ejemplo n.º 41
0
        /// <summary>
        /// A chave deve possuir 16 com caracteres "1234567890123456"
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCriptografiaSimetrica(this string str, string key)
        {
            using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
            {

                provider.Mode = CipherMode.CFB;
                provider.Padding = PaddingMode.PKCS7;

                MemoryStream mStream = new MemoryStream();

                CryptoStream cs = new CryptoStream(mStream, provider.CreateEncryptor(Encoding.UTF8.GetBytes(key), new byte[] { 138, 154, 251, 188, 64, 108, 167, 121 }), CryptoStreamMode.Write);

                byte[] toEncrypt = new UTF8Encoding().GetBytes(str);

                cs.Write(toEncrypt, 0, toEncrypt.Length);
                cs.FlushFinalBlock();
                byte[] ret = mStream.ToArray();

                mStream.Close();
                cs.Close();

                str = Convert.ToBase64String(ret);

            }


            return str;
        }
Ejemplo n.º 42
0
        /// <summary>
        /// 用给定的Key进行加密
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="encryptString">要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string encryptString, string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                key = _Key;
            else
                key += _Key;

            if (string.IsNullOrWhiteSpace(encryptString))
                encryptString = string.Empty;

            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] keyIV = keyBytes;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            using (DESCryptoServiceProvider provider = new DESCryptoServiceProvider())
            {
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();

                //Get the data back from the memory stream, and into a string
                StringBuilder ret = new StringBuilder();
                foreach (byte b in mStream.ToArray())
                {
                    //Format as hex
                    ret.AppendFormat("{0:X2}", b);
                }
                return ret.ToString();
            }
        }
Ejemplo n.º 43
0
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            AesManaged aes = null;
            MemoryStream memoryStream = null;
            CryptoStream cryptoStream = null;

            try
            {
                aes = new AesManaged();
                aes.Key = readKeyFromFile(partition);

                memoryStream = new MemoryStream();
                cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

                byte[] buf = Encoding.UTF8.GetBytes(data);
                cryptoStream.Write(buf, 0, buf.Length);
                cryptoStream.FlushFinalBlock();

                dataOut = Convert.ToBase64String(memoryStream.ToArray());
            }
            finally
            {
                if (cryptoStream != null)
                    cryptoStream.Close();

                if (memoryStream != null)
                    memoryStream.Close();

                if (aes != null)
                    aes.Clear();
            }

            return getErrorCode() == 0 ? 1 : 0;
        }
Ejemplo n.º 44
0
        /// <summary>
        /// DES 加密算法
        /// </summary>
        /// <param name="str">待加密字符串</param>
        /// <returns>加密后字符串</returns>
        public static string EncodeStr(string str)
        {
            try
            {
                byte[] temp = Encoding.UTF8.GetBytes(str);

                using (DESCryptoServiceProvider desc = new DESCryptoServiceProvider())
                {
                    desc.Key = ASCIIEncoding.ASCII.GetBytes(key); desc.IV = ASCIIEncoding.ASCII.GetBytes(iv);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(temp, 0, temp.Length);

                            cs.FlushFinalBlock();
                        }

                        StringBuilder sb = new StringBuilder();

                        foreach (byte b in ms.ToArray())
                        {
                            sb.AppendFormat("{0:X2}", b);
                        }
                        return sb.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static string DESDecrypt(string Value, string Key)
        {
            if (Value.Trim().Equals(string.Empty))
                return string.Empty;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[Value.Length / 2];
            for (int x = 0; x < Value.Length / 2; x++)
            {
                int i = (Convert.ToInt32(Value.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(Key);
            des.IV = ASCIIEncoding.ASCII.GetBytes(Key);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder sb = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                sb.Append((char)b);
            }
            return sb.ToString();
        }
Ejemplo n.º 46
0
        public string Decrypt(string encryptStr)
        {
            byte[] bKey = Encoding.UTF8.GetBytes(PrivateKey);
            byte[] bIV = Encoding.UTF8.GetBytes(IV);
            byte[] byteArray = Convert.FromBase64String(encryptStr);

            string decrypt = null;
            #if !NET451
            var aes = System.Security.Cryptography.Aes.Create();
            #else
            var aes = Rijndael.Create();
            #endif
            try
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray(), 0, mStream.ToArray().Count());
                    }
                }
            }
            catch { }
            #if NET451
            aes.Clear();
            #endif

            return decrypt;
        }
Ejemplo n.º 47
0
 public static byte[] DESDecrypt(byte[] data, byte[] cryptKey = null, byte[] cryptIV = null)
 {
     System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = EncryptHelper.CreateDESCrypto();
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(cryptKey, cryptIV), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(data, 0, data.Length);
     cryptoStream.FlushFinalBlock();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 48
0
 public static byte[] smethod_12(byte[] byte_0, string string_0, string string_1)
 {
     byte[] bytes  = System.Text.Encoding.ASCII.GetBytes(string_1);
     byte[] bytes2 = System.Text.Encoding.ASCII.GetBytes(string_0);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.RC2CryptoServiceProvider rC2CryptoServiceProvider = new System.Security.Cryptography.RC2CryptoServiceProvider();
     System.Security.Cryptography.CryptoStream             cryptoStream             = new System.Security.Cryptography.CryptoStream(memoryStream, rC2CryptoServiceProvider.CreateEncryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.FlushFinalBlock();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 49
0
 public string Decrypt()
 {
     System.Security.Cryptography.ICryptoTransform transform = this._mCSP.CreateDecryptor(this._mCSP.Key, this._mCSP.IV);
     byte[] array = System.Convert.FromBase64String(this._mstrEncryptedString);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, transform, System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(array, 0, array.Length);
     cryptoStream.FlushFinalBlock();
     cryptoStream.Close();
     this._mstrOriginalString = System.Text.Encoding.Unicode.GetString(memoryStream.ToArray());
     return(this._mstrOriginalString);
 }
Ejemplo n.º 50
0
 public static byte[] smethod_0(byte[] byte_0, string string_0)
 {
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0);
     byte[] rgbIV = bytes;
     System.Array.Resize <byte>(ref byte_0, byte_0.Length + 1);
     byte_0[byte_0.Length - 1] = (byte)new System.Random().Next(0, 255);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.RC2CryptoServiceProvider rC2CryptoServiceProvider = new System.Security.Cryptography.RC2CryptoServiceProvider();
     System.Security.Cryptography.CryptoStream             cryptoStream             = new System.Security.Cryptography.CryptoStream(memoryStream, rC2CryptoServiceProvider.CreateEncryptor(bytes, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.FlushFinalBlock();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 51
0
 public static string Encrypt(string encryptString, string encryptKey)
 {
     encryptKey = TextUtility.CutLeft(encryptKey, 8);
     encryptKey = encryptKey.PadRight(8, ' ');
     byte[] bytes  = System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
     byte[] keys   = DES.Keys;
     byte[] bytes2 = System.Text.Encoding.UTF8.GetBytes(encryptString);
     System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, keys), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(bytes2, 0, bytes2.Length);
     cryptoStream.FlushFinalBlock();
     return(System.Convert.ToBase64String(memoryStream.ToArray()));
 }
Ejemplo n.º 52
0
 //加密的代码:
 /// <summary>
 /// DES加密
 /// </summary>
 /// <param name="str">要加密字符串</param>
 /// <returns>返回加密后字符串</returns>
 public static String Encrypt_DES(String str)
 {
     System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
     Byte[] inputByteArray = System.Text.Encoding.Default.GetBytes(str);
     des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strDesKey, "md5").Substring(0, 8)); //加密对象的密钥
     des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strDesKey, "md5").Substring(0, 8)); //加密对象的偏移量,此两个值重要不能修改
     System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     foreach (Byte b in ms.ToArray())
     {
         sb.AppendFormat("{0:X2}", b);
     }
     return(sb.ToString());
 }
Ejemplo n.º 53
0
        private const string IV_64  = "5C83B05C"; //"#CoolSc#";
        public static string EncodeStatic(string data)
        {
            byte[] bytes  = System.Text.Encoding.ASCII.GetBytes(KEY_64);
            byte[] bytes2 = System.Text.Encoding.ASCII.GetBytes(IV_64);
            System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
            int keySize = dESCryptoServiceProvider.KeySize;

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, bytes2), System.Security.Cryptography.CryptoStreamMode.Write);
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(cryptoStream);
            streamWriter.Write(data);
            streamWriter.Flush();
            cryptoStream.FlushFinalBlock();
            streamWriter.Flush();
            return(System.Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
        }
Ejemplo n.º 54
0
 public static string Encriptar(string valor)
 {
     try
     {
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         byte[] inputByteArray        = System.Text.Encoding.UTF8.GetBytes(valor);
         System.IO.MemoryStream ms    = new System.IO.MemoryStream();
         System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(key, IV), System.Security.Cryptography.CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         return(Convert.ToBase64String(ms.ToArray()));
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
Ejemplo n.º 55
0
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="str">要解密字符串</param>
        /// <returns>返回解密后字符串</returns>
        public static String Decrypt_DES_Old(String str)
        {
            System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
            Int32 x;

            Byte[] inputByteArray = new Byte[str.Length / 2];
            for (x = 0; x < str.Length / 2; x++)
            {
                inputByteArray[x] = (Byte)(Convert.ToInt32(str.Substring(x * 2, 2), 16));
            }
            des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
            des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strDesKey);
            System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return(System.Text.Encoding.Default.GetString(ms.ToArray()));
        }
        public void ExampleScript()
        {
            // Turn input string into a byte array.
            var input = System.Text.Encoding.Unicode.GetBytes("Plain Text");

            // Create an instance of the Rijndael class.
            System.Security.Cryptography.RijndaelManaged cipher;
            cipher = new System.Security.Cryptography.RijndaelManaged();
            // Calculate salt bytes to make it harder to guess key by using a dictionary attack.
            var password = System.Text.Encoding.UTF8.GetBytes("password");
            var hmac     = new System.Security.Cryptography.HMACSHA1(password);
            var salt     = hmac.ComputeHash(password);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key     = secretKey.GetBytes(32);
            var iv      = secretKey.GetBytes(16);
            var cryptor = cipher.CreateEncryptor(key, iv);
            // Create new Input.
            var inputBuffer = new System.Byte[input.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            //cryptoStream.Close();
            // Convert encrypted data into a base64-encoded string.
            var base64String = System.Convert.ToBase64String(outputBuffer);
            // base64String = laFf3eKu9tzB2XksJjd8EVM3PA9O30wz0Y+X3nyelW4=
        }
Ejemplo n.º 57
0
 /// <summary>
 /// DES多重加密
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static String Encrypt_DES(String str)
 {
     System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
     Byte[] inputByteArray = System.Text.Encoding.Unicode.GetBytes(str);
     des.Key = Convert.FromBase64String("uwniTq6wza2nU3/cCVxTScpjhlv1Tl5s");
     des.IV  = Convert.FromBase64String("ld6Et92CmbQ=");
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     foreach (Byte b in ms.ToArray())
     {
         sb.AppendFormat("{0:X2}", b);
     }
     return(sb.ToString());
 }
Ejemplo n.º 58
0
        byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt, bool fips)
        {
            /// <summary>Encrypt by using AES-256 algorithm.</summary>
            // Create an instance of the Rijndael class.
            var cipher = fips
                                ? new System.Security.Cryptography.AesCryptoServiceProvider() as SymmetricAlgorithm
                                : new System.Security.Cryptography.RijndaelManaged();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = encrypt
                                ? cipher.CreateEncryptor(key, iv)
                                : cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new byte[dataBytes.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            cryptoStream.Close();
            return(outputBuffer);
        }
Ejemplo n.º 59
0
        public static string Encrypt3DES(string a_strString, string a_strKey, string a_strIV)
        {
            System.Security.Cryptography.TripleDESCryptoServiceProvider des = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(a_strString);
            //des.Key = System.Text.Encoding.UTF8.GetBytes(a_strKey);
            byte[] _key = System.Text.Encoding.UTF8.GetBytes(a_strKey);
            //des.IV = System.Text.Encoding.UTF8.GetBytes(a_strIV);
            //des.IV = Keys;
            des.Mode    = System.Security.Cryptography.CipherMode.CBC;
            des.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            //System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(cs);
            //swEncrypt.WriteLine(a_strString);
            //swEncrypt.Close();

            //把内存流转换成字节数组,内存流现在已经是密文了
            byte[] bytesCipher = ms.ToArray();
            //内存流关闭

            string base64String = System.Convert.ToBase64String(bytesCipher);

            //string by = "";
            //foreach (byte b in bytesCipher)
            //{
            //    by += b.ToString() + " ";
            //}
            //SbeLogger.info("【3DESBytes】" + by);
            //byte[] FromBase64String = Convert.FromBase64String(base64String);
            //ms = new MemoryStream(FromBase64String);
            //cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read);
            //StreamReader sr = new StreamReader(cs);
            ////输出解密后的内容
            //string DecryptString = sr.ReadLine();

            //加密流关闭
            cs.Close();
            des.Clear();
            ms.Close();


            return(base64String);
        }
Ejemplo n.º 60
0
 public static string DecodeStatic(string pToDecrypt, string sKey = KEY_64)
 {
     System.Security.Cryptography.DESCryptoServiceProvider dESCryptoServiceProvider = new System.Security.Cryptography.DESCryptoServiceProvider();
     byte[] array = new byte[pToDecrypt.Length / 2];
     for (int i = 0; i < pToDecrypt.Length / 2; i++)
     {
         int num = System.Convert.ToInt32(pToDecrypt.Substring(i * 2, 2), 16);
         array[i] = (byte)num;
     }
     sKey = FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8);
     dESCryptoServiceProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey);
     dESCryptoServiceProvider.IV  = System.Text.Encoding.ASCII.GetBytes(sKey);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(array, 0, array.Length);
     cryptoStream.FlushFinalBlock();
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     return(HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString(memoryStream.ToArray())));
 }