private void Decrypt (ICryptoTransform trans, byte[] input, byte[] output)
{
	int bs = trans.InputBlockSize;
	int full = input.Length / bs;
	int partial = input.Length % bs;
	int pos = 0;
	for (int i=0; i < full; i++) {
		trans.TransformBlock (input, pos, bs, output, pos);
		pos += bs;
	}
	if (partial > 0) {
		byte[] final = trans.TransformFinalBlock (input, pos, partial);
		Array.Copy (final, 0, output, pos, partial);
	}
}
        private static void EncryptDecryptAndDispose(ICryptoTransform crypto, ICryptoTransform decrypto, byte[] data)
        {
            var encryptedData = crypto.TransformFinalBlock(data, 0, data.Length);
            var decryptedData = decrypto.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            // NOTE: no need to check if they are equal
            //if (!decryptedData.AllEqual(data))
               // throw new InvalidProgramException();

            crypto.Dispose();
            decrypto.Dispose();
        }
        private void InvalidInput_Base64Transform(ICryptoTransform transform)
        {
            byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa");

            Assert.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformBlock(Array.Empty<byte>(), -1, 0, null, 0));
            Assert.Throws<ArgumentNullException>("dst", () => transform.TransformBlock(data_4bytes, 0, 4, null, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformBlock(Array.Empty<byte>(), 0, 1, null, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformBlock(Array.Empty<byte>(), 1, 0, null, 0));

            Assert.Throws<ArgumentNullException>("inputBuffer", () => transform.TransformFinalBlock(null, 0, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
            Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty<byte>(), -1, 0));
            Assert.Throws<ArgumentException>(null, () => transform.TransformFinalBlock(Array.Empty<byte>(), 1, 0));
        }
        private BufferChunk SymmetricEncryption(RtpPacket packet,ICryptoTransform crypto)
        {
            BufferChunk payload = packet.Payload;

            byte[] data = crypto.TransformFinalBlock(payload.Buffer, payload.Index, payload.Length);

            return new BufferChunk(data);
        }
Exemple #5
0
        /// <summary>
        /// Decrypts the informed string
        /// </summary>
        /// <param name="str">The string that will be decrypted</param>
        /// <returns>The decrypted string</returns>
        public static string Decrypt(string str)
        {
            try
            {
                arrResult = new byte[0];
                arrKey = md5.ComputeHash(utf8.GetBytes(key));

                tripleDES.Key = arrKey;
                tripleDES.Mode = CipherMode.ECB;
                tripleDES.Padding = PaddingMode.PKCS7;

                arrBytes = Convert.FromBase64String(str);
                cryptoTransform = tripleDES.CreateDecryptor();
                arrResult = cryptoTransform.TransformFinalBlock(arrBytes, 0, arrBytes.Length);

                return utf8.GetString(arrResult);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error while decrypting: " + e.Message);
                return string.Empty;
            }
        }
Exemple #6
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="text">待解密的字符串</param>
        /// <param name="sKey">解密密钥</param>
        /// <returns></returns>
        public static string Decrypt(string text, string sKey)
        {
            defaultIV = "4R38WE5E";

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            des.Key     = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV      = ASCIIEncoding.ASCII.GetBytes(defaultIV);
            des.Mode    = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            ICryptoTransform DESDecrypt = des.CreateDecryptor();
            string           result     = string.Empty;

            try
            {
                byte[] Buffer = Convert.FromBase64String(text);
                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Exemple #7
0
        /// <summary>
        /// AES256位加密
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <returns></returns>
        public static string AESEncrypt(string toEncrypt)
        {
            byte[] keyArray       = UTF8Encoding.UTF8.GetBytes(aeskey);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();

            rDel.Key     = keyArray;
            rDel.Mode    = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            //     return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            StringBuilder ret = new StringBuilder();

            foreach (byte b in resultArray)
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return(ret.ToString());
        }
Exemple #8
0
        /// <summary>
        /// Encrypts a string
        /// </summary>
        public string Encrypt(string originalString)
        {
            var returnValue = TypeExtension.DefaultString;

            try
            {
                var              saltedString  = originalString + this.Salt;
                TripleDES        des           = CreateDes();
                ICryptoTransform encryptor     = des.CreateEncryptor();
                var              encryptedByte = Encoding.Unicode.GetBytes(saltedString);
                // Final encryption and return
                returnValue = Convert.ToBase64String(encryptor.TransformFinalBlock(encryptedByte, 0, encryptedByte.Length));
                if (this.EncodeForURL)
                {
                    returnValue = UrlEncoder.Encode(returnValue);
                }
            }
            catch
            {
                returnValue = TypeExtension.DefaultString;
            }

            return(returnValue);
        }
Exemple #9
0
        private static void DoesNotSupportMode(CipherMode mode)
        {
            using (Aes aes = AesFactory.Create())
            {
                // One of the following should throw:
                // aes.Mode = invalidMode
                // aes.CreateEncryptor() (with an invalid Mode value)
                // transform.Transform[Final]Block() (with an invalid Mode value)

                Assert.Throws <CryptographicException>(
                    () =>
                {
                    aes.Mode = mode;

                    // If assigning the Mode property did not fail, then it should reflect what we asked for.
                    Assert.Equal(mode, aes.Mode);

                    using (ICryptoTransform transform = aes.CreateEncryptor())
                    {
                        transform.TransformFinalBlock(Array.Empty <byte>(), 0, 0);
                    }
                });
            }
        }
Exemple #10
0
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="txt"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string Decrypt(string txt, string key)
 {
     try
     {
         byte[]   inputBuffer = Convert.FromBase64String(txt);
         Rijndael rijndael    = new RijndaelManaged();
         MD5      md          = new MD5CryptoServiceProvider();
         rijndael.BlockSize = 0x80;
         rijndael.KeySize   = 0x80;
         rijndael.Mode      = CipherMode.CBC;
         rijndael.Padding   = PaddingMode.PKCS7;
         rijndael.IV        = new byte[0x10];
         rijndael.Key       = md.ComputeHash(Encoding.UTF8.GetBytes(key));
         ICryptoTransform transform  = rijndael.CreateDecryptor();
         byte[]           byteResult = transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
         return(Encoding.UTF8.GetString(byteResult));
     }
     catch (Exception ex)
     {
         var log = LogManager.GetLogger("EncryptUtils.Decrypt");
         log.Error(ex);
         return(string.Empty);
     }
 }
Exemple #11
0
        public string AesDecryption(string toDecrypt, string key)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);

            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);



            RijndaelManaged rDel = new RijndaelManaged();

            rDel.Key = keyArray;

            rDel.Mode = CipherMode.ECB;

            rDel.Padding = PaddingMode.PKCS7;



            ICryptoTransform cTransform = rDel.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemple #12
0
        public static string AESEncrypt(string str, string strkey, string strivKey, bool isVasEncrypt = false)
        {
            var aesCipher = new AesManaged
            {
                KeySize   = 128,
                BlockSize = 128,
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.PKCS7
            };

            var keyStr = KeyGenerator(strkey);
            var key    = Convert.FromBase64String(keyStr);
            var ivKey  = Encoding.UTF8.GetBytes(strivKey);
            var input  = str;
            var ivStr  = Convert.ToBase64String(ivKey);

            aesCipher.Key = key;
            aesCipher.IV  = ivKey;
            byte[]           b = System.Text.Encoding.UTF8.GetBytes(str); // plain text to be encrypted
            ICryptoTransform encryptTransform = aesCipher.CreateEncryptor();

            byte[] cipherText = encryptTransform.TransformFinalBlock(b, 0, b.Length);
            return(Convert.ToBase64String(cipherText));
        }
Exemple #13
0
        // encryption with AES-128
        static byte[] encryptWithAES128(string input, byte[] key, byte[] IV)
        {
            // convert input string to byte array
            byte[] byteInput = Encoding.Default.GetBytes(input);

            // create AES object from System.Security.Cryptography
            RijndaelManaged aesObject = new RijndaelManaged();

            // since we want to use AES-128
            aesObject.KeySize = 128;
            // block size of AES is 128 bits
            aesObject.BlockSize = 128;
            // mode -> CipherMode.*
            aesObject.Mode = CipherMode.CFB;
            // feedback size should be equal to block size
            aesObject.FeedbackSize = 128;
            // set the key
            aesObject.Key = key;
            // set the IV
            aesObject.IV = IV;
            // create an encryptor with the settings provided
            ICryptoTransform encryptor = aesObject.CreateEncryptor();

            byte[] result = null;

            try
            {
                result = encryptor.TransformFinalBlock(byteInput, 0, byteInput.Length);
            }
            catch (Exception e)               // if encryption fails
            {
                Console.WriteLine(e.Message); // display the cause
            }

            return(result);
        }
Exemple #14
0
        public string Decrypt(string decryptText, string decryptKey = null, bool useHashing = false)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(decryptText);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();

            if (string.IsNullOrEmpty(decryptKey))
            {
                decryptKey = (string)settingsReader.GetValue("SecurityKey", typeof(string));
            }

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(decryptKey));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(decryptKey);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key     = keyArray;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemple #15
0
        private byte[] BuildPack(CMD c, byte[] data)
        {
            byte[] cmd = BitConverter.GetBytes((uint)c);
            byte[] src = new byte[cmd.Length + data.Length];
            Array.Copy(cmd, 0, src, 0, cmd.Length);
            Array.Copy(data, 0, src, cmd.Length, data.Length);

            byte[] result;
            try
            {
                ICryptoTransform cTransform = m_aes.CreateEncryptor();
                result = cTransform.TransformFinalBlock(src, 0, src.Length);
            }
            catch (Exception e)
            {
                Logger.Trace(e);
                return(null);
            }

            byte[] ret = new byte[result.Length + 4];
            Array.Copy(BitConverter.GetBytes(result.Length), ret, 4);
            Array.Copy(result, 0, ret, 4, result.Length);
            return(ret);
        }
Exemple #16
0
        public static string Encrypt256(string text)
        {
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.BlockSize = 128;
            aes.KeySize   = 256;
            aes.IV        = Encoding.UTF8.GetBytes(AesIV256);
            aes.Key       = Encoding.UTF8.GetBytes(AesKey256);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;

            // Convert string to byte array
            byte[] src = Encoding.Unicode.GetBytes(text);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return(Convert.ToBase64String(dest));
            }
        }
Exemple #17
0
        /// <summary>
        /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
        /// </summary>
        /// <param name="cipherString">encrypted string</param>
        /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
        /// <returns></returns>
        public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            cipherString = cipherString.Replace(" ", "+");
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            //Get your key from config file to open the lock!
            string key = "kj@18231";

            //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
            {
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            }

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key     = keyArray;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemple #18
0
        // encrypt or decrypt a string
        // for encrypt type=true
        // for decrypt type=false
        public string EncryptOrDecrypt(bool type, string plainStr)
        {
            RijndaelManaged aesEncryption = new RijndaelManaged();

            aesEncryption.KeySize   = 256;
            aesEncryption.BlockSize = 128;
            aesEncryption.Mode      = CipherMode.CBC;
            aesEncryption.Padding   = PaddingMode.PKCS7;
            aesEncryption.IV        = ASCIIEncoding.UTF8.GetBytes("0123456789012345");
            aesEncryption.Key       = md5(this.CIPHER_KEY);
            if (type)
            {
                ICryptoTransform crypto     = aesEncryption.CreateEncryptor();
                byte[]           plainText  = ASCIIEncoding.UTF8.GetBytes(plainStr);
                byte[]           cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
                return(Convert.ToBase64String(cipherText));
            }
            else
            {
                ICryptoTransform decrypto       = aesEncryption.CreateDecryptor();
                byte[]           encryptedBytes = Convert.FromBase64CharArray(plainStr.ToCharArray(), 0, plainStr.Length);
                return(ASCIIEncoding.UTF8.GetString(decrypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length)));
            }
        }
Exemple #19
0
        //AES-256 Encrypt
        private string Encrypt256(string text, string key, string IV)
        {
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.BlockSize = 128;
            aes.KeySize   = 256;
            aes.Key       = Encoding.ASCII.GetBytes(key);
            aes.IV        = Encoding.ASCII.GetBytes(IV);
            aes.Mode      = CipherMode.ECB;
            aes.Padding   = PaddingMode.None;

            // Convert string to byte array
            byte[] src = Encoding.Default.GetBytes(text);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor(aes.Key, aes.IV))
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return(Convert.ToBase64String(dest));
            }
        }
Exemple #20
0
 /// <summary>
 /// AES加密 EBC PKCS7 HEX UTF8 加密
 /// </summary>
 /// <param name="text">明文字符串</param>
 /// <param name="key">秘钥</param>
 /// <returns>密文</returns>
 public static string AesStr_EPHU(string text, string key, string iv = null)
 {
     RijndaelManaged rijndaelCipher = new RijndaelManaged();
     rijndaelCipher.Mode = CipherMode.ECB;
     rijndaelCipher.Padding = PaddingMode.PKCS7;
     rijndaelCipher.KeySize = 128;
     rijndaelCipher.BlockSize = 128;
     byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
     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;
     if (!string.IsNullOrEmpty(iv))
     {
         byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv);
         rijndaelCipher.IV = ivBytes;
     }
     ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
     byte[] plainText = Encoding.UTF8.GetBytes(text);
     byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
     return ToHexString(cipherBytes);
 }
Exemple #21
0
        public static string AesDecryptHex(string text, string key)
        {
            try
            {
                using (RijndaelManaged rm = new RijndaelManaged())
                {
                    rm.Key     = Encoding.UTF8.GetBytes(key);
                    rm.Mode    = CipherMode.ECB;
                    rm.Padding = PaddingMode.PKCS7;

                    using (ICryptoTransform cTransform = rm.CreateDecryptor())
                    {
                        byte[] bytes   = ConvertUtil.HexStringToBytes(text);
                        byte[] results = cTransform.TransformFinalBlock(bytes, 0, bytes.Length);

                        return(Encoding.UTF8.GetString(results));
                    }
                }
            }
            catch
            {
                return(null);
            }
        }
Exemple #22
0
        public string Encrypt(string text, string password)
        {
            if (text == null)
            {
                return(null);
            }
            using (var aesProvider = new AesCryptoServiceProvider())
            {
                aesProvider.Mode    = CipherMode.CBC;
                aesProvider.Padding = PaddingMode.PKCS7;

                var    Rfc   = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes("phi lookup request"), 1000);
                byte[] bytes = Rfc.GetBytes(16);
                aesProvider.IV  = bytes;
                aesProvider.Key = bytes;

                ICryptoTransform encryptor = aesProvider.CreateEncryptor();

                byte[] inputBytes  = Encoding.UTF8.GetBytes(text);
                byte[] outputBytes = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);

                return(Convert.ToBase64String(outputBytes));
            }
        }
Exemple #23
0
        /// <summary>

        /// DES3

        /// </summary>

        /// <param name="encryptionStr"></param>

        /// <param name="key"></param>

        /// <returns></returns>

        public string Des3Encryption(string encryptionStr, string key)
        {
            TripleDESCryptoServiceProvider _pTripDes = new TripleDESCryptoServiceProvider();

            _pTripDes.Key = Encoding.UTF8.GetBytes(key);

            _pTripDes.Mode = CipherMode.ECB;

            _pTripDes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            try
            {
                ICryptoTransform ery = _pTripDes.CreateEncryptor();

                byte[] buffer = Encoding.UTF8.GetBytes(encryptionStr);

                return(Convert.ToBase64String(ery.TransformFinalBlock(buffer, 0, buffer.Length)));
            }

            catch
            {
                return(string.Empty);
            }
        }
Exemple #24
0
        public static string Decrypt(string key, string cipherString, bool useHashing = true)
        {
            byte[] resultArray = null;
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = Convert.FromBase64String(cipherString);

                if (useHashing)
                {
                    using (MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider())
                    {
                        keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key));
                    }
                }
                else
                {
                    keyArray = Encoding.UTF8.GetBytes(key);
                }

                using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
                {
                    tdes.Key     = keyArray;
                    tdes.Mode    = CipherMode.ECB;
                    tdes.Padding = PaddingMode.PKCS7;

                    ICryptoTransform cTransform = tdes.CreateDecryptor();
                    resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Log(ex);
            }
            return(Encoding.UTF8.GetString(resultArray));
        }
Exemple #25
0
        /// <summary>
        /// Deobfuscate a string on UNIX.
        /// </summary>
        /// <param name="value">The string to deobfuscate</param>
        /// <returns>The clear string</returns>
        private static string UnixDeobfuscate(string value)
        {
#if __MonoCS__
            try
            {
                using (PasswordDeriveBytes pdb = new PasswordDeriveBytes(
                           GetCryptoKey(), new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }))
                    using (AesManaged myAes = new AesManaged())
                    {
                        myAes.Key = pdb.GetBytes(myAes.KeySize / 8);
                        myAes.IV  = pdb.GetBytes(myAes.BlockSize / 8);
                        using (ICryptoTransform decryptor = myAes.CreateDecryptor())
                        {
                            byte[] data    = Convert.FromBase64String(value);
                            byte[] uncrypt = decryptor.TransformFinalBlock(data, 0, data.Length);
                            return(System.Text.Encoding.UTF8.GetString(uncrypt));
                        }
                    }
            }
            catch (Exception e)
            {
                if (e is CryptographicException || e is FormatException || e is ArgumentException)
                {
                    Console.WriteLine("Your password is not obfuscated yet.");
                    Console.WriteLine("Using unobfuscated value directly might be deprecated soon, so please delete your local directories and recreate them. Thank you for your understanding.");
                    return(value);
                }
                else
                {
                    throw;
                }
            }
#else
            throw new ApplicationException("Should never be reached");
#endif
        }
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            MensagemModel mensagemModel = db.Mensagens.Find(id);

            if (mensagemModel == null)
            {
                return(HttpNotFound());
            }

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.BlockSize = 128;
            aes.KeySize   = 256;
            aes.IV        = Encoding.UTF8.GetBytes(AesIV256BD);
            aes.Key       = Encoding.UTF8.GetBytes(AesKey256BD);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            string msgE = mensagemModel.Mensagem;

            byte[] src = Convert.FromBase64String(mensagemModel.Mensagem);
            using (ICryptoTransform decrypt = aes.CreateDecryptor())
            {
                byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
                mensagemModel.Mensagem = Encoding.Unicode.GetString(dest);
            }
            string msgD = mensagemModel.Mensagem;

            TempData["msgE"] = msgE;
            TempData["msgD"] = msgD;
            //return RedirectToAction(nameof(Details));
            return(View());
        }
 /// <summary>
 /// Aes解密
 /// </summary>
 /// <param name="source">源字符串</param>
 /// <param name="key">aes密钥,长度必须32位</param>
 /// <returns>解密后的字符串</returns>
 public static string DecryptAes(string source, string key)
 {
     using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
     {
         aesProvider.Key     = GetAesKey(key);
         aesProvider.Mode    = CipherMode.ECB;
         aesProvider.Padding = PaddingMode.PKCS7;
         using (ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor())
         {
             try
             {
                 byte[] inputBuffers = Convert.FromBase64String(source);
                 byte[] results      = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                 aesProvider.Clear();
                 return(Encoding.UTF8.GetString(results));
             }
             catch (FormatException ex)
             {
                 //throw new UserFriendlyException("密文格式错误")
                 throw new Exception("密文格式错误");
             }
         }
     }
 }
Exemple #28
0
        public static string MD5Decrypt(this string password)
        {
            byte[] keyArray;
            //convierte el texto en una secuencia de bytes
            byte[] Array_a_Descifrar =
                Convert.FromBase64String(password);

            //se llama a las clases que tienen los algoritmos
            //de encriptación se le aplica hashing
            //algoritmo MD5
            MD5CryptoServiceProvider hashmd5 =
                new MD5CryptoServiceProvider();

            keyArray = hashmd5.ComputeHash(
                UTF8Encoding.UTF8.GetBytes(key));

            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes =
                new TripleDESCryptoServiceProvider();

            tdes.Key     = keyArray;
            tdes.Mode    = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform =
                tdes.CreateDecryptor();

            byte[] resultArray =
                cTransform.TransformFinalBlock(Array_a_Descifrar,
                                               0, Array_a_Descifrar.Length);

            tdes.Clear();
            //se regresa en forma de cadena
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemple #29
0
        /// <summary>
        /// aes解密 2.0 由62进制解密
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AESDecrypt62(string toDecrypt, string key)
        {
            key = checkKeyLength(key);
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
            //  byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

            int halfInputLength = toDecrypt.Length / 2;

            byte[] toDecryptArray = new byte[halfInputLength];
            for (int x = 0; x < halfInputLength; x++)
            {
                Int64 i = ConvertSixtytwoToTen(toDecrypt.Substring(x * 2, 2));
                toDecryptArray[x] = (byte)i;
            }
            RijndaelManaged rDel = new RijndaelManaged();

            rDel.Key     = keyArray;
            rDel.Mode    = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
            return(UTF8Encoding.UTF8.GetString(resultArray));
        }
Exemple #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="str">f527e75a9cf89ecb23a32fa3e8b2c650</param>
        /// <param name="key">16位</param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(null);
            }
            List <string> list = new List <string>();

            for (int i = 0; i < str.Length; i = i + 2)
            {
                list.Add(str.Substring(i, 2));
            }
            string a4 = (string.Join("-", list.ToArray()));

            String[] arr2           = a4.ToUpper().Split('-');
            byte[]   toEncryptArray = new byte[arr2.Length];
            for (int i = 0; i < arr2.Length; i++)
            {
                toEncryptArray[i] = Convert.ToByte(arr2[i], 16);
            }

            //Byte[] toEncryptArray = Convert.FromBase64String(content);

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

            ICryptoTransform cTransform = rm.CreateDecryptor();

            Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return(Encoding.UTF8.GetString(resultArray));
        }
Exemple #31
0
        public void Encriptar(string filename)
        {
            byte[] plano = Encoding.UTF8.GetBytes(File.ReadAllText(filename));

            using (var md5 = new MD5CryptoServiceProvider())
            {
                byte[] code = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                md5.Clear();
                using (var des = new TripleDESCryptoServiceProvider())
                {
                    des.Key     = code;
                    des.Mode    = CipherMode.ECB;
                    des.Padding = PaddingMode.PKCS7;

                    using (var memo = new MemoryStream())
                    {
                        ICryptoTransform crypt   = des.CreateEncryptor();
                        byte[]           encrypt = crypt.TransformFinalBlock(plano, 0, plano.Length);
                        des.Clear();
                        File.WriteAllBytes(filename, encrypt.ToArray());
                    }
                }
            }
        }
Exemple #32
0
 /// <summary>  
 /// AES Str类型 EBC PKCS7 HEX UTF8 NoIV解密  
 /// </summary>  
 /// <param name="data">待解密</param>  
 /// <param name="keyVal">密钥值16字节</param>  
 /// <returns></returns>  
 public static string UnAesStr_EPHU(string data, string keyVal, string iv = null)
 {
     RijndaelManaged rijndaelCipher = new RijndaelManaged();
     rijndaelCipher.Mode = CipherMode.ECB;
     rijndaelCipher.Padding = PaddingMode.PKCS7;
     rijndaelCipher.KeySize = 128;
     rijndaelCipher.BlockSize = 128;
     byte[] encryptedData = StrToHexByte(data);
     byte[] pwdBytes = Encoding.UTF8.GetBytes(keyVal);
     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;
     if (!string.IsNullOrEmpty(iv))
     {
         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);
 }
Exemple #33
0
        public void send(byte[] data)
        {
            try
            {
                lock (_encLock)
                {
                    if (_secured)
                    {
                        data = _encryptor.TransformFinalBlock(data, 0, data.Length);
                    }
                }

                NetworkStream stream = _client.GetStream();

                lock (stream)
                    _formatter.Serialize(stream, data);

                if (OnDataSentEvent != null)
                {
                    OnDataSentEvent(this, data);
                }
            }
            catch { }
        }
Exemple #34
0
        /// <summary>
        /// 3des解密字符串
        /// </summary>
        /// <param name="text">要解密的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>解密后的字符串</returns>
        /// <remarks>静态方法,指定编码方式</remarks>
        public static string Decrypt(string text, string key, Encoding encoding)
        {
            TripleDESCryptoServiceProvider DES     = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider       hashMD5 = new MD5CryptoServiceProvider();

            DES.Key  = hashMD5.ComputeHash(encoding.GetBytes(key));
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESDecrypt = DES.CreateDecryptor();

            string result = string.Empty;

            try
            {
                byte[] Buffer = Convert.FromBase64String(text);
                result = encoding.GetString(DESDecrypt.TransformFinalBlock
                                                (Buffer, 0, Buffer.Length));
            }
            catch (Exception e)
            {
                throw (new Exception("Invalid Key or input string is not a valid base64 string", e));
            }
            return(result);
        }
Exemple #35
0
        private static byte[] Encrypt(byte[] toEncrypt, byte[] key)
        {
            List <byte> te = toEncrypt.ToList();

            while (te.Count % 16 != 0)
            {
                te.Add(0x00);
            }
            toEncrypt = te.ToArray();
            AesCryptoServiceProvider aes = CreateProvider(key);
            List <byte> K = new List <byte>();

            K = key.ToList();
            while (K.Count < 32)
            {
                K.Add(0x00);
            }
            key = K.ToArray();
            ICryptoTransform cTransform = aes.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length);
            aes.Clear();
            return(resultArray);
        }
Exemple #36
0
 internal static byte[] GenericTransform(ICryptoTransform transform,
                                     byte[] data)
 {
     List<byte> byteList = new List<byte>();
       byte[] outputBytes;
       int inputLength = data.Length;
       int inputBlockSize = transform.InputBlockSize;
       if (typeof(FromBase64Transform).IsInstanceOfType(transform)) {
     // workaround for apparent bug where FromBase64Transform.InputBlockSize
     // returns 1 when it should return 4
     inputBlockSize = 4;
       }
       int inputOffset = 0;
       outputBytes = new byte[transform.OutputBlockSize];
       if (!transform.CanTransformMultipleBlocks) {
     while (inputLength - inputOffset > inputBlockSize) {
       transform.TransformBlock(data, inputOffset, inputBlockSize,
     outputBytes, 0);
       byteList.AddRange(outputBytes);
       inputOffset += inputBlockSize;
     }
       }
       outputBytes = transform.TransformFinalBlock(data, inputOffset,
                                           inputLength - inputOffset);
       byteList.AddRange(outputBytes);
       byte[] result = byteList.ToArray();
       ClearByteList(byteList);
       return result;
 }
 /// <summary>
 /// Encrypt message by AES with given secret key and key size.
 /// </summary>
 /// <param name="encryptor">A symmetric encryptor object with key and IV</param>
 /// <param name="message">Message to be encrypted.</param>
 /// <returns>Message has been encrypted.</returns>
 private static byte[] EncrypteMessageByAes(ICryptoTransform encryptor, byte[] message)
 {
     byte[] encryptedMessage = new byte[16];
     byte[] encryptedBytes = encryptor.TransformFinalBlock(message, 0, message.Length).ToArray();
     for (int i = 0; i < 16; i++)
     {
         encryptedMessage[i] = encryptedBytes[i];
     }
     return encryptedMessage;
 }
 private static byte[] Encrypt(ICryptoTransform crypto, byte[] data)
 {
     return crypto.TransformFinalBlock(data, 0, data.Length);
 }
Exemple #39
0
        /// <summary>
        /// Does the actual work of pulling the filestreams in
        /// and passing the blocks into the crytoprovider
        /// </summary>
        /// <param name="filenames">An array of String objects, each containing a filename</param>
        /// <param name="cryptoInterface">An <see cref="ICryptoTransform"/> interface pointing to a cryptoprovider</param>
        /// <param name="blockSize">Size in bytes of the transform block / read buffer</param>
        protected void ComputeHashes(String[] filenames, ICryptoTransform cryptoInterface, int blockSize)
        {
            for (int loop = 0; loop <= filenames.GetUpperBound(0); loop++)
            {
                using (FileStream inputFile = new FileStream(filenames[loop], FileMode.Open, FileAccess.Read))
                {
                    byte[] readBuffer = new byte[(int)blockSize];
                    byte[] copyBuffer;
                    long fileLength = inputFile.Length;
                    int bytesRead = 0;
                    long totalBytesRead = 0;

                    while (totalBytesRead < fileLength)
                    {
                        bytesRead = inputFile.Read(readBuffer, 0, (int)blockSize);
                        if (bytesRead == blockSize) { copyBuffer = readBuffer; }
                        else
                        {
                            copyBuffer = new byte[bytesRead];
                            Array.Copy(readBuffer, copyBuffer, bytesRead);
                        }
                        totalBytesRead += bytesRead;
                        if (totalBytesRead == fileLength && loop == filenames.GetUpperBound(0))
                        {
                            // Last block of the last file
                            cryptoInterface.TransformFinalBlock(copyBuffer, 0, copyBuffer.Length);
                        }
                        else
                        {
                            cryptoInterface.TransformBlock(copyBuffer, 0, copyBuffer.Length, copyBuffer, 0);
                        }
                        // Report progress and
                        // check for cancellation request
                        OnHashBlockProcessed(new HasherEventArgs(HasherEventReportType.ProgressReport,
                                         filenames.Length,
                                         loop + 1,
                                         totalBytesRead,
                                         fileLength));
                        if (this.cancelRequested == true)
                        {
                            throw new OperationCanceledException();
                        }

                    }
                }
            }
            // Report hash computed
            OnHashComputed(new HasherEventArgs(HasherEventReportType.Completed, null, null, null, null));
        }
Exemple #40
0
 private unsafe byte[] Encrypt2(UnmanagedArray<byte> bytes, ICryptoTransform transform)
 {
     byte[] managedBytes = new byte[bytes.Length];
     fixed (byte* dummy = managedBytes)
     {
         try
         {
             SecurityUtil.UnmanagedBytesToManagedBytes(bytes, managedBytes);
             byte[] rv = transform.TransformFinalBlock(managedBytes, 0, managedBytes.Length);
             return rv;
         }
         finally
         {
             SecurityUtil.Clear(managedBytes);
         }
     }
 }
Exemple #41
0
 private unsafe UnmanagedArray<byte> Decrypt2(byte[] bytes, ICryptoTransform transform)
 {
     byte[] managedBytes = transform.TransformFinalBlock(bytes, 0, bytes.Length);
     //pin it ASAP. this is a small race condition that is unavoidable due
     //to the way the crypto API's return byte[].
     fixed (byte* dummy = managedBytes)
     {
         try
         {
             UnmanagedByteArray rv = new UnmanagedByteArray(managedBytes.Length);
             for (int i = 0; i < rv.Length; i++)
             {
                 rv[i] = managedBytes[i];
             }
             return rv;
         }
         finally
         {
             SecurityUtil.Clear(managedBytes);
         }
     }
 }
 public string AesDecrypt(ICryptoTransform decrypter, string encryptedString)
 {
     var inBytes = Convert.FromBase64String(encryptedString);
     byte[] outBlock = decrypter.TransformFinalBlock(inBytes, 0, inBytes.Length);
     return Encoding.Unicode.GetString(outBlock);
 }
 public string AesEncrypt(ICryptoTransform encryptor, string plainText)
 {
     byte[] inBlock = Encoding.Unicode.GetBytes(plainText);
     byte[] outBlock = encryptor.TransformFinalBlock(inBlock, 0, inBlock.Length);
     return Convert.ToBase64String(outBlock);
 }
Exemple #44
0
 public static byte[] Encrypt(ICryptoTransform transform, byte[] buffer)
 {
     return transform.TransformFinalBlock(buffer, 0, buffer.Length);
 }
 public static GStruct2 smethod_4(ICryptoTransform icryptoTransform_1, byte[] byte_0)
 {
     GStruct2 result;
     byte_0 = icryptoTransform_1.TransformFinalBlock(byte_0, 0, byte_0.Length);
     MemoryStream memoryStream_0 = new MemoryStream(byte_0);
     BinaryReader binaryReader_0 = new BinaryReader(memoryStream_0);
     if (binaryReader_0.ReadBoolean())
     {
         int num = binaryReader_0.ReadInt32();
         DeflateStream deflateStream = new DeflateStream(memoryStream_0, CompressionMode.Decompress, false);
         byte[] array = new byte[num - 1 + 1];
         deflateStream.Read(array, 0, array.Length);
         deflateStream.Close();
         memoryStream_0 = new MemoryStream(array);
         binaryReader_0 = new BinaryReader(memoryStream_0);
     }
     GStruct2 gStruct = default(GStruct2);
     gStruct.byte_0 = binaryReader_0.ReadByte();
     gStruct.byte_1 = binaryReader_0.ReadByte();
     List<object> list_0 = new List<object>();
     if (binaryReader_0.ReadBoolean())
     {
         gStruct.guid_0 = new Guid(binaryReader_0.ReadBytes(16));
     }
     while (memoryStream_0.Position != memoryStream_0.Length)
     {
         switch (binaryReader_0.ReadByte())
         {
             case 0:
                 list_0.Add(binaryReader_0.ReadBoolean());
                 break;
             case 1:
                 list_0.Add(binaryReader_0.ReadByte());
                 break;
             case 2:
                 list_0.Add(binaryReader_0.ReadBytes(binaryReader_0.ReadInt32()));
                 break;
             case 3:
                 list_0.Add(binaryReader_0.ReadChar());
                 break;
             case 4:
                 list_0.Add(binaryReader_0.ReadString().ToCharArray());
                 break;
             case 5:
                 list_0.Add(binaryReader_0.ReadDecimal());
                 break;
             case 6:
                 list_0.Add(binaryReader_0.ReadDouble());
                 break;
             case 7:
                 list_0.Add(binaryReader_0.ReadInt32());
                 break;
             case 8:
                 list_0.Add(binaryReader_0.ReadInt64());
                 break;
             case 9:
                 list_0.Add(binaryReader_0.ReadSByte());
                 break;
             case 10:
                 list_0.Add(binaryReader_0.ReadInt16());
                 break;
             case 11:
                 list_0.Add(binaryReader_0.ReadSingle());
                 break;
             case 12:
                 list_0.Add(binaryReader_0.ReadString());
                 break;
             case 13:
                 list_0.Add(binaryReader_0.ReadUInt32());
                 break;
             case 14:
                 list_0.Add(binaryReader_0.ReadUInt64());
                 break;
             case 15:
                 list_0.Add(binaryReader_0.ReadUInt16());
                 break;
             case 16:
                 list_0.Add(DateTime.FromBinary(binaryReader_0.ReadInt64()));
                 break;
             case 17:
                 {
                     string[] array2 = new string[binaryReader_0.ReadInt32() - 1 + 1];
                     int arg_381_0 = 0;
                     int num2 = array2.Length - 1;
                     for (int i = arg_381_0; i <= num2; i++)
                     {
                         array2[i] = binaryReader_0.ReadString();
                     }
                     list_0.Add(array2);
                     break;
                 }
             case 18:
                 {
                     List<object> arg_3D0_0 = list_0;
                     Guid guid = new Guid(binaryReader_0.ReadBytes(16));
                     arg_3D0_0.Add(guid);
                     break;
                 }
             case 19:
                 {
                     List<object> arg_401_0 = list_0;
                     Size size = new Size(binaryReader_0.ReadInt32(), binaryReader_0.ReadInt32());
                     arg_401_0.Add(size);
                     break;
                 }
             case 20:
                 {
                     List<object> arg_443_0 = list_0;
                     Rectangle rectangle = new Rectangle(binaryReader_0.ReadInt32(), binaryReader_0.ReadInt32(), binaryReader_0.ReadInt32(), binaryReader_0.ReadInt32());
                     arg_443_0.Add(rectangle);
                     break;
                 }
             case 21:
                 list_0.Add(new Version(binaryReader_0.ReadString()));
                 break;
         }
     }
     gStruct.object_0 = list_0.ToArray();
     result = gStruct;
     list_0.Clear();
     binaryReader_0.Close();
     return result;
 }
 internal static void AssertTransformsEqual(byte[] plainTextBytes, ICryptoTransform decryptor, byte[] encryptedBytes)
 {
     byte[] decrypted = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
     Assert.Equal(plainTextBytes, decrypted);
 }
Exemple #47
0
        private static byte[] TransformRecordBytes(BulkCipherAlgorithmType cipherType, ICryptoTransform transform, byte[] input)
        {
            if (cipherType != BulkCipherAlgorithmType.AEAD) {
                // In case of non-AEAD cipher algorithm, check that data matches block size
                if (input.Length % transform.InputBlockSize != 0) {
                    throw new Exception("Input data size doesn't match block size");
                }
            }

            int blockCount = input.Length / transform.InputBlockSize;
            if (cipherType == BulkCipherAlgorithmType.AEAD) {
                // Make sure there is enough data at TransformFinalBlock, because
                // decryption requires that the authentication tag is present
                if (blockCount > 0) {
                    blockCount--;
                }
            }

            byte[] output = new byte[blockCount * transform.OutputBlockSize];
            if (transform.CanTransformMultipleBlocks) {
                transform.TransformBlock(input, 0, blockCount*transform.InputBlockSize, output, 0);
            } else {
                for (int i=0; i<blockCount; i++) {
                    transform.TransformBlock(input, i*transform.InputBlockSize,
                                             transform.InputBlockSize,
                                             output, i*transform.OutputBlockSize);
                }
            }

            if (cipherType == BulkCipherAlgorithmType.AEAD) {
                int currentPosition = blockCount*transform.InputBlockSize;

                // Transfer the last block when encrypting or authentication tag when decrypting
                byte[] finalBytes = transform.TransformFinalBlock(input, currentPosition, input.Length-currentPosition);
                if (finalBytes == null) {
                    return null;
                } else if (finalBytes.Length > 0) {
                    byte[] finalOutput = new byte[output.Length + finalBytes.Length];
                    Buffer.BlockCopy(output, 0, finalOutput, 0, output.Length);
                    Buffer.BlockCopy(finalBytes, 0, finalOutput, output.Length, finalBytes.Length);
                    output = finalOutput;
                }
            }

            return output;
        }
Exemple #48
-1
 private static bool TestKeyDecryption(ICryptoTransform desEngine, byte[] r, int keyOffset, int hashOffset)
 {
     var testKey = desEngine.TransformFinalBlock(r.Copy(keyOffset, 8), 0, 8);
     var testHash = r.Copy(hashOffset, 20);
     return SHA1.Create().ComputeHash(testKey).IsEqualTo(testHash);
 }