Пример #1
0
        public static string decryptRJ256(string target, string key, string iv)
        {
            var rijndael = new System.Security.Cryptography.RijndaelManaged()
            {
                Padding = System.Security.Cryptography.PaddingMode.Zeros,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                KeySize = 256,
                BlockSize = 256
            };

            var keyBytes = Encoding.ASCII.GetBytes(key);
            var ivBytes = Encoding.ASCII.GetBytes(iv);

            var decryptor = rijndael.CreateDecryptor(keyBytes, ivBytes);
            var toDecrypt = Convert.FromBase64String(target);
            var fromEncrypt = new byte[toDecrypt.Length];

            var msDecrypt = new System.IO.MemoryStream(toDecrypt);
            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

            string data = Encoding.ASCII.GetString(fromEncrypt);
            data = data.Replace("\0", "");

            return data;
        }
Пример #2
0
        /// <summary>
        /// 暗号化された文字列を復号化する
        /// </summary>
        /// <param name="sourceString">暗号化された文字列</param>
        /// <param name="password">暗号化に使用したパスワード</param>
        /// <returns>復号化された文字列</returns>
        public static string DecryptString(string sourceString, string password)
        {
            if (String.IsNullOrEmpty(sourceString))
            {
                return "";
            }

            //RijndaelManagedオブジェクトを作成
            System.Security.Cryptography.RijndaelManaged rijndael =
                new System.Security.Cryptography.RijndaelManaged();

            //パスワードから共有キーと初期化ベクタを作成
            byte[] key, iv;
            GenerateKeyFromPassword(
                password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV = iv;

            //文字列をバイト型配列に戻す
            byte[] strBytes = System.Convert.FromBase64String(sourceString);

            //対称暗号化オブジェクトの作成
            System.Security.Cryptography.ICryptoTransform decryptor =
                rijndael.CreateDecryptor();
            //バイト型配列を復号化する
            byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            //閉じる
            decryptor.Dispose();

            //バイト型配列を文字列に戻して返す
            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
Пример #3
0
 /// <summary>  
 /// AES解密  
 /// </summary>  
 /// <param name="str">要解密字符串</param>  
 /// <returns>返回解密后字符串</returns>  
 public static String Decrypt_AES(String str, string strAesKey)
 {
     Byte[] keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(strAesKey);
     Byte[] toEncryptArray = Convert.FromBase64String(str);
     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);
 }
Пример #4
0
		public List<byte> Decrypt(string encodedEncPayload)
		{
			var ciphrBytes = Convert.FromBase64String(encodedEncPayload).ToList();
			using (var aes = new System.Security.Cryptography.RijndaelManaged())
			{
				aes.Mode = System.Security.Cryptography.CipherMode.CBC;
				aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
				aes.IV = ciphrBytes.Take(16).ToArray();
				aes.Key = _key.ToArray();
				var dec = aes.CreateDecryptor();
				var encBytes = ciphrBytes.Skip(16).ToArray();
				var plainbytes = dec.TransformFinalBlock(encBytes, 0, encBytes.Length).ToList();
				return plainbytes;
			}
		}
Пример #5
0
        public string Decrypt(string Original)
        {
            Byte[] keyArray       = System.Text.UTF8Encoding.UTF8.GetBytes(crKey);
            Byte[] toEncryptArray = Convert.FromBase64String(Original);

            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));
        }
Пример #6
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, Byte[] key)
        {
            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged {
                Key     = 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));
        }
Пример #7
0
        //-------------------------------------------------

        public static string AesDecrypt(string password, string base64)
        {
            // Turn input string into a byte array.
            var input = System.Convert.FromBase64String(base64);
            // 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 passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
            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 = cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new System.Byte[input.Length];

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

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

            // Close both streams.
            stream.Close();
            //cryptoStream.Close();
            // Convert encrypted data into a base64-encoded string.
            var s = System.Text.Encoding.UTF8.GetString(outputBuffer);

            return(s);
        }
Пример #8
0
        //public static string EncryptString(string input)
        //{
        //	System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
        //	System.Security.Cryptography.MD5CryptoServiceProvider Hash_AES = new System.Security.Cryptography.MD5CryptoServiceProvider();
        //	string encrypted;
        //	byte[] hash = new byte[32];
        //	byte[] temp = Hash_AES.ComputeHash(Encoding.ASCII.GetBytes(sharedKey));
        //	Array.Copy(temp, 0, hash, 0, 16);
        //	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 DESEncrypter = AES.CreateEncryptor();
        //	byte[] Buffer = Encoding.ASCII.GetBytes(input);
        //	encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
        //	return encrypted;
        //}

        public string DecryptString(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;

            byte[] hash = new byte[32];
            byte[] temp = Hash_AES.ComputeHash(Encoding.ASCII.GetBytes(sharedKey));
            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);
            decrypted = Encoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
            return(decrypted);
        }
        public static string DeCrypt(string strEncryptedInput)
        {
            string strReturnValue = null;

            if (string.IsNullOrEmpty(strEncryptedInput))
            {
                throw new System.ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values.");
            }

            // Dim encASCII As New System.Text.ASCIIEncoding()
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            System.Security.Cryptography.RijndaelManaged objRijndael = new System.Security.Cryptography.RijndaelManaged();

            byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput);

            byte[] baDecryptionKey = HexStringToByteArray(strKey);
            byte[] baInitializationVector = HexStringToByteArray(strIV);

            // This is where the message would be transmitted to a recipient
            // who already knows your secret key. Optionally, you can
            // also encrypt your secret key using a public key algorithm
            // and pass it to the mesage recipient along with the RijnDael
            // encrypted message.
            //Get a decryptor that uses the same key and IV as the encryptor.
            System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector);

            //Now decrypt the previously encrypted message using the decryptor
            // obtained in the above step.
            System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer);
            System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read);

            //Dim baPlainTextBuffer() As Byte
            //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {}
            byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1];

            //Read the data out of the crypto stream.
            csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length);

            //Convert the byte array back into a string.
            strReturnValue = enc.GetString(baPlainTextBuffer);
            if (!string.IsNullOrEmpty(strReturnValue))
                strReturnValue = strReturnValue.Trim('\0');

            return strReturnValue;
        }
        /// <summary>
        /// Initializa os objetos necessários para realizar criptografia e descriptografia.
        /// </summary>
        private void Initialize()
        {
            System.Security.Cryptography.RijndaelManaged    v_rijndael;
            System.Security.Cryptography.Rfc2898DeriveBytes v_passwordbytes;
            byte[] v_initvectorbytes;
            byte[] v_keybytes;

            v_rijndael      = new System.Security.Cryptography.RijndaelManaged();
            v_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC;

            v_initvectorbytes = System.Text.Encoding.ASCII.GetBytes(this.v_initvector);

            v_passwordbytes = new System.Security.Cryptography.Rfc2898DeriveBytes(this.v_password, v_initvectorbytes, 1);
            v_keybytes      = v_passwordbytes.GetBytes(this.v_keysize / 8);

            this.v_encryptor = v_rijndael.CreateEncryptor(v_keybytes, v_initvectorbytes);
            this.v_decryptor = v_rijndael.CreateDecryptor(v_keybytes, v_initvectorbytes);
        }
Пример #11
0
        public List <byte> Decrypt(string encodedEncPayload)
        {
            var ciphrBytes = Convert.FromBase64String(encodedEncPayload).ToList();

            using (var aes = new System.Security.Cryptography.RijndaelManaged())
            {
                aes.Mode    = System.Security.Cryptography.CipherMode.CBC;
                aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                aes.IV      = ciphrBytes.Take(16).ToArray();
                var key = _key.ToArray();
                System.Security.Cryptography.ProtectedMemory.Unprotect(key, System.Security.Cryptography.MemoryProtectionScope.SameProcess);
                aes.Key = key;
                var dec        = aes.CreateDecryptor();
                var encBytes   = ciphrBytes.Skip(16).ToArray();
                var plainbytes = dec.TransformFinalBlock(encBytes, 0, encBytes.Length).ToList();
                Array.Clear(key, 0, key.Length);
                return(plainbytes);
            }
        }
Пример #12
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="input"></param>
        /// <param name="key">大于16位自动截断</param>
        /// <returns></returns>
        public static string AesDecrypt(string input, string key)
        {
            if (key.Length > 16)
            {
                key = key.Substring(0, 16);
            }

            Byte[] keyArray       = Encoding.UTF8.GetBytes(key);
            Byte[] toEncryptArray = Convert.FromBase64String(input);
            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = keyArray,
                Mode    = System.Security.Cryptography.CipherMode.ECB,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            };
            System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Encoding.UTF8.GetString(resultArray));
        }
Пример #13
0
        // Decrypt a string.
        public static string DecryptString(string sourceString, string password)
        {
            System.Security.Cryptography.RijndaelManaged rijndael =
                new System.Security.Cryptography.RijndaelManaged();

            byte[] key, iv;
            GenerateKeyFromPassword(
                password, rijndael.KeySize, out key, rijndael.BlockSize, out iv);
            rijndael.Key = key;
            rijndael.IV = iv;

            byte[] strBytes = System.Convert.FromBase64String(sourceString);

            System.Security.Cryptography.ICryptoTransform decryptor =
                rijndael.CreateDecryptor();
            byte[] decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
            decryptor.Dispose();

            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
Пример #14
0
        //解密
        public static string SystemDecryptByKey(string toDecrypt, string key)
        {
            while (16 > key.Length)
            {
                key += "_";
            }

            byte[] keyArray       = UTF8Encoding.UTF8.GetBytes(key);
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            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(UTF8Encoding.UTF8.GetString(resultArray));
        }
Пример #15
0
        public static Byte[] Dencrypt(Byte[] encryptedData, String key)
        {
            Byte[] iv  = new Byte[16];
            Byte[] k   = new Byte[32];
            Byte[] tmp = Convert.FromBase64String(key);

            Array.Copy(tmp, 0, iv, 0, 16);
            Array.Copy(tmp, 16, k, 0, 32);

            System.Security.Cryptography.RijndaelManaged aesEncryption = new System.Security.Cryptography.RijndaelManaged();
            aesEncryption.KeySize   = 256;
            aesEncryption.BlockSize = 128;
            aesEncryption.Mode      = System.Security.Cryptography.CipherMode.CBC;
            aesEncryption.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;
            aesEncryption.IV        = iv;
            aesEncryption.Key       = k;

            System.Security.Cryptography.ICryptoTransform decrypto = aesEncryption.CreateDecryptor();
            return(decrypto.TransformFinalBlock(encryptedData, 0, encryptedData.Length));
        }
Пример #16
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt_FromHexStr(string str, byte[] btkey)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = StringToByte.strToToHexByte(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = btkey,
                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));
        }
Пример #17
0
        public byte[] AESDecrypt(byte[] securityTxt, byte[] key)
        {
            try
            {
                System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
                {
                    Key     = key,
                    Mode    = System.Security.Cryptography.CipherMode.ECB,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                };

                System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
                Byte[] resultArray = cTransform.TransformFinalBlock(securityTxt, 0, securityTxt.Length);
                return(resultArray);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #18
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="text">明文(待解密)</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string AesDecrypt(string text, string key)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }
            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));
        }
Пример #19
0
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">要解密的字符</param>
        /// <returns></returns>
        /// <remarks>2015-10-12 杨浩 创建</remarks>
        protected virtual string Decrypt(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            Byte[] toEncryptArray = Convert.FromBase64String(str);

            System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
            {
                Key     = Convert.FromBase64String(CustomsKey),
                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));
        }
Пример #20
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptKey"></param>
        /// <param name="bizContent"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string AesDencrypt(string encryptKey, string bizContent, string charset = null)
        {
            if (string.IsNullOrWhiteSpace(encryptKey))
            {
                encryptKey = SystemKey.AesKey;
            }

            var arr_key     = Convert.FromBase64String(encryptKey);
            var arr_content = Convert.FromBase64String(bizContent);
            var reslut      = default(string);

            try
            {
                using (System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged())
                {
                    rDel.Key     = arr_key;
                    rDel.Mode    = System.Security.Cryptography.CipherMode.CBC;
                    rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                    rDel.IV      = AES_IV;

                    System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateDecryptor(rDel.Key, rDel.IV);
                    var arr_result = cTransform.TransformFinalBlock(arr_content, 0, arr_content.Length);

                    if (string.IsNullOrWhiteSpace(charset))
                    {
                        reslut = Encoding.UTF8.GetString(arr_result);
                    }
                    else
                    {
                        reslut = Encoding.GetEncoding(charset).GetString(arr_result);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }

            return(reslut);
        }
Пример #21
0
        internal static string ToDescrypt(string chave, string criptografia)
        {
            System.Security.Cryptography.RijndaelManaged rijndael = new System.Security.Cryptography.RijndaelManaged();
            rijndael.Mode    = System.Security.Cryptography.CipherMode.CBC;
            rijndael.KeySize = 128;

            byte[] chaveBytes;
            byte[] criptografiaBytes;
            byte[] mensagemBytes;
            string mensagem;

            chaveBytes    = Encoding.UTF8.GetBytes(chave);
            mensagemBytes = Convert.FromBase64String(criptografia);


            System.Security.Cryptography.ICryptoTransform cryptor = rijndael.CreateDecryptor(chaveBytes, chaveBytes);
            criptografiaBytes = cryptor.TransformFinalBlock(mensagemBytes, 0, mensagemBytes.Length);
            cryptor.Dispose();

            mensagem = Encoding.UTF8.GetString(criptografiaBytes);
            return(mensagem);
        }
Пример #22
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="str">要解密字符串</param>
        /// <returns>返回解密后字符串</returns>
        public static string Decrypt_AES(String str)
        {
            try
            {
                Byte[] keyArray       = System.Text.UTF8Encoding.UTF8.GetBytes(strAesKey);
                Byte[] toEncryptArray = Convert.FromBase64String(str);

                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));
            }
            catch (Exception ex)
            {
                return("");
            }
        }
Пример #23
0
 /// <summary>
 /// AES解密
 /// </summary>
 /// <param name="str">需要解密的字符串</param>
 /// <param name="key">32位密钥</param>
 /// <returns>解密后的字符串</returns>
 public static string Decrypt(string str, string key)
 {
     try
     {
         byte[] keyArray       = Encoding.UTF8.GetBytes(key);
         byte[] toEncryptArray = Convert.FromBase64String(str);
         var    rijndael       = new System.Security.Cryptography.RijndaelManaged
         {
             Key     = keyArray,
             Mode    = System.Security.Cryptography.CipherMode.ECB,
             Padding = System.Security.Cryptography.PaddingMode.PKCS7
         };
         //rijndael.IV = System.Text.Encoding.UTF8.GetBytes(Iv);
         System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
         byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
         return(Encoding.UTF8.GetString(resultArray));
     }
     catch (Exception ex)
     {
         return(str);
     }
 }
Пример #24
0
        private byte[] AESDecrypt(byte[] data, int index, int count, byte[] key)
        {
            byte[] decryptedBytes = null;

            //  Create uninitialized Rijndael encryption object.
            System.Security.Cryptography.RijndaelManaged symmetricKey = new  System.Security.Cryptography.RijndaelManaged();

            // It is required that the encryption mode is Electronic Codebook (ECB)
            // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39.
            symmetricKey.Mode    = System.Security.Cryptography.CipherMode.ECB;
            symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None;
            symmetricKey.KeySize = keySize;
            // symmetricKey.IV = null; // new byte[16];
            // symmetricKey.Key = key;

            //  Generate decryptor from the existing key bytes and initialization
            //  vector. Key size will be defined based on the number of the key
            //  bytes.
            System.Security.Cryptography.ICryptoTransform decryptor;
            decryptor = symmetricKey.CreateDecryptor(key, null);

            //  Define memory stream which will be used to hold encrypted data.
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data, index, count))
            {
                //  Define memory stream which will be used to hold encrypted data.
                using (System.Security.Cryptography.CryptoStream cryptoStream
                           = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.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 ciphertext;
                    //  plaintext is never longer than ciphertext.
                    decryptedBytes = new byte[data.Length];
                    int decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

                    return(decryptedBytes);
                }
            }
        }
Пример #25
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="key">32位密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string DecryptToString(string str, string key)
        {
            Byte[] keyArray        = System.Text.Encoding.UTF8.GetBytes(key);
            int    halfInputLength = str.Length / 2;

            Byte[] toEncryptArray = new Byte[halfInputLength];
            for (int x = 0; x < halfInputLength; x++)
            {
                int i = (Convert.ToInt32(str.Substring(x * 2, 2), 16));
                toEncryptArray[x] = (byte)i;
            }

            var rijndael = new System.Security.Cryptography.RijndaelManaged();

            rijndael.Key     = keyArray;
            rijndael.Mode    = System.Security.Cryptography.CipherMode.ECB;
            rijndael.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            rijndael.IV      = System.Text.Encoding.UTF8.GetBytes(Iv);
            System.Security.Cryptography.ICryptoTransform cTransform = rijndael.CreateDecryptor();
            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(System.Text.Encoding.UTF8.GetString(resultArray));
            //  return UTF8Encoding.UTF8.GetString(resultArray);
        }
Пример #26
0
        public static string AES_Decrypt(byte[] input, string pass)
        {
            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(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 AESDecrypter = AES.CreateDecryptor();
                decrypted = System.Text.ASCIIEncoding.ASCII.GetString(AESDecrypter.TransformFinalBlock(input, 0, input.Length));
                return(decrypted);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Пример #27
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptKey"></param>
        /// <param name="bizContent"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string AesDencrypt(string encryptKey, string bizContent, string charset = null)
        {
            if (string.IsNullOrWhiteSpace(encryptKey))
            {
                encryptKey = AppConfig.GetValue("AesKey");
            }

            Byte[] keyArray       = Convert.FromBase64String(encryptKey);
            Byte[] toEncryptArray = Convert.FromBase64String(bizContent);

            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();

            try
            {
                rDel.Key     = keyArray;
                rDel.Mode    = System.Security.Cryptography.CipherMode.CBC;
                rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                rDel.IV      = AES_IV;

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

                if (string.IsNullOrWhiteSpace(charset))
                {
                    return(Encoding.UTF8.GetString(resultArray));
                }
                else
                {
                    return(Encoding.GetEncoding(charset).GetString(resultArray));
                }
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                return(null);
            }
        }
Пример #28
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="encryptKey"></param>
        /// <param name="bizContent"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string AesDencrypt(string encryptKey, string bizContent, string charset)
        {
            Byte[] keyArray       = Convert.FromBase64String(encryptKey);
            Byte[] toEncryptArray = Convert.FromBase64String(bizContent);

            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();
            rDel.Key     = keyArray;
            rDel.Mode    = System.Security.Cryptography.CipherMode.CBC;
            rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            rDel.IV      = AES_IV;

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


            if (string.IsNullOrEmpty(charset))
            {
                return(Encoding.UTF8.GetString(resultArray));
            }
            else
            {
                return(Encoding.GetEncoding(charset).GetString(resultArray));
            }
        }
Пример #29
0
        public static string strDecifraString(string strTextoASerDecifrado)
        {
            string strRetorno = "";

            try
            {
                byte[] byTextoASerDeCifrado, byTextoDeCifrado;
                byte[] byKey = new byte[] { 255, 241, 3, 17, 206, 69, 56, 167, 94, 220, 219, 76, 112, 179, 12, 97, 178, 233, 14, 172, 238, 20, 54, 232, 212, 54, 50, 151, 138, 32, 26, 122 };
                byte[] byIV  = new byte[] { 207, 100, 146, 104, 139, 60, 94, 109, 109, 195, 236, 213, 235, 234, 233, 114 };
                System.Text.UnicodeEncoding conversorTexto = new System.Text.UnicodeEncoding();
                System.Security.Cryptography.RijndaelManaged clsSecCrypRijndael = new System.Security.Cryptography.RijndaelManaged();
                clsSecCrypRijndael.Padding = System.Security.Cryptography.PaddingMode.Zeros;

                //Get an encryptor.
                System.Security.Cryptography.ICryptoTransform decifrador = clsSecCrypRijndael.CreateDecryptor(byKey, byIV);

                byTextoASerDeCifrado = System.Convert.FromBase64String(strTextoASerDecifrado);

                // Cria os Streams
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(byTextoASerDeCifrado);
                System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decifrador, System.Security.Cryptography.CryptoStreamMode.Read);

                byTextoDeCifrado = new byte[byTextoASerDeCifrado.Length];

                // Read all data to the crypto stream and flush it.
                cryptoStream.Read(byTextoDeCifrado, 0, byTextoDeCifrado.Length);

                strRetorno = conversorTexto.GetString(byTextoDeCifrado).Replace("\0", "");
            }
            catch (Exception err)
            {
                m_errException = err;
                return(strRetorno);
            }
            return(strRetorno);
        }
Пример #30
0
        public static String Decrypt(String input, String pass)
        {
            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(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();
                byte[] Buffer = Convert.FromBase64String(input);
                decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length));
                return(decrypted);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Пример #31
0
        /// <summary>
        /// 通过公钥做key进行解密,AES算法
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string DecryptByPublicKey(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(null);
            }

            var content = File.ReadAllText(PublicKeySavePath.Replace("~", CallContext_Parameter.ServerRootPath));
            var key     = ComFunc.getMD5_String(ComFunc.Base64Code(content));

            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));
        }
Пример #32
0
            public static string Decrypt(string CipherText, string Password,
                string Salt, string HashAlgorithm,
                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);
                System.Security.Cryptography.PasswordDeriveBytes DerivedPassword = new System.Security.Cryptography.PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
                byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
                System.Security.Cryptography.RijndaelManaged SymmetricKey = new System.Security.Cryptography.RijndaelManaged();
                SymmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;
                byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
                int ByteCount = 0;
                using (System.Security.Cryptography.ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
                {
                    using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                    {
                        using (System.Security.Cryptography.CryptoStream CryptoStream = new System.Security.Cryptography.CryptoStream(MemStream, Decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                        {

                            ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                            MemStream.Close();
                            CryptoStream.Close();
                        }
                    }
                }
                SymmetricKey.Clear();
                return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
            }
Пример #33
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="cryptString">密文</param>
        /// <returns>原文</returns>
        public static string DecryptToString(this string cryptString)
        {
            if (cryptString.Length == 0)
            {
                return(cryptString);
            }

            byte[] cryptKey = System.Convert.FromBase64String(CryptKey);
            byte[] cryptIV  = System.Convert.FromBase64String(CryptIV);
            byte[] array    = System.Convert.FromBase64String(cryptString);
            //if (array.Length != 16)
            //    return cryptString;

            System.Security.Cryptography.RijndaelManaged rijndaelManaged = new System.Security.Cryptography.RijndaelManaged();
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(cryptKey, cryptIV), System.Security.Cryptography.CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            return(System.Text.Encoding.UTF8.GetString(memoryStream.ToArray()));
        }
Пример #34
0
        /// <summary>
        /// Initializa os objetos necessários para realizar criptografia e descriptografia.
        /// </summary>
        private void Initialize()
        {
            System.Security.Cryptography.RijndaelManaged v_rijndael;
            System.Security.Cryptography.Rfc2898DeriveBytes v_passwordbytes;
            byte[] v_initvectorbytes;
            byte[] v_keybytes;

            v_rijndael = new System.Security.Cryptography.RijndaelManaged();
            v_rijndael.Mode = System.Security.Cryptography.CipherMode.CBC;

            v_initvectorbytes = System.Text.Encoding.ASCII.GetBytes(this.v_initvector);

            v_passwordbytes = new System.Security.Cryptography.Rfc2898DeriveBytes(this.v_password, v_initvectorbytes, 1);
            v_keybytes = v_passwordbytes.GetBytes(this.v_keysize / 8);

            this.v_encryptor = v_rijndael.CreateEncryptor(v_keybytes, v_initvectorbytes);
            this.v_decryptor = v_rijndael.CreateDecryptor(v_keybytes, v_initvectorbytes);
        }
Пример #35
0
            /// <summary>
            /// Decrypt a stream based on fixed internal keys
            /// </summary>
            /// <param name="EncryptedStream"></param>
            /// <returns></returns>
            private MemoryStream DecryptStream(Stream EncryptedStream)
            {
                try
                {
                    System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                    Enc.KeySize = 256;
                    // KEY is 32 byte array
                    Enc.Key = LineMapKeys.ENCKEY;
                    // IV is 16 byte array
                    Enc.IV = LineMapKeys.ENCIV;

                    var cryptoStream = new System.Security.Cryptography.CryptoStream(EncryptedStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);

                    byte[] buf = null;
                    buf = new byte[1024];
                    MemoryStream DecryptedStream = new MemoryStream();
                    while (EncryptedStream.Length > 0)
                    {
                        var l = cryptoStream.Read(buf, 0, 1024);
                        if (l == 0)
                        {
                            break;                             // TODO: might not be correct. Was : Exit Do
                        }
                        if (l < 1024)
                        {
                            Array.Resize(ref buf, l);
                        }
                        DecryptedStream.Write(buf, 0, buf.GetUpperBound(0) + 1);
                        if (l < 1024)
                        {
                            break;                             // TODO: might not be correct. Was : Exit Do
                        }
                    }
                    DecryptedStream.Position = 0;
                    return(DecryptedStream);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", ex.ToString()));
                    // any problems, nothing much to do, so return an empty stream
                    return(new MemoryStream());
                }
            }
Пример #36
0
        /// <summary>Deszyfruje przekazany strumień danych.</summary>
        /// <param name="cipherStream">Zaszyfrowany strumień danych.</param>
        /// <param name="decryptedStream">Odszyfrowany strumień bajtów.</param>
        /// <param name="key">Klucz deszyfrujący. Maksymalnie 256 bitów, minimalnie 128 bitów, przeskok o 64 bity.</param>
        /// <param name="iv">Wektor inicjalizacji. Rozmiar 128 bitów.</param>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="System.ArgumentException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException"></exception>
        public static void Decrypt(System.IO.Stream cipherStream, System.IO.Stream decryptedStream, byte[] key, byte[] iv)
        {
            if (cipherStream == null)
            {
                throw new System.ArgumentNullException("cipherStream");
            }
            if (cipherStream.CanRead == false)
            {
                throw new System.ArgumentException("Argument 'cipherStream' is not readable.");
            }

            if (decryptedStream == null)
            {
                throw new System.ArgumentNullException("decryptedStream");
            }
            if (decryptedStream.CanWrite == false)
            {
                throw new System.ArgumentException("Argument 'decryptedStream' is not writable.");
            }

            if (key == null)
            {
                throw new System.ArgumentNullException("key");
            }
            if (key.Length != 16 && key.Length != 22 && key.Length != 32)
            {
                throw new System.ArgumentException("Argument 'key' does not mach the block size for this algorithm.");
            }

            if (iv == null)
            {
                throw new System.ArgumentNullException("iv");
            }
            if (iv.Length != 16)
            {
                throw new System.ArgumentException("Argument 'iv' does not mach the block size for this algorithm.");
            }

            cipherStream.Position    = 0;
            decryptedStream.Position = 0;

            System.Security.Cryptography.ICryptoTransform decryptor = null;

            try
            {
                using (System.Security.Cryptography.RijndaelManaged algoritmCrypt = new System.Security.Cryptography.RijndaelManaged())
                {
                    decryptor = algoritmCrypt.CreateDecryptor(key, iv);
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(
                               cipherStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        cs.CopyTo(decryptedStream);
                        decryptedStream.Position = 0;
                    }
                }
            }
            finally
            {
                if (decryptor != null)
                {
                    decryptor.Dispose();
                }
            }
        }
Пример #37
0
        private byte[] Decrypt(byte[] EncData)
        {
            byte[] Result = null;

            try
            {
                System.Security.Cryptography.RijndaelManaged Enc = new System.Security.Cryptography.RijndaelManaged();
                Enc.KeySize = 256;
                Enc.Key = this.Encryption_Key();
                Enc.IV = this.Encryption_IV();

                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncData);
                System.Security.Cryptography.CryptoStream cryptoStream = null;
                cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, Enc.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read);

                byte[] TempDecryptArr = null;
                TempDecryptArr = new byte[EncData.Length + 1];
                int decryptedByteCount = 0;
                decryptedByteCount = cryptoStream.Read(TempDecryptArr, 0, EncData.Length);

                cryptoStream.Close();
                memoryStream.Close();
                cryptoStream.Dispose();
                memoryStream.Dispose();

                Result = new byte[decryptedByteCount + 1];
                Array.Copy(TempDecryptArr, Result, decryptedByteCount);
            }
            catch (Exception)
            {
                Result = null;
            }

            return Result;
        }
Пример #38
0
        /// <SUMMARY>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </SUMMARY>
        /// <PARAM name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </PARAM>
        /// <PARAM name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </PARAM>
        /// <PARAM name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </PARAM>
        /// <PARAM name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </PARAM>
        /// <PARAM name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </PARAM>
        /// <PARAM name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </PARAM>
        /// <PARAM name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </PARAM>
        /// <RETURNS>
        /// Decrypted string value.
        /// </RETURNS>
        /// <REMARKS>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </REMARKS>
        public string Decrypt(string cipherText)
        {
            // Convert strings defining encryption key characteristics to byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            // Convert our ciphertext to a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            System.Security.Cryptography.PasswordDeriveBytes password = new System.Security.Cryptography.PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            System.Security.Cryptography.RijndaelManaged symmetricKey = new System.Security.Cryptography.RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            System.Security.Cryptography.ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                keyBytes,
                initVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream,
                                                                                                                   decryptor,
                                                                                                                   System.Security.Cryptography.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 ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                       0,
                                                       plainTextBytes.Length);

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();

            // Convert decrypted data to a string.
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                       0,
                                                       decryptedByteCount);

            // Return decrypted string.
            return(plainText);
        }
        /// <summary>
        /// 文字列を復号化
        /// </summary>
        /// <param name="sourceString">暗号化文字列</param>
        /// <param name="password">パスワード</param>
        /// <returns>復号化後文字列</returns>
        public string DecryptString(string sourceString, string password)
        {
            byte[] key, iv, strBytes, decBytes;
            System.Security.Cryptography.RijndaelManaged rijndael;
            System.Security.Cryptography.ICryptoTransform decryptor;

            // 複合化(コンバートあり)
            try {
                // v2.0
                rijndael = new System.Security.Cryptography.RijndaelManaged();
                GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 100);
                rijndael.Key = key;
                rijndael.IV = iv;
                strBytes = System.Convert.FromBase64String(sourceString);
                decryptor = rijndael.CreateDecryptor();
                decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                decryptor.Dispose();
            } catch (Exception) {
                try {
                    // v1.0-1.3
                    rijndael = new System.Security.Cryptography.RijndaelManaged();
                    GenerateKeyFromPassword(password, rijndael.KeySize, out key, rijndael.BlockSize, out iv, 1000);
                    rijndael.Key = key;
                    rijndael.IV = iv;
                    strBytes = System.Convert.FromBase64String(sourceString);
                    decryptor = rijndael.CreateDecryptor();
                    decBytes = decryptor.TransformFinalBlock(strBytes, 0, strBytes.Length);
                    decryptor.Dispose();
                } catch (Exception) {
                    throw;
                }
            }

            return System.Text.Encoding.UTF8.GetString(decBytes);
        }
Пример #40
0
        private byte[] AESDecrypt(byte[] data, int index, int count, byte[] key)
        {
            byte[] decryptedBytes = null;

            //  Create uninitialized Rijndael encryption object.
             System.Security.Cryptography.RijndaelManaged symmetricKey = new  System.Security.Cryptography.RijndaelManaged();

            // It is required that the encryption mode is Electronic Codebook (ECB)
            // see MS-OFFCRYPTO v1.0 2.3.4.7 pp 39.
            symmetricKey.Mode = System.Security.Cryptography.CipherMode.ECB;
            symmetricKey.Padding = System.Security.Cryptography.PaddingMode.None;
            symmetricKey.KeySize = keySize;
            // symmetricKey.IV = null; // new byte[16];
            // symmetricKey.Key = key;

            //  Generate decryptor from the existing key bytes and initialization
            //  vector. Key size will be defined based on the number of the key
            //  bytes.
            System.Security.Cryptography.ICryptoTransform decryptor;
            decryptor = symmetricKey.CreateDecryptor(key, null);

            //  Define memory stream which will be used to hold encrypted data.
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(data, index, count))
            {
                //  Define memory stream which will be used to hold encrypted data.
                using (System.Security.Cryptography.CryptoStream cryptoStream
                        = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.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 ciphertext;
                    //  plaintext is never longer than ciphertext.
                    decryptedBytes = new byte[data.Length];
                    int decryptedByteCount = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);

                    return decryptedBytes;
                }
            }
        }