CreateDecryptor() public method

public CreateDecryptor ( ) : ICryptoTransform
return ICryptoTransform
コード例 #1
0
 private static string Decrypt(byte[] cipher, string passPhrase, string salt, SymmetricAlgorithm algorithm)
 {
     var saltBytes = Encoding.UTF8.GetBytes(salt);
     algorithm.Padding = PaddingMode.None;
     using (algorithm)
     {
         using (var password = new Rfc2898DeriveBytes(passPhrase, saltBytes))
         {
             algorithm.Key = password.GetBytes(algorithm.KeySize / 8);
             algorithm.IV = password.GetBytes(algorithm.BlockSize / 8);
             using (var memStream = new MemoryStream(cipher))
             {
                 using (
                     var cryptoStream = new CryptoStream(memStream, algorithm.CreateDecryptor(),
                                                         CryptoStreamMode.Read))
                 {
                     using (var sr = new StreamReader(cryptoStream))
                     {
                         return sr.ReadToEnd();
                     }
                 }
             }
         }
     }
 }
コード例 #2
0
        /// <summary>
        /// Initialize CipherTextStealingMode with a specific symmetric algorithm
        /// </summary>
        /// <param name="symmetricAlgorithm">The symmetric algorithm</param>
        public CipherTextStealingMode(SymmetricAlgorithm symmetricAlgorithm)
        {
            // in CTS Mode there is no padding
            symmetricAlgorithm.Padding = PaddingMode.None;

            // set the symmetric algorithm's mode to ECB
            // (for single block encryption and decryption)
            symmetricAlgorithm.Mode = CipherMode.ECB;

            // get the symmetric algorithm's block size in bytes
            blockSize = symmetricAlgorithm.BlockSize / 8;
            if (blockSize != symmetricAlgorithm.IV.Length)
            {
                throw new ArgumentException(
                    "The IV size should equal to the block size.");
            }

            // initialize local IV
            iv = symmetricAlgorithm.IV;

            // initialize cipher state using the symmetric algorithms's IV
            cipherState = new byte[blockSize];
            symmetricAlgorithm.IV.CopyTo(cipherState, 0);

            // create encryptor and decryptor
            encryptor = symmetricAlgorithm.CreateEncryptor();
            decryptor = symmetricAlgorithm.CreateDecryptor();
        }
コード例 #3
0
ファイル: Crypto.cs プロジェクト: danygolden/gianfratti
        public static string DecryptString(string Value, string parKey)
        {
            mCSP = SetEnc();
            string iv = "PenS8UCVF7s=";
            mCSP.IV = Convert.FromBase64String(iv);
            string key = SetLengthString(parKey.ToString(), 32);
            mCSP.Key = Convert.FromBase64String(key);
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            Byte[] byt = new byte[64];
            try
            {
                ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
                byt = Convert.FromBase64String(Value);
                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                cs.Close();

                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw (new Exception("An error occurred while decrypting string"));
            }
        }
コード例 #4
0
ファイル: Encryption.cs プロジェクト: TheNaked/Firewind
        public static byte[] DecryptBytes(SymmetricAlgorithm symAlg, byte[] inBytes)
        {
            ICryptoTransform xfrm = symAlg.CreateDecryptor();
            byte[] outBlock = xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);

            return outBlock;
        }
コード例 #5
0
        /// <summary>
        /// 解密数据.
        /// </summary>
        /// <param name="service"> 解密处理的服务 </param>
        /// <param name="cipherText"> 被加密的字节数组 </param>
        /// <returns> 解密后的文本信息 </returns>
        public string DecryptStringFromBytes(SymmetricAlgorithm service, byte[] cipherText)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");

            // 预期返回的结果.
            string plaintext = null;

            // 创建对称解密器对象。
            ICryptoTransform decryptor = service.CreateDecryptor();

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

            // 返回.
            return plaintext;
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: sancas/ProgramacionIII
 public static byte[] Desencriptar(byte[] mensajeEncriptado,
     SymmetricAlgorithm algoritmo)
 {
     int numeroBytesDesencriptados = 0;
     // La clase SymmetricAlgorithm delega el proceso de desencriptación de datos
     // Una instancia de ICryptoTransform transforma texto plano en texto cifrado o vice versa.
     // Las siguiente sentencia demuestra como crear transformaciones usando CreateDecryptor.
     byte[] mensajeDesencriptado = new
     byte[mensajeEncriptado.Length];
     // Crear una ICryptoTransform que puede ser usada para desencriptar datos
     ICryptoTransform desencriptador =
         algoritmo.CreateDecryptor();
     // Procedemos a descifrar el mensaje
     MemoryStream memoryStream = new
     MemoryStream(mensajeEncriptado);
     // Creamos el CryptoStream
     CryptoStream cryptoStream = new CryptoStream(memoryStream,
         desencriptador, CryptoStreamMode.Read);
     // Decrypting data and get the count of plain text bytes.
     numeroBytesDesencriptados = cryptoStream.Read(mensajeDesencriptado, 0, mensajeDesencriptado.Length);
     // Liberamos recursos.
     memoryStream.Close();
     cryptoStream.Close();
     return mensajeDesencriptado;
 }
コード例 #7
0
 /// <summary>
 ///  Decrypts the offline transaction file using the TripleDES cryptography.
 /// </summary>
 /// <param name="Password"> Password to be decrypted</param>
 /// <returns></returns>
 public static string DecryptPassword(string Password)
 {
     DES = new TripleDESCryptoServiceProvider();
     byte[] encryptedBytes = Convert.FromBase64String(Password);
     byte[] decryptedBytes = DES.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
     return Encoding.UTF8.GetString(decryptedBytes);
 }
コード例 #8
0
ファイル: EncryptHelper.cs プロジェクト: hijushen/WindowDemo
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value">要解密的值</param>
        /// <returns>解密后值</returns>
        public static string DecryptString(string value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            //// 设置加密Key
            string txtKey = "tkGGRmBErvc=";
            //// 设置加密IV
            string txtIV = "Kl7ZgtM1dvQ=";
            mcsp = SetEnc();
            byte[] byt2 = Convert.FromBase64String(txtKey);
            mcsp.Key = byt2;
            byte[] byt3 = Convert.FromBase64String(txtIV);
            mcsp.IV = byt3;

            ct = mcsp.CreateDecryptor(mcsp.Key, mcsp.IV);

            byt = Convert.FromBase64String(value);

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();

            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray());
        }
コード例 #9
0
ファイル: FxCrypt.cs プロジェクト: tomochandv/Test
        private byte[] Decrypt(SymmetricAlgorithm sa, byte[] source)
        {
            System.Diagnostics.Trace.WriteLine(string.Format("DE:CSP:Key[{0}], IV[{1}]",
                Convert.ToBase64String(this.__cspExternal.Key), Convert.ToBase64String(this.__cspExternal.IV)));

            try
            {
                MemoryStream ms = new MemoryStream(source);
                CryptoStream cs = new CryptoStream(ms, sa.CreateDecryptor(), CryptoStreamMode.Read);
                BinaryReader br = new BinaryReader(cs);

                try
                {
                    return br.ReadBytes(source.Length);
                }
                catch (Exception)
                { }
                finally
                {
                    br.Close();
                    cs.Close();
                    ms.Close();
                }
            }
            catch (Exception)
            {
            }

            return null;
        }
コード例 #10
0
		private byte[] Decrypt (SymmetricAlgorithm algo, PaddingMode padding, byte[] data) 
		{
			algo.IV = new byte [algo.BlockSize >> 3];
			algo.Mode = CipherMode.CBC;
			algo.Padding = padding;
			ICryptoTransform ct = algo.CreateDecryptor ();
			return ct.TransformFinalBlock (data, 0, data.Length);
		}
コード例 #11
0
ファイル: CryptoHelper.cs プロジェクト: xpss/remote
        private static ICryptoTransform CreateCryptoTransform(SymmetricAlgorithm algorithm, CryptoAction action)
        {
            byte[] key = Encoding.ASCII.GetBytes(stringKey);
            byte[] vector = Encoding.ASCII.GetBytes(stringVector);

            return action == CryptoAction.Encrypt
                ? algorithm.CreateEncryptor(key, vector)
                : algorithm.CreateDecryptor(key, vector);
        }
コード例 #12
0
ファイル: Server.cs プロジェクト: feLenius/EPSAssignment
 /// <summary>
 /// Decrypts given text
 /// </summary>
 /// <param name="encryptedText">Text to decrypt</param>
 /// <param name="key">Key, used for decryption</param>
 /// <param name="iv">Initialization Vector</param>
 /// <param name="cryptoProvider">Cryptography algorithm</param>
 /// <returns>Decrypted text</returns>
 public static string Decrypt(string encryptedText, byte[] key, byte[] iv, SymmetricAlgorithm cryptoProvider)
 {
     //using (var cryptoProvider = Rijndael.Create())
     using (cryptoProvider)
     using (var memoryStream = new MemoryStream(Convert.FromBase64String(encryptedText)))
     using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
     using (var reader = new StreamReader(cryptoStream))
     {
         return reader.ReadToEnd();
     }
 }
コード例 #13
0
ファイル: Form1.cs プロジェクト: DashaSerdyuk/main
 public static string[][] Decrypt_and_deserialize(MemoryStream memoryStream, SymmetricAlgorithm des)
 {
     using (memoryStream)
     {
         using (var cs = new CryptoStream(memoryStream, des.CreateDecryptor(des.Key, des.IV), CryptoStreamMode.Read))
         {
             var xmlser = new XmlSerializer(typeof(string[][]));
             return (string[][])xmlser.Deserialize(cs);
         }
     }
 }
コード例 #14
0
ファイル: AESEncryption.cs プロジェクト: Chaek/MCSD
        public static string Decrypt(SymmetricAlgorithm aesAlg, byte[] cipherText)
        {
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    return srDecrypt.ReadToEnd();
            }
        }
コード例 #15
0
ファイル: CryptoHelper.cs プロジェクト: Geminior/DeepConfig
        internal static byte[] Decrypt(SymmetricAlgorithm crypter, byte[] encryptedData, byte[] cryptoKey, byte[] authKey, int clearTextPayloadLength = 0)
        {
            using (var hmac = new HMACSHA256(authKey))
            {
                //Ready the tag and iv array
                var dataTag = new byte[hmac.HashSize / 8];
                var iv = new byte[crypter.BlockSize / 8];

                //if message length is too small just return null
                if (encryptedData.Length < dataTag.Length + clearTextPayloadLength + iv.Length)
                {
                    return null;
                }

                //Get the sent tag and the expected tag
                Array.Copy(encryptedData, encryptedData.Length - dataTag.Length, dataTag, 0, dataTag.Length);

                var expectedTag = hmac.ComputeHash(encryptedData, 0, encryptedData.Length - dataTag.Length);

                //Compare Tags with constant time comparison
                var compare = 0;
                for (var i = 0; i < dataTag.Length; i++)
                {
                    compare |= dataTag[i] ^ expectedTag[i];
                }

                //if message doesn't authenticate return null
                if (compare != 0)
                {
                    return null;
                }

                //Get the IV from message
                Array.Copy(encryptedData, clearTextPayloadLength, iv, 0, iv.Length);

                using (var decrypter = crypter.CreateDecryptor(cryptoKey, iv))
                using (var plainTextStream = new MemoryStream())
                {
                    using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                    {
                        //Decrypt Cipher Text from Message
                        decrypterStream.Write(
                            encryptedData,
                            clearTextPayloadLength + iv.Length,
                            encryptedData.Length - clearTextPayloadLength - iv.Length - dataTag.Length);

                        decrypterStream.FlushFinalBlock();
                    }

                    //Return Plain Text
                    return plainTextStream.ToArray();
                }
            }
        }
コード例 #16
0
ファイル: Utility.cs プロジェクト: mashiro/tig-bind
 public static byte[] Decrypt(SymmetricAlgorithm algorithm, byte[] src)
 {
     using (MemoryStream ms = new MemoryStream())
     {
         using (CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
         {
             cs.Write(src, 0, src.Length);
             cs.FlushFinalBlock();
             return ms.ToArray();
         }
     }
 }
コード例 #17
0
ファイル: AES.cs プロジェクト: ChegnduJackli/Projects
        /// <summary>
        /// Constructor for AES class that takes byte arrays for the key and IV
        /// </summary>
        /// <param name="key">Cryptographic key</param>
        /// <param name="IV">Cryptographic initialization vector</param>
        public AES(byte[] key, byte[] IV)
        {
            // Initialize AESProvider with AES service provider
            AESProvider = new AesCryptoServiceProvider();

            // Set the key and IV for AESProvider
            AESProvider.Key = key;
            AESProvider.IV = IV;

            // Initialize cryptographic transformers from AESProvider
            encryptor = AESProvider.CreateEncryptor();
            decryptor = AESProvider.CreateDecryptor();
        }
コード例 #18
0
 private string Decrypt(SymmetricAlgorithm symmetricAlgorithm, byte[] encrypted)
 {
     ICryptoTransform decryptor = symmetricAlgorithm.CreateDecryptor(symmetricAlgorithm.Key, symmetricAlgorithm.IV);
     using (MemoryStream msDecrypt = new MemoryStream(encrypted))
     {
         using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
         {
             using (StreamReader swDecrypt = new StreamReader(csDecrypt))
             {
                 return swDecrypt.ReadToEnd();
             }
         }
     }
 }
コード例 #19
0
        public static string Decrypt(byte[] encryptText, SymmetricAlgorithm key)
        {
            MemoryStream ms = new MemoryStream(encryptText);
            CryptoStream cs = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(cs);

            string val = sr.ReadLine();
            sr.Close();
            cs.Close();
            ms.Close();

            return val;
        }
コード例 #20
0
		void TestEncryptDecrypt(SymmetricAlgorithm ealg, SymmetricAlgorithm dalg)
		{
			System.Diagnostics.Trace.WriteLine(String.Format("b={0}, k={1}, r={2}", ealg.BlockSize, ealg.KeySize, 
				ealg is ModifiedRijndael ? ((ModifiedRijndael)ealg).Rounds : ((ModifiedRijndael)dalg).Rounds));
			byte[] test = Encoding.ASCII.GetBytes("Testing 123");

			byte[] copy;
			using (ICryptoTransform enc = ealg.CreateEncryptor())
				copy = enc.TransformFinalBlock(test, 0, test.Length);

			using (ICryptoTransform dec = dalg.CreateDecryptor())
				copy = dec.TransformFinalBlock(copy, 0, copy.Length);

			Assert.AreEqual(0, BinaryComparer.Compare(test, copy));
		}
コード例 #21
0
ファイル: AES.cs プロジェクト: ChegnduJackli/Projects
        /// <summary>
        /// Constructor for AES class that generates the key and IV from salted passwords
        /// </summary>
        /// <param name="keyPassword">Password used to generate the key</param>
        /// <param name="IVPassword">Password used to generate the IV</param>
        /// <param name="salt">Salt used to secure the passwords</param>
        public AES(string keyPassword, string IVPassword, string salt)
        {
            // Initialize AESProvider with AES service provider
            AESProvider = new AesCryptoServiceProvider();

            // Initialize a hasher with the default MD5 algorithm
            MD5 md5 = System.Security.Cryptography.MD5.Create();

            // Generate the key and IV for AESProvider from hashed, salted passwords
            AESProvider.Key = md5.ComputeHash(UnicodeEncoding.Unicode.GetBytes(keyPassword + salt));
            AESProvider.IV = md5.ComputeHash(UnicodeEncoding.Unicode.GetBytes(IVPassword + salt));

            // Initialize cryptographic transformers from AESProvider
            encryptor = AESProvider.CreateEncryptor();
            decryptor = AESProvider.CreateDecryptor();
        }
コード例 #22
0
ファイル: Crypto.cs プロジェクト: Ricardoinf/MMAA
        private static string Decrypt(byte[] CypherText, SymmetricAlgorithm objCript)
        {
            MemoryStream ms = new MemoryStream(CypherText);

            CryptoStream encStream = new CryptoStream(ms, objCript.CreateDecryptor(), CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(encStream, Encoding.UTF8);

            string val = sr.ReadLine();

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

            return val;
        }
コード例 #23
0
        public static byte[] Decrypt(SymmetricAlgorithm algorithm,byte[] data)
        {
            using (MemoryStream memory = new MemoryStream(data))
            {
                using (CryptoStream decrypt = new CryptoStream(memory, algorithm.CreateDecryptor(algorithm.Key, algorithm.IV), CryptoStreamMode.Read))
                {
                    var result = new List<byte>();
                    var ibyte = decrypt.ReadByte();
                    while(ibyte > -1)
                    {
                        result.Add((byte)ibyte);
                        ibyte = decrypt.ReadByte();
                    }
                    return result.ToArray();
                }

            }
        }
コード例 #24
0
        public static string DecryptString(string EncryptText)
        {
            byte[]       encryptedTextBytes = Convert.FromBase64String(EncryptText);
            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            string key1 = "aaaaaaaaaaaaaaaa";
            string key2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

            byte[]       rgbIV = Encoding.ASCII.GetBytes(key1);
            byte[]       key   = Encoding.ASCII.GetBytes(key2);
            CryptoStream cs    = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);

            cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
            cs.Close();
            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
コード例 #25
0
ファイル: Crypt.cs プロジェクト: pschuegr/IronAHK
        static byte[] Encrypt(object value, object key, bool decrypt, SymmetricAlgorithm alg)
        {
            int size = 0;

            foreach (var legal in alg.LegalKeySizes)
                size = Math.Max(size, legal.MaxSize);

            var k = new byte[size / 8];

            var keyBytes = ToByteArray(key);

            if (keyBytes.Length < k.Length)
            {
                var padded = new byte[k.Length];
                keyBytes.CopyTo(padded, 0);
                keyBytes = padded;
            }

            for (int i = 0; i < k.Length; i++)
                k[i] = keyBytes[i];

            try
            {
                alg.Key = k;
            }
            catch (CryptographicException)
            {
                ErrorLevel = 2;
                return new byte[] { };
            }

            var iv = new byte[alg.IV.Length];
            var hash = new SHA1Managed().ComputeHash(keyBytes, 0, iv.Length);

            for (int i = 0; i < Math.Min(iv.Length, hash.Length); i++)
                iv[i] = hash[i];

            alg.IV = iv;

            var trans = decrypt ? alg.CreateDecryptor() : alg.CreateEncryptor();
            var buffer = ToByteArray(value);
            var result = trans.TransformFinalBlock(buffer, 0, buffer.Length);
            return result;
        }
コード例 #26
0
        public static string DecryptString(string EncryptedText)
        {
            byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

            MemoryStream ms = new MemoryStream();

            System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


            byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj");
            byte[] key   = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo");

            CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);

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

            return(Encoding.UTF8.GetString(ms.ToArray()));
        }
コード例 #27
0
        public static string Decrypt(byte[] encryptText, SymmetricAlgorithm key)
        {
            // Create a memory stream to the passed buffer.
            MemoryStream ms = new MemoryStream(encryptText);
            // Create a CryptoStream using  memory stream and CSP DES key.
            CryptoStream crypstream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);

            // Create a StreamReader for reading the stream.
            StreamReader sr = new StreamReader(crypstream);

            // Read the stream as a string.
            string val = sr.ReadLine();

            // Close the streams.
            sr.Close();
            crypstream.Close();
            ms.Close();

            return val;
        }
コード例 #28
0
        private static SymmetricAlgorithm mCSP; //声明对称算法变量

        #endregion Fields

        #region Methods

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Value">要解密的字符串</param>
        /// <returns>string</returns>
        public static string DecryptString(string Value)
        {
            mCSP = new DESCryptoServiceProvider();

            ICryptoTransform ct; //定义基本的加密转换运算
            MemoryStream ms; //定义内存流
            CryptoStream cs; //定义将数据流链接到加密转换的流
            byte[] byt;

            ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV)); //用指定的密钥和初始化向量创建对称数据解密标准
            byt = Convert.FromBase64String(Value); //将Value(Base 64)字符转换成字节数组

            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();

            return Encoding.UTF8.GetString(ms.ToArray()); //将字节数组中的所有字符解码为一个字符串
        }
コード例 #29
0
ファイル: EncryptProvider.cs プロジェクト: danni95/Core
        private byte[] EncryptDecrypt(bool encrypt,
            SymmetricAlgorithm alg, byte[] key, byte[] iv, byte[] data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] rgbKey = new PasswordDeriveBytes(key, _salt).GetBytes(24);
                byte[] rgbIV = new PasswordDeriveBytes(iv, _salt).GetBytes(24);
                using (CryptoStream cs = new CryptoStream(ms,
                    encrypt
                        ? alg.CreateEncryptor(rgbKey, rgbIV)
                        : alg.CreateDecryptor(rgbKey, rgbIV),
                    CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.Close();

                    return ms.ToArray();
                }
            }
        }
コード例 #30
0
ファイル: Encryption.cs プロジェクト: Brett1981/PopcornViewer
        private string Decrypt(string EncryptedText)
        {
            byte[] EncryptedBytes;
            try { EncryptedBytes = Convert.FromBase64String(EncryptedText.Substring(0, EncryptedText.IndexOf('$'))); }
            catch { return(""); }

            System.Security.Cryptography.SymmetricAlgorithm Alg = System.Security.Cryptography.SymmetricAlgorithm.Create();

            MemoryStream MemStr = new MemoryStream();

            byte[] KeyBytes   = Encoding.ASCII.GetBytes(KEY);
            byte[] KeyIIBytes = Encoding.ASCII.GetBytes(KEYII);

            CryptoStream CryptStr = new CryptoStream(MemStr, Alg.CreateDecryptor(KeyBytes, KeyIIBytes), CryptoStreamMode.Write);

            CryptStr.Write(EncryptedBytes, 0, EncryptedBytes.Length);
            CryptStr.Close();

            return(Encoding.UTF8.GetString(MemStr.ToArray()));
        }
コード例 #31
0
    public static string DecryptString(string EncryptedText)
    {
        string theKey = SystemInfo.deviceUniqueIdentifier;

        byte[]             salt = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };
        Rfc2898DeriveBytes pdb  = new Rfc2898DeriveBytes(theKey, salt);

        byte[] key = pdb.GetBytes(32);
        byte[] iv  = pdb.GetBytes(16);

        byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

        System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, iv), CryptoStreamMode.Write);

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

        return(Encoding.UTF8.GetString(ms.ToArray()));
    }
コード例 #32
0
		private string Roundtrip (SymmetricAlgorithm sa, CipherMode mode) 
		{
			sa.Key = GetKey (sa);
			sa.IV = GetIV (sa);
			sa.Mode = mode;

			// two full blocks
			int bs = (sa.BlockSize >> 3) * 2;
			byte[] data = new byte [bs]; // in bytes
			ICryptoTransform enc = sa.CreateEncryptor ();
			byte[] encdata = enc.TransformFinalBlock (data, 0, data.Length);
			string result = BitConverter.ToString (encdata);

			ICryptoTransform dec = sa.CreateDecryptor ();
			byte[] decdata = dec.TransformFinalBlock (encdata, 0, encdata.Length);

			for (int i = 0; i < bs; i++)
				Assert.AreEqual (data [i], decdata [i], i.ToString ());

			return result;
		}
コード例 #33
0
    /// <summary>
    /// Decrypts the specified cipher text.
    /// </summary>
    /// <param name="cipherText">The cipher text.</param>
    /// <returns>The decrypted value as a byte array.</returns>
    public byte[] Decrypt(byte[] cipherText)
    {
        if (cipherText is null)
        {
            throw new ArgumentNullException(nameof(cipherText));
        }

        if (!cipherText.IsEncrypted())
        {
            return(cipherText);
        }

        var decrypted = new List <byte>(cipherText.Length);

        using (var stream = new MemoryStream(cipherText))
        {
            var decryptor = _algorithm.CreateDecryptor(
                _credential.GetKey(), stream.ReadIVFromCipherTextHeader());

            using var cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
            const int bufferSize = 256;
            var       buffer     = new byte[bufferSize];

            while (true)
            {
                var readBytes = cryptoStream.Read(buffer, 0, buffer.Length);

                if (readBytes > 0)
                {
                    decrypted.AddRange(buffer.Take(readBytes));
                }
                else
                {
                    break;
                }
            }
        }

        return(decrypted.ToArray());
    }
コード例 #34
0
ファイル: Program.cs プロジェクト: AlinaKapustina/nsudotnet
        static void DecryptorType(SymmetricAlgorithm sa, string file_output, string key, string file_input)
        {
            byte[] key_byte;
            byte[] iv_byte;
            using (StreamReader key_file = new StreamReader(key))
            {
                String s = key_file.ReadLine();
                iv_byte = Convert.FromBase64String(s);
                s = key_file.ReadLine();
                key_byte = Convert.FromBase64String(s);
            }
            ICryptoTransform transform = sa.CreateDecryptor(key_byte, iv_byte);
            using (FileStream output = new FileStream(file_output, FileMode.Open, FileAccess.Read))
            {
                using (FileStream input = new FileStream(file_input, FileMode.Create, FileAccess.Write))
                {
                    using(CryptoStream stream = new CryptoStream(input, transform, CryptoStreamMode.Write))
                    output.CopyTo(stream);

                }
            }
        }
コード例 #35
0
ファイル: SpeedTest.cs プロジェクト: kazuki/opencrypto.net
		static double[] Run (SymmetricAlgorithm algo, byte[] key, byte[] iv, int totalBlocks)
		{
			double[] result = new double[] {0.0, 0.0};
			byte[] input = new byte[iv.Length * totalBlocks];
			byte[] output = new byte[iv.Length * totalBlocks];
			Stopwatch sw = new Stopwatch ();
			algo.KeySize = key.Length << 3;
			algo.BlockSize = iv.Length << 3;
			algo.FeedbackSize = iv.Length << 3;
			using (ICryptoTransform ct = algo.CreateEncryptor (key, iv)) {
				if (ct.CanTransformMultipleBlocks) {
					sw.Reset (); sw.Start ();
					ct.TransformBlock (input, 0, input.Length, output, 0);
					sw.Stop ();
				} else {
					sw.Reset (); sw.Start ();
					for (int i = 0, q = 0; i < totalBlocks; i ++, q += iv.Length) {
						ct.TransformBlock (input, q, iv.Length, output, q);
					}
					sw.Stop ();
				}
				result[0] = sw.Elapsed.TotalSeconds;
			}
			using (ICryptoTransform ct = algo.CreateDecryptor (key, iv)) {
				if (ct.CanTransformMultipleBlocks) {
					sw.Reset (); sw.Start ();
					ct.TransformBlock (input, 0, input.Length, output, 0);
					sw.Stop ();
				} else {
					sw.Reset (); sw.Start ();
					for (int i = 0, q = 0; i < totalBlocks; i++, q += iv.Length) {
						ct.TransformBlock (input, q, iv.Length, output, q);
					}
					sw.Stop ();
				}
				result[1] = sw.Elapsed.TotalSeconds;
			}
			return result;
		}
コード例 #36
0
 public override ICryptoTransform CreateDecryptor()
 {
     return(m_impl.CreateDecryptor());
 }
コード例 #37
0
ファイル: SecureHelper.cs プロジェクト: radtek/TaoLa
        public static string AESDecrypt(string decryptStr, string decryptKey)
        {
            string result;

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