Write() public method

public Write ( byte buffer, int offset, int count ) : void
buffer byte
offset int
count int
return void
Ejemplo n.º 1
1
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV, CipherMode cipherMode, PaddingMode paddingMode)
        {
            // Create a MemoryStream that is going to accept the
            // decrypted bytes
            MemoryStream ms = new MemoryStream();

            // Create a symmetric algorithm.
            // We are going to use Rijndael because it is strong and
            // available on all platforms.
            // You can use other algorithms, to do so substitute the next
            // line with something like
            //     TripleDES alg = TripleDES.Create();

            Rijndael alg = Rijndael.Create();

            // Now set the key and the IV.
            // We need the IV (Initialization Vector) because the algorithm
            // is operating in its default
            // mode called CBC (Cipher Block Chaining). The IV is XORed with
            // the first block (8 byte)
            // of the data after it is decrypted, and then each decrypted
            // block is XORed with the previous
            // cipher block. This is done to make encryption more secure.
            // There is also a mode called ECB which does not need an IV,
            // but it is much less secure.

            alg.Mode = cipherMode;
            alg.Padding = paddingMode;
            alg.Key = Key;
            alg.IV = IV;

            // Create a CryptoStream through which we are going to be
            // pumping our data.
            // CryptoStreamMode.Write means that we are going to be
            // writing data to the stream
            // and the output will be written in the MemoryStream
            // we have provided.

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

            // Write the data and make it do the decryption
            cs.Write(cipherData, 0, cipherData.Length);

            // Close the crypto stream (or do FlushFinalBlock).
            // This will tell it that we have done our decryption
            // and there is no more data coming in,
            // and it is now a good time to remove the padding
            // and finalize the decryption process.

            cs.Close();

            // Now get the decrypted data from the MemoryStream.
            // Some people make a mistake of using GetBuffer() here,
            // which is not the right way.

            byte[] decryptedData = ms.ToArray();

            return decryptedData;
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
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.º 4
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.º 5
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.º 6
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.º 7
1
        public byte[] Encrypt(byte[] block)
        {
            ICryptoTransform enc = null;
            Aes.Mode = CipherMode.CBC;
            Aes.Key = key;
            Aes.GenerateIV();
            Console.WriteLine("Key: {0} IV: {1}", CNetwork.ByteArrayToString(Aes.Key), CNetwork.ByteArrayToString(Aes.IV));

            CryptoStream cstream = null;
            MemoryStream mem = null;
            byte[] toEncrypt = null;

            try
            {
                cstream = null;
                mem = new MemoryStream();
                toEncrypt = block;
                enc = Aes.CreateEncryptor();
                cstream = new CryptoStream(mem, enc, CryptoStreamMode.Write);
                cstream.Write(toEncrypt, 0, toEncrypt.Length);
            }
            finally
            {
                if (cstream != null)
                    Aes.Clear();
                cstream.Close();
            }

            Console.WriteLine(CNetwork.ByteArrayToString(mem.ToArray()));

            return mem.ToArray();
        }
Ejemplo n.º 8
1
        public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }
Ejemplo n.º 9
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 "";
        }
 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.º 11
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (Aes aes =Aes.Create())
//            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
Ejemplo n.º 12
0
        public void When_performing_the_standard_test()
        {
            // Adapted from: https://code.google.com/p/smhasher/source/browse/trunk/KeysetTest.cpp#13
            const uint Murmur3_x64_128 = 0x6384BA69u;

            using (var hash = new Murmur3())
            // Also test that Merkle incremental hashing works.
            using (var cs = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write))
            {
                var key = new byte[256];

                for (var i = 0; i < 256; i++)
                {
                    key[i] = (byte)i;
                    using (var m = new Murmur3(256 - i))
                    {
                        var computed = m.ComputeHash(key, 0, i);
                        // Also check that your implementation deals with incomplete
                        // blocks.
                        cs.Write(computed, 0, 5);
                        cs.Write(computed, 5, computed.Length - 5);
                    }
                }

                cs.FlushFinalBlock();
                var final = hash.Hash;
                var verification = ((uint)final[0]) | ((uint)final[1] << 8) | ((uint)final[2] << 16) | ((uint)final[3] << 24);
                Assert.Equal(Murmur3_x64_128, verification);
            }
        }
Ejemplo n.º 13
0
    internal static void Decrypt(string fileIn, string fileOut)
    {
        System.IO.FileStream fsIn  = new System.IO.FileStream(fileIn, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.FileStream fsOut = new System.IO.FileStream(fileOut, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

        System.Security.Cryptography.PasswordDeriveBytes pdb = new System.Security.Cryptography.PasswordDeriveBytes(Password,
                                                                                                                    new byte[] { 0x49, 0x49, 0x35, 0x6e, 0x76, 0x4d,
                                                                                                                                 0x65, 0x64, 0x76, 0x76, 0x64, 0x65, 0x76 });
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV  = pdb.GetBytes(16);

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

        int bufferLen = 4096;

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

        do
        {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // Decrypt it
            cs.Write(buffer, 0, bytesRead);
        } while (bytesRead != 0);
        cs.Close();
        fsIn.Close();
    }
Ejemplo n.º 14
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);
    }
Ejemplo n.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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);
                }
 /// <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.º 21
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());
    }
Ejemplo n.º 22
0
        /// <summary>
        /// 加密
        /// </summary>
        public static string AESEncrypt(string input)
        {
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            // AesManaged - 高级加密标准(AES) 对称算法的管理类
            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged( );
            // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)
            // 通过 密码 和 salt 派生密钥
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
            System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor( );
            // 加密后的输出流
            System.IO.MemoryStream encryptStream = new System.IO.MemoryStream( );
            // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
                                                                      (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
            encryptor.Write(data, 0, data.Length);
            encryptor.Close( );
            // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
            string encryptedString = Convert.ToBase64String(encryptStream.ToArray( ));

            return(encryptedString);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 解密
        /// </summary>
        public static string AESDecrypt(string input)
        {
            byte[] encryptBytes = Convert.FromBase64String(input);
            byte[] salt         = Encoding.UTF8.GetBytes(saltValue);
            System.Security.Cryptography.AesManaged         aes = new System.Security.Cryptography.AesManaged( );
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
            System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor( );
            // 解密后的输出流
            System.IO.MemoryStream decryptStream = new System.IO.MemoryStream( );

            // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream(
                decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
            // 将一个字节序列写入当前 CryptoStream (完成解密的过程)
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Close( );

            // 将解密后所得到的流转换为字符串
            byte[] decryptBytes    = decryptStream.ToArray( );
            string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);

            return(decryptedString);
        }
Ejemplo n.º 24
0
 public string Encrypt(string clearText, string EncryptionKey)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
     using (Aes encryptor = Aes.Create())
     {
         System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.Rfc2898DeriveBytes(EncryptionKey, new byte[]
         {
             73,
             118,
             97,
             110,
             32,
             77,
             101,
             100,
             118,
             101,
             100,
             101,
             118
         });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 cs.Write(clearBytes, 0, clearBytes.Length);
                 cs.Close();
             }
             clearText = System.Convert.ToBase64String(ms.ToArray());
         }
     }
     return(clearText);
 }
Ejemplo n.º 25
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.º 26
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.º 27
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.º 28
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.º 29
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.º 30
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);
            }
        }
        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.º 32
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.º 33
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;
        }
        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.º 35
0
        /// <summary>
        /// Encrypts the specified clear data.
        /// </summary>
        /// <param name="clearData">The clear data.</param>
        /// <param name="Key">The key.</param>
        /// <param name="IV">The IV.</param>
        /// <returns></returns>
        private static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
        {
            Rijndael algorithm = Rijndael.Create();
            algorithm.Key = Key;
            algorithm.IV = IV;

            if (ConfigurationManager.AppSettings["EncryptionBlockSize"] != null)
            {
                int blocksize = int.Parse(ConfigurationManager.AppSettings["EncryptionBlockSize"], NumberStyles.Integer, CultureInfo.InvariantCulture);
                if (blocksize != 128 && blocksize != 192 && blocksize != 256)
                    throw new ConfigurationErrorsException("Please provide a block size. Supported block size is: 128, 192, or 256 bits.");

                algorithm.BlockSize = blocksize;
            }
            else
            {
                algorithm.BlockSize = 128;
            }

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

            cryptoStream.Write(clearData, 0, clearData.Length);
            cryptoStream.Close();

            byte[] encryptedData = memoryStream.ToArray();
            return encryptedData;
        }
Ejemplo n.º 36
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.º 37
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.º 38
0
        private void encryptFile(string inputFile, string cryptFile)
        {
            FileStream fsCrypt = null;
            CryptoStream cryptStream = null;

            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(TPW);
                fsCrypt = new FileStream(cryptFile, FileMode.Create);
                RijndaelManaged RMCrypto = new RijndaelManaged();
                cryptStream = new CryptoStream(fsCrypt,
                                                RMCrypto.CreateEncryptor(key, key),
                                                CryptoStreamMode.Write);

                byte[] inBytes = File.ReadAllBytes(inputFile);
                cryptStream.Write(inBytes, 0, inBytes.Length);

            }
            finally
            {
                if (cryptStream != null)
                    cryptStream.Close();

                if ( fsCrypt != null )
                    fsCrypt.Close();
            }
        }
Ejemplo n.º 39
0
        public void EncryptFile(string sInputFilename,string sOutputFilename,string sKey)
        {
            var fsInput = new FileStream(sInputFilename,
                FileMode.Open,
                FileAccess.Read);

            var fsEncrypted = new FileStream(sOutputFilename,
                            FileMode.Create,
                            FileAccess.Write);
            var DES = new DESCryptoServiceProvider();
            
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            ICryptoTransform desencrypt = DES.CreateEncryptor();
            var cryptostream = new CryptoStream(fsEncrypted,
                                desencrypt,
                                CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length - 1];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();

        }
Ejemplo n.º 40
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.º 41
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;
            }
        }
Ejemplo n.º 42
0
 public static byte[] smethod_3(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.Rijndael           rijndael           = System.Security.Cryptography.Rijndael.Create();
     System.Security.Cryptography.Rfc2898DeriveBytes rfc2898DeriveBytes = new System.Security.Cryptography.Rfc2898DeriveBytes(string_0, new byte[]
     {
         38,
         220,
         255,
         0,
         173,
         237,
         122,
         238,
         197,
         254,
         7,
         175,
         77,
         8,
         34,
         60
     });
     rijndael.Key = rfc2898DeriveBytes.GetBytes(32);
     rijndael.IV  = rfc2898DeriveBytes.GetBytes(16);
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
        /// <summary>
        /// Encrypt/Decrypt with Write method.
        /// </summary>
        /// <param name="cryptor"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        private byte[] CipherStreamWrite(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;
            // 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 cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, System.Security.Cryptography.CryptoStreamMode.Write);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            outputBuffer = stream.ToArray();
            // Close both streams.
            stream.Close();
            //cryptoStream.Close();
            WriteEnc(inputBuffer, outputBuffer);
            return(outputBuffer);
        }
        public msgMaid cooking(byte[] otama)
        {
            //メイドオブジェクト
            msgMaid m = new msgMaid();

            //DESC
            TripleDESCryptoServiceProvider frill = new TripleDESCryptoServiceProvider();

            // Triple DES のサービス プロバイダを生成します
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            //取得
            m.houshinokokoro = frill.Key;
            m.zettaifukujyu = frill.IV;

            // source 配列から cryptData 配列へ変換
            // 文字列を byte 配列に変換します
            //byte[] source = Encoding.Unicode.GetBytes(cachusha);

            // 入出力用のストリームを生成します
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(m.houshinokokoro, m.zettaifukujyu), CryptoStreamMode.Write))
                {
                    // ストリームに暗号化するデータを書き込みます
                    cs.Write(otama, 0, otama.Length);
                }

                // 暗号化されたデータを byte 配列で取得します
                m.zenryokushugo = ms.ToArray();
            }

            // byte 配列を文字列に変換して表示します
            return m;
        }
Ejemplo n.º 45
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.º 46
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.º 47
0
        public static string Decrypt(string encryptedText)
        {
            RegistryKey registryKey =
                Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\PbsEncryptionKey");
            var password = (string)registryKey.GetValue("Key");
            var passwordDerivedBytes = new PasswordDeriveBytes(password, _salt);
            byte[] encryptedTextBytes = Convert.FromBase64String(encryptedText);

            using (var memoryStream = new MemoryStream())
            {
                using (var rijndael = Rijndael.Create())
                {
                    using (
                        var cryptoTransform = rijndael.CreateDecryptor(passwordDerivedBytes.GetBytes(32), 
                            passwordDerivedBytes.GetBytes(16)))
                    {
                        using (
                            var cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
                                CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
                            cryptoStream.Close();
                            return Encoding.Unicode.GetString(memoryStream.ToArray());
                        }
                    }
                }
            }
        }
Ejemplo n.º 48
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;
 }
 /// <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.º 50
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.º 51
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.º 52
0
    /// <summary>
    /// 加密文件
    /// </summary>
    public static void EncryptFile(string Value, string OuputFileName)
    {
        try
        {
            // Must be 64 bits, 8 bytes.
            // Distribute this key to the user who will decrypt this file.
            //Get the Key for the file to Encrypt.
            string sKey = GenerateKey();

            byte[] b = ASCIIEncoding.ASCII.GetBytes(Value);

            System.IO.FileStream fsEncrypted = new System.IO.FileStream(OuputFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

            System.Security.Cryptography.DESCryptoServiceProvider DES = new System.Security.Cryptography.DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV  = ASCIIEncoding.ASCII.GetBytes(sKey);

            System.Security.Cryptography.ICryptoTransform desencrypt = DES.CreateEncryptor();
            System.Security.Cryptography.CryptoStream     cs         = new System.Security.Cryptography.CryptoStream(fsEncrypted, desencrypt, System.Security.Cryptography.CryptoStreamMode.Write);

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

            fsEncrypted.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Ejemplo n.º 53
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.º 54
0
 public static byte[] smethod_9(byte[] byte_0, string string_0)
 {
     System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.SymmetricAlgorithm.Create();
     System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(string_0);
     byte[] rgbIV = bytes;
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(bytes, rgbIV), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(byte_0, 0, byte_0.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 55
0
 private static byte[] AES_Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
 {
     System.IO.MemoryStream memoryStream            = new System.IO.MemoryStream();
     System.Security.Cryptography.Rijndael rijndael = System.Security.Cryptography.Rijndael.Create();
     rijndael.Key = Key;
     rijndael.IV  = IV;
     System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndael.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cryptoStream.Write(cipherData, 0, cipherData.Length);
     cryptoStream.Close();
     return(memoryStream.ToArray());
 }
Ejemplo n.º 56
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.º 57
0
        private static void Main(string[] args)
        {
            string action = "DECRYPT", filePath = "";

            if (args.Length < 1 || args[0] == "/?")
            {
                Console.Error.WriteLine("Aes256 Encryption/Decryption.");
                Console.Error.WriteLine();
                Console.Error.WriteLine("crypt.exe [-e] <filepath>"); // args[0] args[1]
                Console.Error.WriteLine("  -e         encrypting the file, default is decrypting");
                Console.Error.WriteLine("  <filepath> path of file to be encrypted or decrypted");
                Console.Error.WriteLine();
                return;
            }
            else if (args.Length > 1 && args[0] == "-e")
            {
                action   = "ENCRYPT";
                filePath = args[1];
            }
            else
            {
                filePath = args[0];
            }

            // [ https://www.codeproject.com/Questions/562372/Theplusinputplusdataplusisplusnotplusapluscomplete ]
            FileStream reader = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            FileStream writer = new FileStream(filePath + ".out", FileMode.OpenOrCreate, FileAccess.Write);

            using (var aes = getAes256Provider()) {
                using (ICryptoTransform cryptor = (action == "DECRYPT") ? aes.CreateDecryptor(aes.Key, aes.IV) : aes.CreateEncryptor(aes.Key, aes.IV)) {
                    //Create a Crypt Stream using the encryptor/decryptor created above
                    System.Security.Cryptography.CryptoStream cryptoStream
                        = new System.Security.Cryptography.CryptoStream(writer, cryptor, CryptoStreamMode.Write);

                    byte[] bites      = new byte[1024]; //Stores 1 KB
                    Int32  bitesRead  = 0;              //Number of Bytes read
                    Int64  totalBites = 0;              //Total Number of Bytes read

                    //Loop through the entire file reading 1 kb at a time
                    while (!(totalBites >= reader.Length))
                    {
                        bitesRead = reader.Read(bites, 0, 1024); //Read the bytes from the input file.
                        cryptoStream.Write(bites, 0, bitesRead); //Write the encrypted bytes to the output file.
                        totalBites += bitesRead;
                    }
                    cryptoStream.Close();  cryptoStream.Dispose();
                    cryptor.Dispose();
                }
            }
            //Close and release streams:
            reader.Close();  reader.Dispose();
            writer.Close();  writer.Dispose();
        }
Ejemplo n.º 58
0
 // hmacSHA1加密方法
 public static string HmacSha1Sign(string text, string key)
 {
     byte[] byteData = Encoding.UTF8.GetBytes(text);
     byte[] byteKey  = Encoding.UTF8.GetBytes(key);
     System.Security.Cryptography.HMACSHA1     hmac = new System.Security.Cryptography.HMACSHA1(byteKey);
     System.Security.Cryptography.CryptoStream cs   = new System.Security.Cryptography.CryptoStream(Stream.Null,
                                                                                                    hmac,
                                                                                                    System.Security.Cryptography.CryptoStreamMode.Write);
     cs.Write(byteData, 0, byteData.Length);
     cs.Close();
     return(Convert.ToBase64String(hmac.Hash));
 }
Ejemplo n.º 59
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.º 60
0
    internal static byte[] MD5Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
    {
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.Security.Cryptography.Rijndael alg = System.Security.Cryptography.Rijndael.Create();
        alg.Key = Key;
        alg.IV  = IV;

        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, alg.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        cs.Write(cipherData, 0, cipherData.Length);
        cs.Close();
        byte[] decryptedData = ms.ToArray();
        return(decryptedData);
    }