CreateDecryptor() public method

public CreateDecryptor ( ) : ICryptoTransform
return ICryptoTransform
示例#1
1
        /// <summary>
        /// Decrypts the specified data using a 128-bit cipher. The key can be any length.
        /// </summary>
        /// <param name="Data">The data to be decrypted.</param>
        /// <param name="Key">The key used to decrypt the data.</param>
        /// <returns>A string containing the decoded data.</returns>
        public static byte[] Decrypt128Byte(byte[] Data, byte[] Key)
        {
            RijndaelManaged AES = null;
            var MS = new MemoryStream(Data);
            CryptoStream CS = null;
            StreamReader DS = null;
            try
            {
                //Get the IV and length corrected Key.
                KeyData KeyData = GenerateKeyIV128(Key);
                //Create the AES crytpograhy object.
                AES = new RijndaelManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                CS = new CryptoStream(MS, AES.CreateDecryptor(), CryptoStreamMode.Read);
                DS = new StreamReader(CS);

                var D = new byte[CS.Length];
                CS.Read(D, 0, (int)CS.Length - 1);
                return D;
            }
            finally
            {
                if (AES != null) AES.Clear();
                MS.Dispose();
                if (CS != null) CS.Dispose();
                if (DS != null) DS.Dispose();
            }
        }
示例#2
1
        private byte[] DecryptManaged(byte[] Key, byte[] Vector, byte[] Data, PaddingMode Padding = PaddingMode.Zeros)
        {
            byte[] decryptedBytes;
            int count = 0;

            using (MemoryStream stream = new MemoryStream(Data))
            {
                using (RijndaelManaged cipher = new RijndaelManaged())
                {
                    cipher.Mode = CipherMode.CBC;
                    cipher.Padding = Padding;
                    cipher.KeySize = Key.Length * 8;
                    cipher.BlockSize = Vector.Length * 8;

                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(Key, Vector))
                    {
                        using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                        {
                            decryptedBytes = new byte[stream.Length];
                            count = reader.Read(decryptedBytes, 0, decryptedBytes.Length);
                        }
                    }
                    cipher.Clear();
                }
            }
            return decryptedBytes;
        }
示例#3
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);
                        }
                    }
                }
            }
        }
示例#4
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;
 }
 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);
     }
 }
示例#6
1
        public static string Descriptografar(string codigo)
        {
            try
            {
                if (string.IsNullOrEmpty(codigo))
                    return String.Empty;
                string retorno;
                var chave = new Rfc2898DeriveBytes(Segredo, Complemento);

                var algoritimo = new RijndaelManaged();
                algoritimo.Key = chave.GetBytes(algoritimo.KeySize / 8);
                algoritimo.IV = chave.GetBytes(algoritimo.BlockSize / 8);

                var descriptografor = algoritimo.CreateDecryptor(algoritimo.Key, algoritimo.IV);
                var bytes = Convert.FromBase64String(codigo);

                using (var memoryStream = new MemoryStream(bytes))
                using (var cryptoStream = new CryptoStream(memoryStream, descriptografor, CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                    retorno = streamReader.ReadToEnd();

                algoritimo.Clear();

                return retorno;
            }
            catch (Exception)
            {
                return "DEU PAU";
            }
        }
 public AesEncryption(byte[] Key, byte[] Vector)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     this.EncryptorTransform = rijndaelManaged.CreateEncryptor(Key, Vector);
     this.DecryptorTransform = rijndaelManaged.CreateDecryptor(Key, Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
        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();
        }
        public static string DecryptString(String cipherText, string Key)
        {
            byte[] tmpCipherText = Convert.FromBase64String(cipherText);
            byte[] tmpKey = GenerateAlgotihmInputs(Key);

            using (RijndaelManaged alg = new RijndaelManaged())
            {
                alg.Key = tmpKey;
                alg.IV = tmpKey;

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(tmpCipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        // Place les données déchiffrées dans un tableau d'octet
                        byte[] plainTextData = new byte[tmpCipherText.Length];

                        int decryptedByteCount = csDecrypt.Read(plainTextData, 0, plainTextData.Length);
                        return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount);
                    }

                }

            }
        }
示例#10
1
 // Methods
 public EncryptionHelper()
 {
     RijndaelManaged managed = new RijndaelManaged();
     this.EncryptorTransform = managed.CreateEncryptor(this.Key, this.Vector);
     this.DecryptorTransform = managed.CreateDecryptor(this.Key, this.Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
示例#11
1
 public AuthenticationHelper()
 {
     var rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
        /// <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();
            }
        }
示例#13
0
 public static byte[] DecryptAES(byte[] input, string key)
 {
     System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
     System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
     byte[] decrypted;
     try
     {
         byte[] hash = new byte[32];
         byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(key));
         Array.Copy(temp, 0, hash, 0, 16);
         Array.Copy(temp, 0, hash, 15, 16);
         AES.Key  = hash;
         AES.Mode = System.Security.Cryptography.CipherMode.ECB;
         System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
         //byte[] Buffer = Convert.FromBase64String(input);
         //byte[] Buffer = Convert.for;
         //decrypted = System.Text.ASCIIEncoding.UTF8.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
         decrypted = DESDecrypter.TransformFinalBlock(input, 0, input.Length);
         return(decrypted);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
示例#14
0
 /// <summary>
 /// Decrypts a byte array with a password
 /// </summary>
 /// <param name="data">Data to decrypt</param>
 /// <param name="password">Password to use</param>
 /// <param name="paddingMode">Padding mode to use</param>
 /// <returns>Decrypted byte array</returns>
 /// <exception cref="System.ArgumentNullException">
 /// data
 /// or
 /// password
 /// </exception>
 /// <exception cref="ArgumentNullException"></exception>
 public static byte[] DecryptData(byte[] data, string password, PaddingMode paddingMode)
 {
     if (data == null || data.Length == 0)
         throw new ArgumentNullException("data");
     if (password == null)
         throw new ArgumentNullException("password");
     var pdb = new PasswordDeriveBytes(password, Encoding.UTF8.GetBytes("Salt"));
     var rm = new RijndaelManaged { Padding = paddingMode };
     ICryptoTransform decryptor = rm.CreateDecryptor(pdb.GetBytes(16), pdb.GetBytes(16));
     pdb.Dispose();
     using (var msDecrypt = new MemoryStream(data))
     using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
     {
         // Decrypted bytes will always be less then encrypted bytes, so length of encrypted data will be big enough for buffer.
         byte[] fromEncrypt = new byte[data.Length];
         // Read as many bytes as possible.
         int read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
         if (read < fromEncrypt.Length)
         {
             // Return a byte array of proper size.
             byte[] clearBytes = new byte[read];
             Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read);
             return clearBytes;
         }
         return fromEncrypt;
     }
 }
        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);
        }
示例#16
0
        public static String read(byte[] cypher, string KeyString, string IVString)
        {
            var sRet = "";

            var encoding = new UTF8Encoding();
            var Key = encoding.GetBytes(KeyString);
            var IV = encoding.GetBytes(IVString);

            using (var rj = new RijndaelManaged())
            {
                try
                {
                    rj.Padding = PaddingMode.PKCS7;
                    rj.Mode = CipherMode.CBC;
                    rj.KeySize = 256;
                    rj.BlockSize = 256;
                    rj.Key = Key;
                    rj.IV = IV;
                    var ms = new MemoryStream(cypher);

                    using (var cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                    {
                        using (var sr = new StreamReader(cs))
                        {
                            sRet = sr.ReadLine();
                        }
                    }
                }
                finally
                {
                    rj.Clear();
                }
            }
            return sRet;
        }
示例#17
0
文件: AES.cs 项目: zz110/WKT2015
        /// <summary>
        /// AES解密/ECB/NoPadding
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            //key不足16位时用1补齐
            if (key.Length % 16 != 0)
            {
                int keyLen = 16 - (key.Length % 16);
                for (int i = 0; i < keyLen; i++)
                {
                    key += "1";
                }
            }
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.None
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Encoding.UTF8.GetString(resultArray).Replace("\0", ""));
        }
示例#18
0
文件: Encryption.cs 项目: BjkGkh/R106
		/// <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;
		}
示例#19
0
        /// <summary>
        /// AES解密,与JAVA通用
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return("");
            }
            try
            {
                Byte[] toEncryptArray = Convert.FromBase64String(str);

                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key     = Encoding.UTF8.GetBytes(key),
                    Mode    = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

                return(Encoding.UTF8.GetString(resultArray));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return("");
            }
        }
示例#20
0
 public SimplerAES()
 {
     RijndaelManaged rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
        /// <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);
        }
示例#22
0
 private static byte[] AES_decrypt(string input, byte[] iv, byte[] key)
 {
     using (var aes = new RijndaelManaged
     {
         KeySize = 256,
         BlockSize = 128,
         Mode = CipherMode.CBC,
         Padding = PaddingMode.None,
         Key = key,
         IV = iv
     })
     {
         var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
         byte[] xBuff;
         using (var ms = new MemoryStream())
         {
             using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
             {
                 var xXml = Convert.FromBase64String(input);
                 var msg = new byte[xXml.Length + 32 - xXml.Length % 32];
                 Array.Copy(xXml, msg, xXml.Length);
                 cs.Write(xXml, 0, xXml.Length);
                 xBuff = Decode2(ms.ToArray());
             }
         }
         return xBuff;
     }
 }
示例#23
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;
 }
示例#24
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);
        }
		public void CBC_0() {
	
			byte[] plaintext = new byte[32];
			for (int i=0; i < plaintext.Length; i++) plaintext[i] = 0;
	
			byte[] iv = new byte[16];
			for (byte i=0; i < iv.Length; i++) {
				iv[i] = 0;
			}
	
			RijndaelManaged r = new RijndaelManaged();
			byte[] key = new byte[16];	
	
			for (int i=0; i < 16; i++) r.Key[i] = 0;
			r.BlockSize = 128;
			r.Mode = CipherMode.CBC;
			r.Padding = PaddingMode.Zeros;
			r.Key = key;
	
			byte[] expected = { 
				0x66, 0xe9, 0x4b, 0xd4, 0xef, 0x8a, 0x2c, 0x3b, 
				0x88, 0x4c, 0xfa, 0x59, 0xca, 0x34, 0x2b, 0x2e, 
				0xf7, 0x95, 0xbd, 0x4a, 0x52, 0xe2, 0x9e, 0xd7, 
				0x13, 0xd3, 0x13, 0xfa, 0x20, 0xe9, 0x8d, 0xbc };
	
			CheckCBC(r.CreateEncryptor(key, iv), r.CreateDecryptor(key, iv), plaintext, expected);
		}
示例#26
0
        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Decrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void decryptFile(string inputFile, string outputFile)
        {
            FileStream fsCrypt = null;
            FileStream fsOut = null;
            CryptoStream cryptStream = null;

            try
            {
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(TPW);
                fsCrypt = new FileStream(inputFile, FileMode.Open);
                RijndaelManaged RMCrypto = new RijndaelManaged();

                cryptStream = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);

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

                fsOut = new FileStream(outputFile, FileMode.Create);
                fsOut.Write(inBytes, 0, inBytes.Length);

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

                if ( cryptStream != null )
                    cryptStream.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;
        }
示例#28
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">需解密字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="isDecodeUrl">是否需要URL解码</param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key, bool isDecodeUrl = true)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            if (isDecodeUrl)
            {
                str = System.Web.HttpUtility.UrlDecode(str);
            }

            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#29
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="text"></param>
        /// <param name="password"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string AESDecrypt(string text, string password, string iv)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            rijndaelCipher.Mode = CipherMode.CBC;

            rijndaelCipher.Padding = PaddingMode.PKCS7;

            rijndaelCipher.KeySize = 128;

            rijndaelCipher.BlockSize = 128;

            byte[] encryptedData = Convert.FromBase64String(text);

            byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password);

            byte[] keyBytes = new byte[16];

            int len = pwdBytes.Length;

            if (len > keyBytes.Length) len = keyBytes.Length;

            System.Array.Copy(pwdBytes, keyBytes, len);

            rijndaelCipher.Key = keyBytes;

            byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
            rijndaelCipher.IV = ivBytes;

            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();

            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            return Encoding.UTF8.GetString(plainText);
        }
示例#30
0
        public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
        {
            byte[] decryptedBytes = 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.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }
        internal static String Decrypt_AES(String data, String key, String iv)
        {
            string plaintext = null;

            byte[] bytesToBeDecrypted = Convert.FromBase64String(data);

            using (MemoryStream ms = new MemoryStream(bytesToBeDecrypted))
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 256;
                    AES.Padding = PaddingMode.Zeros;
                    AES.Key = Encoding.UTF8.GetBytes(key);
                    AES.IV = Encoding.UTF8.GetBytes(iv);
                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(AES.Key, AES.IV), CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(cs))
                        {
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            plaintext = plaintext.Substring(0,plaintext.LastIndexOf("}")+1);
            return plaintext;
        }
示例#32
0
        /// <summary>
        /// Cryptographic transformation
        /// </summary>
        /// <param name="password"></param>
        /// <param name="encrypt"></param>
        /// <returns></returns>
        private static ICryptoTransform GetTransform(bool Encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged Cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] Salt = SaltFromPassword();

            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes SecretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(Keys.KEY, Salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[]           SecretKeyBytes            = SecretKey.GetBytes(32);
            byte[]           InitializationVectorBytes = SecretKey.GetBytes(16);
            ICryptoTransform Cryptor = null;

            if (Encrypt)
            {
                Cryptor = Cipher.CreateEncryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            else
            {
                Cryptor = Cipher.CreateDecryptor(SecretKeyBytes, InitializationVectorBytes);
            }
            return(Cryptor);
        }
示例#33
0
        public static string Decrypt(string cipherText, string passPhrase)
        {
            if (cipherText != null && cipherText != "")
            {
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
                using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
                {
                    byte[] keyBytes = password.GetBytes(keysize / 8);
                    using (RijndaelManaged symmetricKey = new RijndaelManaged())
                    {
                        symmetricKey.Mode = CipherMode.CBC;
                        using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                        {
                            using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                            {
                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                {
                                    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                                }
                            }
                        }
                    }
                }
            }

            return "";
        }
        private ICryptoTransform GetTransform(string password, bool encrypt)
        {
            // Create an instance of the Rihndael class.
            RijndaelManaged cipher = new System.Security.Cryptography.RijndaelManaged();

            // Calculate salt to make it harder to guess key by using a dictionary attack.
            byte[] salt = SaltFromPassword(password);
            WriteLog("// salt = " + System.BitConverter.ToString(salt).Replace("-", ""));
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            Rfc2898DeriveBytes secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, 10);

            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            byte[] key = secretKey.GetBytes(32);
            byte[] iv  = secretKey.GetBytes(16);
            WriteLog("// key = " + System.BitConverter.ToString(key).Replace("-", ""));
            WriteLog("// iv = " + System.BitConverter.ToString(iv).Replace("-", ""));
            ICryptoTransform cryptor = null;

            if (encrypt)
            {
                cryptor = cipher.CreateEncryptor(key, iv);
            }
            else
            {
                cryptor = cipher.CreateDecryptor(key, iv);
            }
            return(cryptor);
        }
示例#35
0
        public static void DecryptAes(Stream inStream, Stream outStream, string password)
        {
            if (inStream == null)
            {
                throw new ArgumentNullException("inStream");
            }
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // generate an encryption key with the shared secret and salt
            using (var key = new Rfc2898DeriveBytes(password, Salt))
            {
                using (var aesAlg = new RijndaelManaged())
                {
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

                    using (var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
                    {
                        using (var csEncrypt = new CryptoStream(inStream, decryptor, CryptoStreamMode.Read))
                        {
                            csEncrypt.CopyTo(outStream);
                        }
                    }
                }
            }
        }
示例#36
0
        public static byte[] Decrypt(byte[] input)
        {
            if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty.");
            if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty.");

            byte[] data = new byte[0];

            try
            {
                using (var ms = new MemoryStream(input))
                {
                    using (var rd = new RijndaelManaged { Key = _key })
                    {
                        byte[] iv = new byte[IVLENGTH];
                        ms.Read(iv, 0, IVLENGTH); // read first 16 bytes for IV, followed by encrypted message
                        rd.IV = iv;

                        using (var cs = new CryptoStream(ms, rd.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            byte[] temp = new byte[ms.Length - IVLENGTH + 1];
                            data = new byte[cs.Read(temp, 0, temp.Length)];
                            Buffer.BlockCopy(temp, 0, data, 0, data.Length);
                        }
                    }
                }
            }
            catch
            {
            }
            return data;
        }
示例#37
0
        public static string AES_Decrypt(string input_text)
        {
            //Please dont change or EDIT ANY PART of THIS CODE
            // ''' security_Code= [email protected]
            string securitycode = "[email protected]";

            System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                byte[] temp = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(securitycode));
                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);
                AES.Key  = hash;
                AES.Mode = CipherMode.ECB;
                // Security.Cryptography.CipherMode.ECB
                System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
                byte[] Buffer = Convert.FromBase64String(input_text);
                decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(decrypted);
        }
示例#38
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="cipherText">要解密的字串</param>
        /// <returns>解密后的字串</returns>
        public static string DecryptStringAES(string cipherText)
        {
            if (string.IsNullOrEmpty(cipherText))
                throw new ArgumentNullException("cipherText");
            RijndaelManaged aesAlg = null;
            string plaintext = null;

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

            return plaintext;
        } 
示例#39
0
 //stub
 public static byte[] AESDecrypt(byte[] input, string Pass)
 {
     System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
     byte[] hash = new byte[32];
     byte[] temp = new MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.ASCII.GetBytes(Pass));
     Array.Copy(temp, 0, hash, 0, 16);
     Array.Copy(temp, 0, hash, 15, 16);
     AES.Key  = hash;
     AES.Mode = System.Security.Cryptography.CipherMode.ECB;
     System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
     return(DESDecrypter.TransformFinalBlock(input, 0, input.Length));
 }
示例#40
0
 /// <summary>
 /// 用key*对加密串B做AES-256-ECB解密
 /// </summary>
 /// <param name="decryptStr"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string AESDecrypt(string decryptStr, string key)
 {
     byte[] keyArray       = System.Text.UTF8Encoding.UTF8.GetBytes(key);
     byte[] toEncryptArray = Convert.FromBase64String(decryptStr);
     System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
     rDel.Key     = keyArray;
     rDel.Mode    = System.Security.Cryptography.CipherMode.ECB;
     rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
     System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor();
     byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
     return(System.Text.UTF8Encoding.UTF8.GetString(resultArray));
 }
示例#41
0
        /// <summary>
        /// AES解密 - 16进制
        /// </summary>
        public static String DecrypHex(String content, String key)
        {
            Byte[] keyArray     = UTF8Encoding.UTF8.GetBytes(key);
            Byte[] encryptArray = ByteUtil.HexToBytes(content);

            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
            rDel.Key     = keyArray;
            rDel.Mode    = System.Security.Cryptography.CipherMode.ECB;
            rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(encryptArray, 0, encryptArray.Length);
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
示例#42
0
            /// <summary>
            /// AES解密
            /// </summary>
            /// <param name="str">需要解密的字符串</param>
            /// <returns>解密后的字符串</returns>
            public static string AESDecrypt(string str)
            {
                Byte[] toEncryptArray = Convert.FromBase64String(str);
                var    rijndael       = new System.Security.Cryptography.RijndaelManaged();

                rijndael.Key     = aseKey;
                rijndael.Mode    = System.Security.Cryptography.CipherMode.ECB;
                rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                rijndael.IV      = aseIV;
                System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return(System.Text.Encoding.UTF8.GetString(resultArray));
            }
示例#43
0
        internal static byte[] DecryptAES(byte[] RVAR19, string RVAR20)
        {
            RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();

            byte[] hash = new byte[32];
            byte[] temp = new MD5CryptoServiceProvider().ComputeHash(System.Text.Encoding.ASCII.GetBytes(RVAR20));
            Array.Copy(temp, 0, hash, 0, 16);
            Array.Copy(temp, 0, hash, 15, 16);
            AES.Key  = hash;
            AES.Mode = CipherMode.ECB;
            ICryptoTransform DESDecrypter = AES.CreateDecryptor();

            byte[] decrypted = DESDecrypter.TransformFinalBlock(RVAR19, 0, RVAR19.Length);
            return(decrypted);
        }
示例#44
0
 public static String DecryptAES(byte[] buff, byte[] key, byte[] iv)
 {
     using (System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged())
     {
         rijndael.Padding   = PaddingMode.PKCS7;
         rijndael.Mode      = CipherMode.CBC;
         rijndael.KeySize   = 128;
         rijndael.BlockSize = 128;
         ICryptoTransform       decryptor    = rijndael.CreateDecryptor(key, iv);
         System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(buff);
         CryptoStream           cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
         byte[] output    = new byte[buff.Length];
         int    readBytes = cryptoStream.Read(output, 0, output.Length);
         return(System.Text.Encoding.UTF8.GetString(output, 0, readBytes));
     }
 }
示例#45
0
文件: Utility.cs 项目: hw233/ysz
 /// <summary>
 /// AES 解密
 /// </summary>
 /// <param name="decryptBytes">密文</param>
 /// <param name="key">密钥</param>
 /// <returns></returns>
 public static byte[] AESDecrypt(byte[] decryptBytes, string key)
 {
     if (decryptBytes != null && decryptBytes.Length > 0)
     {
         byte[] keyArray = Encoding.UTF8.GetBytes(key);
         System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
         rDel.Key     = keyArray;
         rDel.Mode    = System.Security.Cryptography.CipherMode.ECB;
         rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
         System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor();
         return(cTransform.TransformFinalBlock(decryptBytes, 0, decryptBytes.Length));
     }
     else
     {
         return(new byte[0]);
     }
 }
示例#46
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">明文(待解密)</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static byte[] AesDecrypt(byte[] str, byte[] key)
        {
            byte[] toEncryptArray = str;

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = key.Take(32).ToArray(),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.Zeros
            };
            var sss = rm.Key;

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(resultArray);
        }
示例#47
0
文件: AESCrypto.cs 项目: tanzw/six
        public string Decrypt(string text, string key)
        {
            IsValid(text, key);
            Byte[] toEncryptArray = Convert.FromBase64String(text);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#48
0
文件: AES.cs 项目: zz110/WKT2015
 public static string AesDecrypt(string str)
 {
     if (string.IsNullOrEmpty(str))
     {
         return(null);
     }
     Byte[] toEncryptArray = Convert.FromBase64String(str);
     System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
     {
         Key     = Encoding.UTF8.GetBytes(Key),
         Mode    = System.Security.Cryptography.CipherMode.ECB,
         Padding = System.Security.Cryptography.PaddingMode.None
     };
     System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
     Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
     return(Encoding.UTF8.GetString(resultArray).Replace("\0", ""));
 }
 /// <summary>
 /// 微信小程序,登录使用解码函数
 /// </summary>
 /// <param name="raw"></param>
 /// <param name="signature"></param>
 /// <param name="encryptedData"></param>
 /// <param name="iv"></param>
 /// <param name="session_key"></param>
 /// <returns></returns>
 public static string DecodeUserInfo(string raw, string signature, string encryptedData, string iv, string session_key)//微信小程序,登录使用解码函数
 {
     byte[] iv2 = Convert.FromBase64String(iv);
     if (string.IsNullOrEmpty(encryptedData))
     {
         return("");
     }
     Byte[] toEncryptArray = Convert.FromBase64String(encryptedData);
     System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
     {
         Key     = Convert.FromBase64String(session_key),
         IV      = iv2,
         Mode    = System.Security.Cryptography.CipherMode.CBC,
         Padding = System.Security.Cryptography.PaddingMode.PKCS7
     };
     System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
     Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
     return(Encoding.UTF8.GetString(resultArray));
 }
示例#50
0
    /// <summary>
    ///  AES 解密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static byte[] AesDecrypt(byte[] str, int count_, int index_ = 0, string key = _key)
    {
        // *remark*: ignore
        //if (string.IsNullOrEmpty(Encoding.UTF8.GetString(str, index_, count_))) return null;
        //Byte[] toEncryptArray = Convert.FromBase64String(Encoding.UTF8.GetString(str, index_, count_));
        Byte[] toEncryptArray = Convert.FromBase64String(Encoding.ASCII.GetString(str, index_, count_));

        System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
        {
            Key     = Encoding.ASCII.GetBytes(key),
            Mode    = System.Security.Cryptography.CipherMode.ECB,
            Padding = System.Security.Cryptography.PaddingMode.PKCS7
        };

        System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return(resultArray);
    }
示例#51
0
        byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt)
        {
            /// <summary>Encrypt by using AES-256 algorithm.</summary>
            // Create an instance of the Rijndael class.
            var cipher = new System.Security.Cryptography.RijndaelManaged();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = encrypt
                                ? cipher.CreateEncryptor(key, iv)
                                : cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new byte[dataBytes.Length];

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

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

            // Close both streams.
            stream.Close();
            cryptoStream.Close();
            return(outputBuffer);
        }
示例#52
0
        public static string Decrypt(String value, String key)
        {
            byte[] keyBytes   = Convert.FromBase64String(key);
            byte[] valueBytes = Convert.FromBase64String(value);

            //Server.log("WMS:" + System.Text.Encoding.Default.GetString(keyBytes), Constant.info, Constant.infoColor);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = keyBytes,
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(valueBytes, 0, valueBytes.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#53
0
 /// <summary>
 /// 解密字符串
 /// </summary>
 /// <param name="value"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 /// <exception cref="Exception"></exception>
 public static string DecryptStr(string value, string key)
 {
     try
     {
         Byte[] keyArray       = System.Text.Encoding.UTF8.GetBytes(key);
         Byte[] toEncryptArray = Convert.FromBase64String(value);
         var    rijndael       = new System.Security.Cryptography.RijndaelManaged();
         rijndael.Key     = keyArray;
         rijndael.Mode    = System.Security.Cryptography.CipherMode.ECB;
         rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
         System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
         Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
         return(System.Text.Encoding.UTF8.GetString(resultArray));
     }
     catch (Exception ex)
     {
         Log.PrintError(ex);
         return(null);
     }
 }
示例#54
0
        /// <summary>
        /// AES 解密
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="secretKey">私钥(长度: 16、24、32字节)</param>
        /// <returns></returns>
        public static string AESDecrypt(string content, string secretKey)
        {
            if (string.IsNullOrEmpty(content))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(content);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(secretKey),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#55
0
                /// <summary>
                /// Método para desencriptar um texto em AES
                /// </summary>
                /// <param name="Buffer">Buffer</param>
                /// <param name="text">Texto para desencriptar</param>
                /// <returns></returns>
                public static byte[] Decrypt(byte[] Buffer, string text)
                {
                    System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();

                    byte[] decrypted = null;
                    try
                    {
                        byte[] temp = System.Text.ASCIIEncoding.ASCII.GetBytes(text);
                        AES.Key  = temp;
                        AES.Mode = System.Security.Cryptography.CipherMode.ECB;

                        System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();

                        decrypted = DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length);
                    }
                    catch
                    { }

                    return(decrypted);
                }
示例#56
0
        public static string AES_Decrypt(string input)
        {
            System.Security.Cryptography.RijndaelManaged          AES      = new System.Security.Cryptography.RijndaelManaged();
            System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
            string decrypted = "";

            try
            {
                AES.Key  = getSHA1Hash(pass);
                AES.Mode = System.Security.Cryptography.CipherMode.ECB;
                System.Security.Cryptography.ICryptoTransform DESDecrypter = AES.CreateDecryptor();
                byte[] Buffer = Convert.FromBase64String(input);
                decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
                return(decrypted);
            }
            catch (Exception)
            {
                return(null);
            }
        }
示例#57
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);//如果java没用base64,则这里应该不需要,这个方法尚未验证,先留着

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#58
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            Byte[] iv             = Encoding.UTF8.GetBytes("SiChuanBingosoft");
            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Encoding.UTF8.GetBytes(key),
                Mode    = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7,
                IV      = iv
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
示例#59
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            this.mode        = mode;
            rijndael         = new RijndaelManaged();
            rijndael.Mode    = CipherMode.CBC;
            rijndael.Padding = PaddingMode.None;
            //String pad="NoPadding";
            byte[] tmp;
            if (iv.Length > ivsize)
            {
                tmp = new byte[ivsize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (key.Length > bsize)
            {
                tmp = new byte[bsize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }

            try
            {
                //      SecretKeySpec keyspec=new SecretKeySpec(key, "AES");
                //		cipher=javax.crypto.Cipher.getInstance("AES/CBC/"+pad);

                //      cipher.init((mode==ENCRYPT_MODE?
                //		   javax.crypto.Cipher.ENCRYPT_MODE:
                //		   javax.crypto.Cipher.DECRYPT_MODE),
                //		  keyspec, new IvParameterSpec(iv));
                cipher = (mode == ENCRYPT_MODE?
                          rijndael.CreateEncryptor(key, iv):
                          rijndael.CreateDecryptor(key, iv));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                cipher = null;
            }
        }
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key = getLegalKey(key),
                IV  = getLegalIV(),
                //Mode = System.Security.Cryptography.CipherMode.ECB,
                Mode    = CipherMode.CBC,// "AES/CBC/PKCS7Padding",
                Padding = PaddingMode.PKCS7
            };

            System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }