Ejemplo n.º 1
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.º 2
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.º 3
1
 public string Decrypt(string strEncryptedText)
 {
     if (strEncryptedText == null || strEncryptedText.Equals(""))
         return strEncryptedText;
     string strDecryptedText = null;
     RijndaelManaged rijndael = new RijndaelManaged();
     ICryptoTransform decryptor = rijndael.CreateDecryptor(Key, IV);
     byte[] byteEncryptedText = Convert.FromBase64String(strEncryptedText);
     MemoryStream memStream = new MemoryStream(byteEncryptedText);
     CryptoStream decryptStream = null;
     try
     {
         decryptStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read);
         byte[] byteDecryptedText = new byte[byteEncryptedText.Length];
         int decryptedByteCount = decryptStream.Read(byteDecryptedText, 0, byteDecryptedText.Length);
         strDecryptedText = Encoding.UTF8.GetString(byteDecryptedText, 0, decryptedByteCount);
     }
     finally
     {
         if (rijndael != null) rijndael.Clear();
         if (decryptor != null) decryptor.Dispose();
         if (memStream != null) memStream.Close();
         if (decryptStream != null) decryptStream.Close();
     }
     if (UseSalt)
         strDecryptedText = strDecryptedText.Substring(8);
     return strDecryptedText;
 }
Ejemplo n.º 4
1
 protected static string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
Ejemplo n.º 5
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.º 6
1
        /// <summary>
        /// AES解密(无向量)
        /// </summary>
        /// <param name="encryptedBytes">被加密的明文</param>
        /// <param name="key">密钥</param>
        /// <returns>明文</returns>
        public static string AESDecryptWithoutVector(String Data, String Key)
        {
            Byte[] encryptedBytes = Convert.FromBase64String(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

            MemoryStream mStream = new MemoryStream(encryptedBytes);
            //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
            //mStream.Seek( 0, SeekOrigin.Begin );
            RijndaelManaged aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key = bKey;
            //aes.IV = _iV;
            CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                byte[] tmp = new byte[encryptedBytes.Length + 32];
                int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
                byte[] ret = new byte[len];
                Array.Copy(tmp, 0, ret, 0, len);
                return Encoding.UTF8.GetString(ret);
            }
            finally
            {
                cryptoStream.Close();
                mStream.Close();
                aes.Clear();
            }
        }
Ejemplo n.º 7
1
        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            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 decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                {
                    using (var memoryStream = new MemoryStream(cipherTextBytes))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var plainTextBytes = new byte[cipherTextBytes.Length];
                            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                            memoryStream.Close();
                            cryptoStream.Close();
                            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                        }
                    }
                }
            }
        }
Ejemplo n.º 8
1
        public static void DecryptFile(string strKey, string pathCypheredTextFile, string pathPlainTextFile)
        {
            // Place la clé de déchiffrement dans un tableau d'octets
            byte[] key = GenerateAlgotihmInputs(strKey);

            // Place le vecteur d'initialisation dans un tableau d'octets
            byte[] iv = GenerateAlgotihmInputs(strKey);

            // Filestream of the new file that will be decrypted.
            Directory.CreateDirectory(Directory.GetParent(pathPlainTextFile).FullName);
            FileStream fsCrypt = new FileStream(pathPlainTextFile, FileMode.Create);

            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.Mode = CipherMode.CBC;
            rijndael.Key = key;
            rijndael.IV = iv;

            ICryptoTransform aesDecryptor = rijndael.CreateDecryptor();

            CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write);

            // FileStream of the file that is currently encrypted.
            FileStream fsIn = new FileStream(pathCypheredTextFile, FileMode.OpenOrCreate);

            int data;

            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);
            cs.Close();
            fsIn.Close();
            fsCrypt.Close();
        }
Ejemplo n.º 9
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);
    }
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="cipherText">Text to be decrypted</param>
        /// <param name="password">Password to decrypt with</param>
        /// <param name="salt">Salt to decrypt with</param>
        /// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="passwordIterations">Number of iterations to do. The number of times the algorithm is run on the text. </param>
        /// <param name="initialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="keySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string cipherText, string password, string salt = "69ad1bfbd6605f3f6a3011460cdfb9db7757e0f9", string hashAlgorithm = "SHA1", int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY", int keySize = 256)
        {
            if (string.IsNullOrEmpty(cipherText))
                return "";

            byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
            var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
            byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
            var symmetricKey = new RijndaelManaged {Mode = CipherMode.CBC};
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int byteCount;

            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
            {
                using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
                    {
                        byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }
            symmetricKey.Clear();

            return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
        }
Ejemplo n.º 11
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.º 12
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.º 13
0
		public override void Load()
		{
			if ((File.Exists(DataFilename)) && (new FileInfo(DataFilename).Length != 0))
			{
				try
				{
					using (Stream stream = File.Open(DataFilename, FileMode.Open))
					using (DESCryptoServiceProvider crypt = new DESCryptoServiceProvider())
					{
						BinaryFormatter bin = new BinaryFormatter();


						crypt.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
						crypt.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");

						CryptoStream crStream = new CryptoStream(stream,
	crypt.CreateDecryptor(), CryptoStreamMode.Read);

						_list = (List<MB>)bin.Deserialize(crStream);

						crStream.Close();
					}
				}
				catch (Exception)
				{
				}
			}
		}
Ejemplo n.º 14
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.º 15
0
        public string Decrypt(string encrypted_str)
        {
            Twofish fish = new Twofish();

            fish.Mode = CipherMode.ECB;

            byte[] plainText = {};

            //create Twofish Decryptor from our twofish instance
            ICryptoTransform decrypt = fish.CreateDecryptor(key, plainText);

            System.IO.MemoryStream msD = new System.IO.MemoryStream();

            //create crypto stream set to read and do a Twofish decryption transform on incoming bytes
            CryptoStream cryptostreamDecr = new CryptoStream(msD, decrypt, CryptoStreamMode.Write);

            byte[] bytOut = GetBytes(encrypted_str);

            //write out Twofish encrypted stream
            cryptostreamDecr.Write(bytOut, 0, bytOut.Length);

            cryptostreamDecr.Close();

            byte[] bytOutD = msD.GetBuffer();

            return GetString(bytOutD);
        }
Ejemplo n.º 16
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.º 17
0
 public byte[] digest()
 {
     sc.Close();
     byte[] res = md.Hash;
     init();
     return(res);
 }
Ejemplo n.º 18
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.º 19
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.º 20
0
        private static string CryKey = "Xky_Lq_Py_Hu_Lp_Jhj_Zxt";//密钥
        /// <summary>
        /// 加密字符串
        /// </summary>
        public static string Encrypt(string PlainText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV  = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(encStream);
            sw.WriteLine(PlainText);
            sw.Close();
            encStream.Close();

            byte[] buffer = ms.ToArray();
            ms.Close();

            string s = "";

            for (int i = 0; i < buffer.Length; i++)
            {
                s += buffer[i].ToString("X2");
            }
            return(s);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 解密字符串
        /// </summary>
        public static string Decrypt(string CypherText)
        {
            System.Security.Cryptography.DESCryptoServiceProvider key = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] bk = System.Text.Encoding.Unicode.GetBytes(CryKey);
            byte[] bs = new byte[8];
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = bk[i];
            }
            key.Key = bs;
            key.IV  = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

            byte[] bc = new byte[CypherText.Length / 2];
            for (int i = 0; i < bc.Length; i++)
            {
                try
                {
                    bc[i] = Convert.ToByte(CypherText.Substring(2 * i, 2), 16);
                }
                catch { }
            }
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bc);
            System.Security.Cryptography.CryptoStream encStream = new System.Security.Cryptography.CryptoStream(ms, key.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);
            System.IO.StreamReader sr = new System.IO.StreamReader(encStream);

            string val = sr.ReadLine();

            sr.Close();
            encStream.Close();
            ms.Close();

            return(val);
        }
Ejemplo n.º 22
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);
            des.IV      = System.Text.Encoding.UTF8.GetBytes(a_strIV);
            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);
            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);

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


            return(base64String);
        }
Ejemplo n.º 23
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.º 24
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.º 25
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();
    }
 /// <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.º 27
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.º 28
0
    public static void Main()
    {
        //chave secreta
        byte[] Key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
        //vetor de inicialização
        byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

        //Stream de memória
        IO.MemoryStream memstream = new IO.MemoryStream(15);
        //Stream de criptografia
        CP.RC2CryptoServiceProvider provider  = new CP.RC2CryptoServiceProvider();
        CP.ICryptoTransform         transform = provider.CreateEncryptor(Key, IV);
        CP.CryptoStreamMode         mode      = CP.CryptoStreamMode.Write;
        CP.CryptoStream             stream    = new CP.CryptoStream(memstream, transform, mode);

        //Lê cada caracter da string
        foreach (char ch in "Isto é um teste")
        {
            stream.WriteByte((Convert.ToByte(ch)));
        }

        int c;

        //Reposiciona o ponteiro para leitura
        memstream.Position = c = 0; //técnica não trivial, mas válida

        while ((c = memstream.ReadByte()) != -1)
        {
            Console.Write((char)c);
        }

        stream.Close();    //Libera a stream (crypto)
        memstream.Close(); //Libera a stream (mem)
    }
        /// <summary>
        /// A simply rijndael aes encryption, can be used to store passwords
        /// </summary>
        /// <param name="ClearText">the string to call upon</param>
        /// <returns>an encryped string in base64 form</returns>
        public static string Encrypt(this string ClearText)
        {
            string returnValue = ClearText;
            try
            {
                byte[] clearTextBytes = Encoding.ASCII.GetBytes(ClearText);
                SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV);
                    byte[] key = Encoding.ASCII.GetBytes(KEY);
                    CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

                    cs.Write(clearTextBytes, 0, clearTextBytes.Length);

                    cs.Close();
                    returnValue = Convert.ToBase64String(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                LOG.ErrorFormat("Error encrypting, error: ", ex.Message);
            }
            return returnValue;
        }
Ejemplo n.º 30
0
        /// <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>
        private 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.º 31
0
 public static byte[] aes_decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes, byte[] iv)
 {
     byte[] decryptedBytes = null;
     using (MemoryStream ms = new MemoryStream())
     {
         using (RijndaelManaged AES = new RijndaelManaged())
         {
             AES.KeySize = 256;
             AES.BlockSize = 128;
             AES.Padding = PaddingMode.ANSIX923;
             AES.Key = passwordBytes;
             AES.IV = iv;
             AES.Mode = CipherMode.CBC;
             try
             {
                 using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                 {
                     cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                     cs.FlushFinalBlock();
                     cs.Close();
                 }
                 decryptedBytes = ms.ToArray();
             }
             catch
             {
                 Console.WriteLine("Error in decryption process");
                 Environment.Exit(1);
             }
         }
     }
     return decryptedBytes;
 }
        public string Decrypt(string CypherText)
        {
            string outText = string.Empty;

            System.Security.Cryptography.CryptoStream myCryptoStream = null;
            try
            {
                System.Byte[]          data      = System.Convert.FromBase64String(CypherText);
                System.IO.MemoryStream memStream = new System.IO.MemoryStream(data.Length);

                myrijManaged.Key = keyByte;
                myrijManaged.IV  = IVByte;
                System.Security.Cryptography.ICryptoTransform myCryptoTransform = myrijManaged.CreateDecryptor();
                myCryptoStream = new System.Security.Cryptography.CryptoStream(memStream, myCryptoTransform, System.Security.Cryptography.CryptoStreamMode.Read);

                memStream.Write(data, 0, data.Length);
                memStream.Position = 0;
                outText            = new System.IO.StreamReader(myCryptoStream).ReadToEnd();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (myCryptoStream != null)
                {
                    myCryptoStream.Close();
                }
            }
            return(outText);
        }
Ejemplo n.º 33
0
        public byte[] Decrypt(byte[] file)
        {
            Twofish fish = new Twofish();

            fish.Mode = CipherMode.ECB;

            byte[] dummy = { };

            //create Twofish Decryptor from our twofish instance
            ICryptoTransform decrypt = fish.CreateDecryptor(key, dummy);

            System.IO.MemoryStream msD = new System.IO.MemoryStream();

            //create crypto stream set to read and do a Twofish decryption transform on incoming bytes
            CryptoStream cryptostreamDecr = new CryptoStream(msD, decrypt, CryptoStreamMode.Write);

            //write out Twofish encrypted stream
            cryptostreamDecr.Write(file, 0, file.Length);

            cryptostreamDecr.Close();

            byte[] buf = msD.GetBuffer();

            // TODO: It might be pretty dangerous to cut on the size of the input buffer
            // because of the padding some bytes might be added. However these bytes will
            // be only zeros (External.Twofish uses Padding.Zero) so zeros should be OK.
            Array.Resize(ref buf, file.Length);
            // We can not remove any other padding bytes because we can not distinuish between
            // bytes added by the crypto algo and bytes belonging to the original unecrtypted file.

            return buf;
        }
        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.º 35
0
		/// <summary>
		/// Decrypts a string
		/// </summary>
		/// <param name="CipherText">Text to be decrypted</param>
		/// <param name="Password">Password to decrypt with</param>
		/// <param name="Salt">Salt to decrypt with</param>
		/// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
		/// <param name="PasswordIterations">Number of iterations to do</param>
		/// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
		/// <param name="KeySize">Can be 128, 192, or 256</param>
		/// <returns>A decrypted byte array in UTF-8 format</returns>
		public static byte[] Decrypt(byte[] CipherText, 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[] PlainTextBytes = new byte[CipherText.Length];
			int ByteCount = 0;
			using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVector))
			{
				using (MemoryStream MemStream = new MemoryStream(CipherText))
				{
					using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
					{

						ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
						MemStream.Close();
						CryptoStream.Close();
					}
				}
			}
			SymmetricKey.Clear();
			byte[] decrypted = new byte[ByteCount];
			Array.Copy(PlainTextBytes, decrypted, ByteCount);
			return decrypted;
		}
Ejemplo n.º 36
0
 public static void DecryptFile(string inputFile, string outputFile, string keyIV)
 {
     byte[] array = new byte[0x20];
     byte[] buffer2 = new byte[0x10];
     HexStringToByteArray(keyIV, array, 0);
     HexStringToByteArray(keyIV, buffer2, 0x40);
     FileStream stream = File.Open(inputFile, System.IO.FileMode.Open);
     FileStream stream2 = File.Open(outputFile, System.IO.FileMode.CreateNew);
     AesManaged managed = new AesManaged {
         Key = array,
         IV = buffer2
     };
     CryptoStream stream3 = new CryptoStream(stream, managed.CreateDecryptor(managed.Key, managed.IV), CryptoStreamMode.Read);
     try
     {
         int num;
         byte[] buffer = new byte[0xa000];
         while ((num = stream3.Read(buffer, 0, buffer.Length)) > 0)
         {
             stream2.Write(buffer, 0, num);
         }
     }
     finally
     {
         stream3.Close();
         stream.Close();
         stream2.Close();
     }
 }
        public static string EncryptString(string _inputString,
           string sKey)
        {
            string sInputFilename = string.Empty;
            string sOutputFilename = string.Empty;
            FileStream fsInput = new FileStream(_inputString,
               FileMode.Open,
               FileAccess.Read);

            FileStream fsEncrypted = new FileStream(sOutputFilename,
               FileMode.Create,
               FileAccess.Write);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted,
               desencrypt,
               CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[_inputString.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();
            return bytearrayinput.ToString();
        }
Ejemplo n.º 38
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.º 39
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();
 }
Ejemplo n.º 40
0
        public static string AESDecrypt(string decryptStr, string decryptKey)
        {
            string result;

            if (string.IsNullOrWhiteSpace(decryptStr))
            {
                result = string.Empty;
            }
            else
            {
                decryptKey = StringHelper.SubString(decryptKey, 32);
                decryptKey = decryptKey.PadRight(32, ' ');
                byte[] array = System.Convert.FromBase64String(decryptStr);
                System.Security.Cryptography.SymmetricAlgorithm symmetricAlgorithm = System.Security.Cryptography.Rijndael.Create();
                symmetricAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(decryptKey);
                symmetricAlgorithm.IV  = SecureHelper._aeskeys;
                byte[] array2 = new byte[array.Length];
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(array))
                {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        cryptoStream.Read(array2, 0, array2.Length);
                        cryptoStream.Close();
                        memoryStream.Close();
                    }
                }
                result = System.Text.Encoding.UTF8.GetString(array2).Replace("\0", "");
            }
            return(result);
        }
        public string mDecryptURLEncode(string EncryptedText)
        {
            string DecryptedText = "";

            System.Security.Cryptography.ICryptoTransform ssd = rc2.CreateDecryptor();

            string sEncrypt = HttpUtility.UrlDecode(EncryptedText);

            byte[] cipherBytes = Convert.FromBase64String(sEncrypt);
            byte[] initialText = null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherBytes))
            {
                using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, ssd, System.Security.Cryptography.CryptoStreamMode.Read))
                {
                    int iCount = opGetArrLength(cipherBytes);
                    initialText = new Byte[cipherBytes.Length];
                    cs.Read(initialText, 0, initialText.Length);
                    cs.Close();
                    cs.Dispose();
                }
                ms.Close();
                ms.Dispose();
            }
            DecryptedText = System.Text.UTF8Encoding.UTF8.GetString(initialText);
            return(DecryptedText = DecryptedText.Replace("\0", ""));
        }
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());
 }
Ejemplo n.º 43
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.º 44
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.º 45
0
 public static byte[] Desencriptar(byte[] mensajeEncriptado,
     SymmetricAlgorithm algoritmo)
 {
     int numeroBytesDesencriptados = 0;
     // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos
     // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa.
     // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor.
     byte[] mensajeDesencriptado = new
     byte[mensajeEncriptado.Length];
     // Crear una ICryptoTransform que puede ser usada para desencriptar datos
     ICryptoTransform desencriptador =
         algoritmo.CreateDecryptor();
     // Procedemos a descifrar el mensaje
     MemoryStream memoryStream = new
     MemoryStream(mensajeEncriptado);
     // Creamos el CryptoStream
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         desencriptador, CryptoStreamMode.Read);
     // Decrypting data and get the count of plain text bytes.
     numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length);
     // Liberamos recursos.
     memoryStream.Close();
     cryptoStream.Close();
     return mensajeDesencriptado;
 }
Ejemplo n.º 46
0
        public static string Decrypt(string cipherText)
        {
            //Get the plain text in a byte array
            System.Byte[] ByteText = System.Convert.FromBase64String(cipherText);

            System.IO.MemoryStream EncStream = new System.IO.MemoryStream(ByteText, 0, ByteText.Length);

            //Get the binary format of the hash key
            System.Byte[] HashKey = Crypter.FormatKey(Crypter.encrypKey);
            System.Byte[] IVector = Crypter.FormatInitializationVector();

            Crypter.encryptionProvider.Key = HashKey;
            Crypter.encryptionProvider.IV  = IVector;

            System.Security.Cryptography.ICryptoTransform Encrypter = Crypter.encryptionProvider.CreateDecryptor();

            //Create a Stream for the transform
            System.Security.Cryptography.CryptoStream Stream = new System.Security.Cryptography.CryptoStream(EncStream, Encrypter, System.Security.Cryptography.CryptoStreamMode.Read);

            System.IO.StreamReader PlainText = null;

            try
            {
                PlainText = new System.IO.StreamReader(Stream);

                return(PlainText.ReadToEnd());
            }
            finally
            {
                PlainText.Close();
                Stream.Close();
            }
        }
Ejemplo n.º 47
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.º 48
0
        private static string DESEncrypt(string MainKey, string strPlain)
        {
            string g_strDESKey = ComputeMD5HashHEX(MainKey + g_strDESIV).Substring(0, 8);
            string p_strReturn = string.Empty;

            try
            {
                string strDESKey   = g_strDESKey;
                string strDESIV    = g_strDESIV;
                byte[] bytesDESKey = System.Text.ASCIIEncoding.ASCII.GetBytes(strDESKey);
                byte[] bytesDESIV  = System.Text.ASCIIEncoding.ASCII.GetBytes(strDESIV);
                System.Security.Cryptography.DESCryptoServiceProvider desEncrypt = new System.Security.Cryptography.DESCryptoServiceProvider();
                System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream();
                System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, desEncrypt.CreateEncryptor(bytesDESKey, bytesDESIV), System.Security.Cryptography.CryptoStreamMode.Write);
                System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt);
                swEncrypt.WriteLine(strPlain);
                swEncrypt.Close();
                csEncrypt.Close();
                byte[] bytesCipher = msEncrypt.ToArray();
                msEncrypt.Close();
                p_strReturn = ConvertByteArrayToHex(bytesCipher);
            }
            catch (System.Exception) { }
            return(p_strReturn);
        }
Ejemplo n.º 49
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="HashAlgorithm">Can be either SHA1 or MD5</param>
 /// <param name="PasswordIterations">Number of iterations to do</param>
 /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="KeySize">Can be 128, 192, or 256</param>
 /// <returns>An encrypted string</returns>
 public static string Encrypt(string PlainText, string Password,
     string Salt = "Kosher", string HashAlgorithm = "SHA1",
     int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
     int KeySize = 256)
 {
     if (string.IsNullOrEmpty(PlainText))
         return "";
     byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
     byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
     byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
     PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
     byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
     RijndaelManaged SymmetricKey = new RijndaelManaged();
     SymmetricKey.Mode = CipherMode.CBC;
     byte[] CipherTextBytes = null;
     using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
     {
         using (MemoryStream MemStream = new MemoryStream())
         {
             using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
             {
                 CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                 CryptoStream.FlushFinalBlock();
                 CipherTextBytes = MemStream.ToArray();
                 MemStream.Close();
                 CryptoStream.Close();
             }
         }
     }
     SymmetricKey.Clear();
     return Convert.ToBase64String(CipherTextBytes);
 }
Ejemplo n.º 50
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.º 51
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.º 52
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();
            }
        }
        public static string Decrypt(string TextToBeDecrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            string Password = "******";
            string DecryptedData;

            try
            {
                byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

                byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

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

                byte[] PlainText = new byte[EncryptedData.Length];
                int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            }
            catch
            {
                DecryptedData = TextToBeDecrypted;
            }
            return DecryptedData;
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="CipherText">Text to be decrypted</param>
        /// <param name="Password">Password to decrypt with</param>
        /// <param name="Salt">Salt to decrypt with</param>
        /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
        /// <param name="PasswordIterations">Number of iterations to do</param>
        /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
        /// <param name="KeySize">Can be 128, 192, or 256</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string CipherText, string Password,
            string Salt = "Kosher", string HashAlgorithm = "SHA1",
            int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
            int KeySize = 256)
        {
            if (string.IsNullOrEmpty(CipherText))
                return "";
            byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
            byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
            byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
            PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
            byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
            RijndaelManaged SymmetricKey = new RijndaelManaged();
            SymmetricKey.Mode = CipherMode.CBC;
            byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
            int ByteCount = 0;
            using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
            {
                using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                {
                    using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                    {

                        ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                        MemStream.Close();
                        CryptoStream.Close();
                    }
                }
            }
            SymmetricKey.Clear();
            return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
        }
Ejemplo n.º 55
0
 public byte[] doFinal()
 {
     //    System.arraycopy(mac.doFinal(), 0, buf, 0, 12);
     //    return buf;
     cs.Close();
     Array.Copy(mentalis_mac.Hash, 0, buf, 0, 12);
     return(buf);
 }
Ejemplo n.º 56
0
 public void doFinal(byte[] buf, int offset)
 {
     cs.Close();
     Array.Copy(mac.Hash, 0, buf, offset, BSIZE);
     byte[] key = (byte[])mac.Key.Clone();
     mac.Clear();
     init(key);
 }
Ejemplo n.º 57
0
        public byte[] doFinal()
        {
            //return mac.doFinal();
            cs.Close();
            byte[] result = mentalis_mac.Hash;
            byte[] key    = mentalis_mac.Key;
            mentalis_mac.Clear();
            init(key);

            return(result);
        }
Ejemplo n.º 58
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.º 59
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.º 60
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();
        }