示例#1
0
        internal static string DecryptBrokerResponse(string encryptedBrokerResponse, ICoreLogger logger)
        {
            byte[] outputBytes = Base64UrlHelpers.DecodeBytes(encryptedBrokerResponse);

            if (TryGetBrokerKey(out byte[] key))
            {
                AesManaged   algo         = null;
                CryptoStream cryptoStream = null;
                MemoryStream memoryStream = null;
                try
                {
                    memoryStream = new MemoryStream(outputBytes);
                    algo         = CreateSymmetricAlgorith(key);
                    cryptoStream = new CryptoStream(
                        memoryStream,
                        algo.CreateDecryptor(),
                        CryptoStreamMode.Read);
                    using (StreamReader srDecrypt = new StreamReader(cryptoStream))
                    {
                        string plaintext = srDecrypt.ReadToEnd();
                        return(plaintext);
                    }
                }
                finally
                {
                    memoryStream?.Dispose();
                    cryptoStream?.Dispose();
                    algo?.Dispose();
                }
            }

            throw new MsalClientException(
                      MsalError.BrokerKeyFetchFailed,
                      MsalErrorMessage.iOSBrokerKeyFetchFailed);
        }
示例#2
0
 private static byte[] Encrypt(byte[] bytesData)
 {
     byte[] result = new byte[0];
     using (MemoryStream memoryStream = new MemoryStream())
     {
         ICryptoTransform transform    = CreateAlgorithm().CreateEncryptor();
         CryptoStream     cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
         try
         {
             cryptoStream.Write(bytesData, 0, bytesData.Length);
             cryptoStream.FlushFinalBlock();
             cryptoStream.Close();
             result = memoryStream.ToArray();
         }
         catch (Exception ex)
         {
             throw new Exception("Error while writing decrypted data to the stream: \n" + ex.Message);
         }
         finally
         {
             cryptoStream?.Dispose();
         }
         memoryStream.Close();
     }
     return(result);
 }
示例#3
0
 protected override void Dispose(bool disposing)
 {
     TransformStream?.Dispose();
     BaseFileStream?.Dispose();
     TransformStream = null;
     BaseFileStream  = null;
 }
示例#4
0
    /// <summary>
    /// ถอดรหัสข้อมูล
    /// </summary>
    /// <param name="Value">ข้อมูลที่ต้องการให้ถอดรหัส</param>
    /// <returns>ข้อมูลหลังจากถอดรหัส</returns>
    /// <example>
    /// clsSecurity.Decrypt("e0NDKIlUhHF3qcIdkmGpZw==");
    /// </example>
    public string Decrypt(string Value)
    {
        #region Variable
        SymmetricAlgorithm mCSP;
        ICryptoTransform ct = null;
        MemoryStream ms = null;
        CryptoStream cs = null;
        byte[] byt;
        byte[] result;
        #endregion
        #region Procedure
        mCSP = new RijndaelManaged();

        try
        {
            mCSP.Key = _key;
            mCSP.IV = _initVector;
            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();
            result = ms.ToArray();
        }
        catch
        {
            result = null;
        }
        finally
        {
            if (ct != null)
                ct.Dispose();
            if (ms != null)
                if (ms.CanRead)
                {
                    ms.Dispose();
                }
            if (cs != null)
                if (cs.CanRead)
                {
                    cs.Dispose();
                }
        }
        try
        {
            return ASCIIEncoding.UTF8.GetString(result);
        }
        catch (Exception)
        {
            return "";
        }
        #endregion
    }
示例#5
0
        public static string DecryptString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return("");
            }

            //DESCryptoServiceProviderオブジェクトの作成
            using (var des = new System.Security.Cryptography.DESCryptoServiceProvider())
            {
                //共有キーと初期化ベクタを決定
                //パスワードをバイト配列にする
                var bytesKey = Encoding.UTF8.GetBytes("_tween_encrypt_key_");
                //共有キーと初期化ベクタを設定
                des.Key = ResizeBytesArray(bytesKey, des.Key.Length);
                des.IV  = ResizeBytesArray(bytesKey, des.IV.Length);

                //Base64で文字列をバイト配列に戻す
                var bytesIn = Convert.FromBase64String(str);

                MemoryStream     msIn        = null;
                ICryptoTransform desdecrypt  = null;
                CryptoStream     cryptStreem = null;

                try
                {
                    //暗号化されたデータを読み込むためのMemoryStream
                    msIn = new MemoryStream(bytesIn);
                    //DES復号化オブジェクトの作成
                    desdecrypt = des.CreateDecryptor();
                    //読み込むためのCryptoStreamの作成
                    cryptStreem = new CryptoStream(msIn, desdecrypt, CryptoStreamMode.Read);

                    //Disposeが重複して呼ばれないようにする
                    msIn       = null;
                    desdecrypt = null;

                    //復号化されたデータを取得するためのStreamReader
                    using (StreamReader srOut = new StreamReader(cryptStreem, Encoding.UTF8))
                    {
                        //Disposeが重複して呼ばれないようにする
                        cryptStreem = null;

                        //復号化されたデータを取得する
                        var result = srOut.ReadToEnd();

                        return(result);
                    }
                }
                finally
                {
                    msIn?.Dispose();
                    desdecrypt?.Dispose();
                    cryptStreem?.Dispose();
                }
            }
        }
示例#6
0
        /// <summary>
        /// Decrypt text by key with initialization vector
        /// </summary>
        /// <param name="value">Encrypted text</param>
        /// <param name="key">Key string</param>
        /// <param name="iv">Initialization vector</param>
        /// <returns>Plain text</returns>
        public static string Decrypt(string value, string key, string iv)
        {
            var decrptValue = string.Empty;

            if (string.IsNullOrEmpty(value))
            {
                return(decrptValue);
            }
            MemoryStream ms = null;
            CryptoStream cs = null;

            value = value.Replace(" ", "+");
            try
            {
                if (!string.IsNullOrEmpty(key))
                {
                    _keyByte = Encoding.UTF8.GetBytes
                                   (key.Substring(0, 8));
                    if (!string.IsNullOrEmpty(iv))
                    {
                        _ivByte = Encoding.UTF8.GetBytes
                                      (iv.Substring(0, 8));
                    }
                }
                else
                {
                    _keyByte = Encoding.UTF8.GetBytes(key);
                }
                using (var des = new DESCryptoServiceProvider())
                {
                    var inputByteArray = Convert.FromBase64String(value);
                    ms = new MemoryStream();
                    cs = new CryptoStream(ms, des.CreateDecryptor
                                              (_keyByte, _ivByte), CryptoStreamMode.Write);
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    var encoding = Encoding.UTF8;
                    decrptValue = encoding.GetString(ms.ToArray());
                }
            }
            catch
            {
                //TODO: write log
            }
            finally
            {
                cs?.Dispose();
                ms?.Dispose();
            }
            return(decrptValue);
        }
示例#7
0
        private string DecryptString(string value, string keyString)
        {
            var fullCipher = Convert.FromBase64String(value);

            var iv     = new byte[16];
            var cipher = new byte[fullCipher.Length - 16];

            Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
            Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);
            var key = Encoding.UTF8.GetBytes(keyString);

            using (var aes = Aes.Create())
            {
                aes.Padding = PaddingMode.Zeros;
                using (var decryptor = aes.CreateDecryptor(key, iv))
                {
                    string       result = string.Empty;
                    CryptoStream dcs    = null;
                    using (var dms = new MemoryStream(cipher))
                    {
                        try
                        {
                            dcs = new CryptoStream(dms, decryptor, CryptoStreamMode.Read);
                            using (var dsr = new StreamReader(dcs))
                            {
                                try
                                {
                                    result = dsr.ReadToEnd();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                    throw;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            dcs?.Dispose();
                        }
                    }
                    // Remove the padding from the decrypted string
                    result = result.Split('\0')[0];
                    return(result);
                }
            }
        }
示例#8
0
            protected override void Dispose(bool isDisposing)
            {
                base.Dispose(isDisposing);
                if (!disposed)
                {
                    if (isDisposing)
                    {
                        innerStream?.Dispose();
                        cryptStream?.Dispose();
                    }

                    innerStream = null;
                    cryptStream = null;

                    disposed = true;
                }
            }
示例#9
0
        private string EncryptString(string value, string keyString)
        {
            var key = Encoding.UTF8.GetBytes(keyString);

            string encryptedValue;

            using (var aes = Aes.Create())
            {
                aes.Padding = PaddingMode.Zeros;
                using (var encryptor = aes.CreateEncryptor(key, aes.IV))
                {
                    CryptoStream ecs = null;

                    using (var ems = new MemoryStream())
                    {
                        byte[] decryptedContent = { };
                        try
                        {
                            ecs = new CryptoStream(ems, encryptor, CryptoStreamMode.Write);
                            using (var esw = new StreamWriter(ecs))
                            {
                                esw.Write(value);
                                esw.Flush();
                                ecs.FlushFinalBlock();
                                decryptedContent = ems.ToArray();
                            }
                        }
                        catch (Exception e)
                        {
                            ecs?.Dispose();
                        }

                        var iv = aes.IV;

                        var result = new byte[iv.Length + decryptedContent.Length];

                        Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                        Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

                        encryptedValue = Convert.ToBase64String(result);
                    }
                }
            }

            return(encryptedValue);
        }
示例#10
0
        /// <summary>
        /// Decrypts the given data using the given mode and padding.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="mode"></param>
        /// <param name="padding"></param>
        /// <returns></returns>
        public byte[] Decrypt(byte[] data, CipherMode mode, PaddingMode padding)
        {
            ICryptoTransform decryptor = null;
            MemoryStream     mStream   = null;
            CryptoStream     cStream   = null;

            try
            {
                // Update the mode and padding for the decryption..
                this.m_AesCryptoProvider.Mode    = mode;
                this.m_AesCryptoProvider.Padding = padding;

                // Create the decryptor..
                decryptor = this.m_AesCryptoProvider.CreateDecryptor(this.m_OriginalKey, this.m_OriginalIv);

                // Create a memory stream for our data..
                mStream = new MemoryStream(data);

                // Create the crypto stream..
                cStream = new CryptoStream(mStream, decryptor, CryptoStreamMode.Read);

                // Decrypt the data..
                var totalBuffer = new List <byte>();
                var buffer      = new byte[2048];
                while ((cStream.Read(buffer, 0, 2048)) > 0)
                {
                    totalBuffer.AddRange(buffer);
                }

                return(totalBuffer.ToArray());
            }
            catch
            {
                return(null);
            }
            finally
            {
                cStream?.Dispose();
                mStream?.Dispose();
                decryptor?.Dispose();
            }
        }
示例#11
0
        /// <summary>
        /// Decrypts requested encoded byte array to plain text based on Rijndael algorithm
        /// <see cref="ICryptoService.Decrypt(byte[])"/>
        /// </summary>
        public string Decrypt(byte[] encodedBytes, string secretKey, string iv, string salt)
        {
            // Check arguments.
            if (encodedBytes == null || encodedBytes.Length <= 0)
            {
                throw new ArgumentNullException("encodedBytes");
            }
            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentNullException("secretKey");
            }

            // Declare the string used to hold the decrypted text.
            string plaintext = null;

            using var aesAlgCipher = CreateCipher(secretKey, iv, salt);

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

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(encodedBytes))
            {
                CryptoStream csDecrypt = null;
                try
                {
                    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.
                        csDecrypt = null;
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
                finally
                {
                    csDecrypt?.Dispose();
                }
            }

            return(plaintext);
        }
示例#12
0
        /// <summary>
        /// IDisposable 패턴을 구현합니다.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    memory1?.Dispose();
                    memory2?.Dispose();
                    memory3?.Dispose();

                    Encryptor?.Dispose();
                    Decryptor?.Dispose();

                    encrypt?.Dispose();
                    decrypt?.Dispose();
                }
                Key           = null;
                disposedValue = true;
            }
        }
示例#13
0
        public static void MultipleDispose()
        {
            ICryptoTransform encryptor = new IdentityTransform(1, 1, true);

            using (MemoryStream output = new MemoryStream())
            {
                using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
                {
                    encryptStream.Dispose();
                }

                Assert.Equal(false, output.CanRead);
            }

            #if netcoreapp11
            using (MemoryStream output = new MemoryStream())
            {
                using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: false))
                {
                    encryptStream.Dispose();
                }

                Assert.Equal(false, output.CanRead);
            }

            using (MemoryStream output = new MemoryStream())
            {
                using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: true))
                {
                    encryptStream.Dispose();
                }

                Assert.Equal(true, output.CanRead);
            }
            #endif
        }
示例#14
0
 public static void MultipleDispose()
 {
     ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
     using (MemoryStream output = new MemoryStream())
     using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
     {
         encryptStream.Dispose();
     }
 }
示例#15
0
 public virtual void Dispose()
 {
     Stream?.Dispose();
     _baseStream?.Dispose();
     _algorithm?.Dispose();
 }
示例#16
0
            /// <summary>
            /// The Save() function will only write out the license file if ContentsChanged is true.
            /// </summary>



            /*
             * public static string DecryptTextFromFile( String FileName ) {
             *  //try
             *  //{
             *  FileStream fStream = File.OpenRead(FileName);
             *  return EncryptedFile.DecryptFromStream(fStream);
             *  //}
             *  //catch (UnauthorizedAccessException e)
             *  //{
             *  //    Error = true;
             *  //    ErrorException = e;
             *  //    ErrorMessage = "Unable to open file: UnauthorizedAccessException.";
             *  //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
             *  //    return null;
             *  //}
             * }
             */
            /*
             * public static string EncryptTextFileToFile(string source, string destination ) {
             *  //try
             *  //{
             *  FileStream fStream = File.OpenRead(source);
             *  return EncryptedFile.DecryptFromStream(fStream);
             *  //}
             *  //catch (UnauthorizedAccessException e)
             *  //{
             *  //    Error = true;
             *  //    ErrorException = e;
             *  //    ErrorMessage = "Unable to open file: UnauthorizedAccessException.";
             *  //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
             *  //    return null;
             *  //}
             * }
             */
            public static void DecryptFromFileToFile(string source, string destination)
            {
                CryptoStream cStream   = null;
                StreamReader sReader   = null;
                FileStream   strm      = null;
                Stream       outStream = null;

                //string rc = "";
                try {
                    strm      = File.Open(source, FileMode.Open);
                    outStream = File.Open(destination, FileMode.OpenOrCreate);

                    UnicodeEncoding u   = new UnicodeEncoding();
                    byte[]          Key = u.GetBytes(key);
                    byte[]          IV  = u.GetBytes(vector);

                    // Create a CryptoStream using the FileStream
                    // and the passed key and initialization vector (IV).

                    cStream = new CryptoStream(strm,
                                               new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
                                               CryptoStreamMode.Read);

                    // Create a StreamReader using the CryptoStream.
                    sReader = new StreamReader(cStream);


                    char[] buffer = new char[0xFFFF];
                    while (true)
                    {
                        int result = sReader.Read(buffer, 0, buffer.Length);
                        if (result == 0)
                        {
                            break;
                        }

                        for (int x = 0; x < result; x++)
                        {
                            outStream.WriteByte(Convert.ToByte(buffer[x]));
                        }

                        if (result < 0xFFFF)
                        {
                            break;
                        }
                    }
                }
                finally {
                    try { outStream.Flush(); outStream.Close(); outStream.Dispose(); }
                    catch { }
                    try { sReader.Close(); sReader.Dispose(); }
                    catch { }
                    try { cStream.Close(); cStream.Dispose(); }
                    catch { }
                    try { strm.Close(); strm.Dispose(); }
                    catch { }
                }
                //return rc;
                //catch (CryptographicException e)
                //{
                //    try { sReader.Close(); }
                //    catch { }
                //    try { cStream.Close(); }
                //    catch { }
                //    try { strm.Close(); }
                //    catch { }
                //    Error = true;
                //    ErrorException = e;
                //    ErrorMessage = "Unable to open file: CryptographicException.";
                //    //Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                //    return "";
                //}
                //catch (UnauthorizedAccessException e)
                //{
                //    try { sReader.Close(); }
                //    catch { }
                //    try { cStream.Close(); }
                //    catch { }
                //    try { strm.Close(); }
                //    catch { }
                //    Error = true;
                //    ErrorException = e;
                //    ErrorMessage = "Unable to open file: UnauthorizedAccessException.";
                //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
                //    return "";
                //}
            }
示例#17
0
        static public bool RC2_CBC_Symmetry_Decode_Byte(byte[] decryptByte, uint startPos, uint inLen, ref byte[] outBytes, byte[] rgbKey)
        {
            try
            {
                RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                m_cstream.Write(decryptByte, (int)startPos, (int)inLen);
                m_cstream.FlushFinalBlock();
                outBytes = m_stream.ToArray();

                m_stream.Close(); 
                m_stream.Dispose();

                m_cstream.Close(); 
                m_cstream.Dispose();

                return true;
            }
            catch
            {
                return false;
            }
        }
            /// <summary>
            /// Encrypts specified plaintext using Rijndael symmetric key algorithm
            /// and returns a base64-encoded result.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be encrypted.
            /// </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>
            /// Encrypted value formatted as a base64-encoded string.
            /// </returns>
            protected static string Encrypt(
                string plainText,
                string passPhrase,
                string saltValue,
                string hashAlgorithm,
                int passwordIterations,
                string initVector,
                int keySize)
            {
                // Convert strings into 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 plaintext into a byte array.
                // Let us assume that plaintext contains UTF8-encoded characters.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                // 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.
                PasswordDeriveBytes password = new 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.
                RijndaelManaged symmetricKey = new RijndaelManaged();

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

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

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

                // Define cryptographic stream (always use Write mode for encryption).
                CryptoStream cryptoStream = new CryptoStream(
                    memoryStream,
                    encryptor,
                    CryptoStreamMode.Write);

                // Start encrypting.
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

                // Finish encrypting.
                cryptoStream.FlushFinalBlock();

                // Convert our encrypted data from a memory stream into a byte array.
                byte[] cipherTextBytes = memoryStream.ToArray();

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

                // Convert encrypted data into a base64-encoded string.
                string cipherText = Convert.ToBase64String(cipherTextBytes);

                // Return encrypted string.
                return(cipherText);
            }
示例#19
0
        private static bool Decrypt(string sourceFile, string targetFile, string keyBase64, string ivBase64)
        {
            var        result           = false;
            FileStream fileStreamTarget = null;
            Aes        aes = null;

            try
            {
                aes = Aes.Create();
                byte[] buffer = new byte[2097152];

                fileStreamTarget = File.Open(targetFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

                ICryptoTransform transform        = null;
                FileStream       fileStreamSource = null;
                CryptoStream     cryptoStream     = null;
                try
                {
                    LogUtil.Write("Processing ");

                    var key = Convert.FromBase64String(keyBase64);
                    var iv  = Convert.FromBase64String(ivBase64);

                    transform = aes?.CreateDecryptor(key, iv);

                    fileStreamSource = File.Open(sourceFile, FileMode.Open, FileAccess.Read, FileShare.None);
                    //skip first 48 bytes... some IV stuff there which is not necessary for the archive
                    _ = fileStreamSource.Seek(48L, SeekOrigin.Begin);

                    cryptoStream = new CryptoStream(fileStreamTarget, transform, CryptoStreamMode.Write);

                    int count, tracker = 0;
                    while ((count = fileStreamSource.Read(buffer, 0, 2097152)) > 0)
                    {
                        cryptoStream.Write(buffer, 0, count);
                        cryptoStream.Flush();
                        tracker++;
                        if (tracker < 0)
                        {
                            LogUtil.Write(".");
                        }
                        else if (tracker % 10 == 0)
                        {
                            LogUtil.Write(".");
                        }
                    }

                    cryptoStream.FlushFinalBlock();
                    LogUtil.WriteLine(" done!");
                    result = true;
                }
                catch (Exception e)
                {
                    LogUtil.WriteLine(e.Message);
                }
                finally
                {
                    cryptoStream?.Dispose();
                    fileStreamSource?.Dispose();
                    transform?.Dispose();
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteLine(e.Message);
            }
            finally
            {
                fileStreamTarget?.Dispose();
                aes?.Dispose();
            }

            return(result);
        }
示例#20
0
文件: NUSD.cs 项目: nastys/Uwizard
            private void encryptTitleKey()
            {
                commonKeyIndex = newKeyIndex;
                byte[] ckey = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                byte[] iv = BitConverter.GetBytes(Shared.Swap(titleId));
                Array.Resize(ref iv, 16);

                RijndaelManaged rm = new RijndaelManaged();
                rm.Mode = CipherMode.CBC;
                rm.Padding = PaddingMode.None;
                rm.KeySize = 128;
                rm.BlockSize = 128;
                rm.Key = ckey;
                rm.IV = iv;

                ICryptoTransform encryptor = rm.CreateEncryptor();

                MemoryStream ms = new MemoryStream(decryptedTitleKey);
                CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Read);

                cs.Read(encryptedTitleKey, 0, encryptedTitleKey.Length);

                cs.Dispose();
                ms.Dispose();
                encryptor.Dispose();
                rm.Clear();
            }
示例#21
0
        // This is the only method about exchange data between this software and AirVPN infrastructure.
        // We don't use SSL. Useless layer in our case, and we need to fetch hostname and direct IP that don't permit common-name match.

        // 'S' is the AES 256 bit one-time session key, crypted with a RSA 4096 public-key.
        // 'D' is the data from the client to our server, crypted with the AES.
        // The server answer is XML decrypted with the same AES session.
        public static XmlDocument FetchUrl(string authPublicKey, string url, Dictionary <string, string> parameters)
        {
            // AES
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();

                // Generate S

                // Bug workaround: Xamarin 6.1.2 macOS throw an 'Default constructor not found for type System.Diagnostics.FilterElement' error.
                // in 'new System.Xml.Serialization.XmlSerializer', so i avoid that.

                /*
                 * StringReader sr = new System.IO.StringReader(authPublicKey);
                 * System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                 * RSAParameters publicKey = (RSAParameters)xs.Deserialize(sr);
                 */
                RSAParameters publicKey        = new RSAParameters();
                XmlDocument   docAuthPublicKey = new XmlDocument();
                docAuthPublicKey.LoadXml(authPublicKey);
                publicKey.Modulus  = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Modulus"].InnerText);
                publicKey.Exponent = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Exponent"].InnerText);

                Dictionary <string, byte[]> assocParamS = new Dictionary <string, byte[]>();
                assocParamS["key"] = rijAlg.Key;
                assocParamS["iv"]  = rijAlg.IV;

                byte[] bytesParamS = null;
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.ImportParameters(publicKey);
                    bytesParamS = csp.Encrypt(UtilsCore.AssocToUtf8Bytes(assocParamS), false);
                }

                // Generate D

                byte[] aesDataIn   = UtilsCore.AssocToUtf8Bytes(parameters);
                byte[] bytesParamD = null;

                {
                    MemoryStream aesCryptStream  = null;
                    CryptoStream aesCryptStream2 = null;

                    try
                    {
                        aesCryptStream = new MemoryStream();
                        using (ICryptoTransform aesEncryptor = rijAlg.CreateEncryptor())
                        {
                            aesCryptStream2 = new CryptoStream(aesCryptStream, aesEncryptor, CryptoStreamMode.Write);
                            aesCryptStream2.Write(aesDataIn, 0, aesDataIn.Length);
                            aesCryptStream2.FlushFinalBlock();

                            bytesParamD = aesCryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesCryptStream2 != null)
                        {
                            aesCryptStream2.Dispose();
                        }
                        else if (aesCryptStream != null)
                        {
                            aesCryptStream.Dispose();
                        }
                    }
                }

                // HTTP Fetch
                HttpRequest request = new HttpRequest();
                request.Url             = url;
                request.Parameters["s"] = UtilsString.Base64Encode(bytesParamS);
                request.Parameters["d"] = UtilsString.Base64Encode(bytesParamD);

                HttpResponse response = Engine.Instance.FetchUrl(request);

                try
                {
                    byte[] fetchResponse      = response.BufferData;
                    byte[] fetchResponsePlain = null;

                    MemoryStream aesDecryptStream  = null;
                    CryptoStream aesDecryptStream2 = null;

                    // Decrypt answer

                    try
                    {
                        aesDecryptStream = new MemoryStream();
                        using (ICryptoTransform aesDecryptor = rijAlg.CreateDecryptor())
                        {
                            aesDecryptStream2 = new CryptoStream(aesDecryptStream, aesDecryptor, CryptoStreamMode.Write);
                            aesDecryptStream2.Write(fetchResponse, 0, fetchResponse.Length);
                            aesDecryptStream2.FlushFinalBlock();

                            fetchResponsePlain = aesDecryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesDecryptStream2 != null)
                        {
                            aesDecryptStream2.Dispose();
                        }
                        else if (aesDecryptStream != null)
                        {
                            aesDecryptStream.Dispose();
                        }
                    }

                    string finalData = System.Text.Encoding.UTF8.GetString(fetchResponsePlain);

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(finalData);
                    return(doc);
                }
                catch (Exception ex)
                {
                    string message = "";
                    if (response.GetHeader("location") != "")
                    {
                        message = MessagesFormatter.Format(Messages.ManifestFailedUnexpected302, response.GetHeader("location"));
                    }
                    else
                    {
                        message = ex.Message + " - " + response.GetLineReport();
                    }
                    throw new Exception(message);
                }
            }
        }
示例#22
0
        protected override void DoTaskForFile(string pPath,
                                              IVgmtWorkerStruct pExamineChecksumGeneratorStruct, DoWorkEventArgs e)
        {
            ExamineChecksumGeneratorStruct examineChecksumGeneratorStruct =
                (ExamineChecksumGeneratorStruct)pExamineChecksumGeneratorStruct;

            string crc32;
            string md5;
            string sha1;

            string vgmtCrc32 = "Not implemented for this format.";
            string vgmtMd5   = "Not implemented for this format.";
            string vgmtSha1  = "Not implemented for this format.";

            string checksumKey;

            Type    formatType = null;
            IFormat vgmData    = null;

            using (FileStream fs = File.OpenRead(pPath))
            {
                crc32 = ChecksumUtil.GetCrc32OfFullFile(fs);
                md5   = ChecksumUtil.GetMd5OfFullFile(fs);
                sha1  = ChecksumUtil.GetSha1OfFullFile(fs);

                if (examineChecksumGeneratorStruct.CheckForDuplicates)
                {
                    checksumKey = String.Format("{0}/{1}/{2}", crc32, md5, sha1);
                    this.addChecksumToHash(checksumKey, pPath, true);
                }

                if (examineChecksumGeneratorStruct.DoVgmtChecksums)
                {
                    formatType = FormatUtil.getObjectType(fs);
                    if (formatType != null)
                    {
                        vgmData = (IFormat)Activator.CreateInstance(formatType);
                        vgmData.Initialize(fs, pPath);
                    }
                }
            }

            if (vgmData != null)
            {
                Crc32 crc32Generator = new Crc32();

                MD5CryptoServiceProvider md5Hash = new MD5CryptoServiceProvider();
                FileStream   md5FileStream       = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.Write);
                CryptoStream md5CryptoStream     = new CryptoStream(md5FileStream, md5Hash, CryptoStreamMode.Write);

                SHA1CryptoServiceProvider sha1Hash = new SHA1CryptoServiceProvider();
                FileStream   sha1FileStream        = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.Write);
                CryptoStream sha1CryptoStream      = new CryptoStream(sha1FileStream, sha1Hash, CryptoStreamMode.Write);

                vgmData.GetDatFileChecksums(ref crc32Generator, ref md5CryptoStream,
                                            ref sha1CryptoStream);
                md5CryptoStream.FlushFinalBlock();
                sha1CryptoStream.FlushFinalBlock();

                vgmtCrc32 = crc32Generator.Value.ToString("X8");
                vgmtMd5   = ParseFile.ByteArrayToString(md5Hash.Hash);
                vgmtSha1  = ParseFile.ByteArrayToString(sha1Hash.Hash);

                if (examineChecksumGeneratorStruct.CheckForDuplicates)
                {
                    checksumKey = String.Format("{0}/{1}/{2}", vgmtCrc32, vgmtMd5, vgmtSha1);
                    this.addChecksumToHash(checksumKey, pPath, false);
                }

                md5FileStream.Close();
                md5FileStream.Dispose();
                sha1FileStream.Close();
                sha1FileStream.Dispose();

                md5CryptoStream.Close();
                md5CryptoStream.Dispose();
                sha1CryptoStream.Close();
                sha1CryptoStream.Dispose();
            }

            this.outputBuffer.AppendFormat("<{0}>{1}", pPath, Environment.NewLine);
            this.outputBuffer.AppendFormat("CRC32: {0}{1}", crc32, Environment.NewLine);
            this.outputBuffer.AppendFormat("MD5: {0}{1}", md5, Environment.NewLine);
            this.outputBuffer.AppendFormat("SHA1: {0}{1}", sha1, Environment.NewLine);

            if (examineChecksumGeneratorStruct.DoVgmtChecksums)
            {
                this.outputBuffer.AppendFormat("CRC32 (VGMT): {0}{1}", vgmtCrc32, Environment.NewLine);
                this.outputBuffer.AppendFormat("MD5 (VGMT): {0}{1}", vgmtMd5, Environment.NewLine);
                this.outputBuffer.AppendFormat("SHA1 (VGMT): {0}{1}", vgmtSha1, Environment.NewLine);
            }
            this.outputBuffer.AppendLine();
        }
示例#23
0
            /*
             * protected void WriteLicenseFile( DataSet ds ) {
             *  if(EncryptFile) {
             *      TextWriter stringWriter = new StringWriter();
             *      ds.WriteXml(stringWriter, XmlWriteMode.WriteSchema);
             *      EncryptTextToFile(stringWriter.ToString(), FilePath);
             *      stringWriter.Close();
             *  }
             *  else
             *      ds.WriteXml(FilePath, XmlWriteMode.WriteSchema);
             * }
             *
             * /// <summary>
             * /// This assumes the file contents is text and needs to be encrypted.
             * /// The original contents still needs to be a valid xml that can be loaded into a DataSet.
             * /// </summary>
             * public void EncryptFileContents() {
             *  DataSet ds = new DataSet("ImsLicense");
             *  //try
             *  //{
             *  ds.ReadXml(FilePath, XmlReadMode.ReadSchema);
             *  TextWriter stringWriter = new StringWriter();
             *  ds.WriteXml(stringWriter, XmlWriteMode.WriteSchema);
             *  EncryptTextToFile(stringWriter.ToString(), FilePath);
             *  stringWriter.Close();
             *  //}
             *  //catch (Exception ex)
             *  //{
             *  //    Error = true;
             *  //    ErrorException = ex;
             *  //    ErrorMessage = "Problem reading xml from file.";
             *  //}
             * }
             */
            //public void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)

            /*
             * public static void EncryptTextToFile( String Data, String FileName ) {
             *  //try
             *  //{
             *  FileStream fStream = File.Open(FileName, FileMode.Create);
             *  EncryptedFile.EncryptToStream(Data, (Stream)fStream);
             *  //}
             *  //catch (UnauthorizedAccessException e)
             *  //{
             *  //    Error = true;
             *  //    ErrorException = e;
             *  //    ErrorMessage = "Unable to open file: UnauthorizedAccessException.";
             *  //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
             *  //    return;
             *  //}
             *
             * }
             */
            /*
             * public static void EncryptBinaryToFile( String Data, String FileName ) {
             *  //try
             *  //{
             *  FileStream fStream = File.Open(FileName, FileMode.Create);
             *  EncryptedFile.EncryptToStream(Data, (Stream)fStream);
             *  //}
             *  //catch (UnauthorizedAccessException e)
             *  //{
             *  //    Error = true;
             *  //    ErrorException = e;
             *  //    ErrorMessage = "Unable to open file: UnauthorizedAccessException.";
             *  //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
             *  //    return;
             *  //}
             *
             * }
             */
            public static void EncryptFileToFile(string source, string destination)
            {
                StreamWriter sWriter = null;
                CryptoStream cStream = null;
                Stream       fStream = null;
                FileStream   iStream = null;

                try {
                    fStream = File.Open(destination, FileMode.Create);
                    iStream = File.Open(source, FileMode.Open);


                    UnicodeEncoding u   = new UnicodeEncoding();
                    byte[]          Key = u.GetBytes(key);
                    byte[]          IV  = u.GetBytes(vector);

                    cStream = new CryptoStream(fStream,
                                               new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                                               CryptoStreamMode.Write);

                    // Create a StreamWriter using the CryptoStream.
                    sWriter = new StreamWriter(cStream);



                    var buffer = new byte[0xFFFF];
                    while (true)
                    {
                        var result = iStream.Read(buffer, 0, 0xFFFF);
                        if (result == 0)
                        {
                            break;
                        }

                        for (int x = 0; x < result; x++)
                        {
                            sWriter.Write(Convert.ToChar(buffer[x]));
                        }

                        if (result < 0xFFFF)
                        {
                            break;
                        }
                    }
                }
                finally {
                    try { fStream.Flush(); fStream.Close(); fStream.Dispose(); }
                    catch { }
                    try { cStream.Close(); cStream.Dispose(); }
                    catch { }
                    try { iStream.Close(); iStream.Dispose(); }
                    catch { }
                }
                //catch (CryptographicException e)
                //{
                //    try { sWriter.Close(); }
                //    catch { }
                //    try { cStream.Close(); }
                //    catch { }
                //    try { strm.Close(); }
                //    catch { }
                //    Error = true;
                //    ErrorException = e;
                //    ErrorMessage = "Unable to write file: CryptographicException.";
                //    //Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
                //    return;
                //}
                //catch (UnauthorizedAccessException e)
                //{
                //    try { sWriter.Close(); }
                //    catch { }
                //    try { cStream.Close(); }
                //    catch { }
                //    try { strm.Close(); }
                //    catch { }
                //    Error = true;
                //    ErrorException = e;
                //    ErrorMessage = "Unable to write file: UnauthorizedAccessException.";
                //    //Console.WriteLine("A file access error occurred: {0}", e.Message);
                //    return;
                //}
            }
示例#24
0
文件: NUSD.cs 项目: nastys/Uwizard
            private byte[] decryptContent(byte[] content, int contentIndex, Ticket tik, TMD tmd)
            {
                Array.Resize(ref content, Shared.AddPadding(content.Length, 16));
                byte[] titleKey = tik.TitleKey;
                byte[] iv = new byte[16];

                byte[] tmp = BitConverter.GetBytes(tmd.Contents[contentIndex].Index);
                iv[0] = tmp[1];
                iv[1] = tmp[0];

                RijndaelManaged rm = new RijndaelManaged();
                rm.Mode = CipherMode.CBC;
                rm.Padding = PaddingMode.None;
                rm.KeySize = 128;
                rm.BlockSize = 128;
                rm.Key = titleKey;
                rm.IV = iv;

                ICryptoTransform decryptor = rm.CreateDecryptor();

                MemoryStream ms = new MemoryStream(content);
                CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

                byte[] decCont = new byte[content.Length];
                cs.Read(decCont, 0, decCont.Length);

                cs.Dispose();
                ms.Dispose();

                return decCont;
            }
示例#25
0
        private void UnpackTrinity(ModuleDefMD module)
        {
            bool can = false;

            if (module.EntryPoint.Body.Instructions[44].Operand.ToString().Contains("Assembly::Load"))
            {
                can = true;
            }


            if (can)
            {
                try
                {
                    string    ivKey = "";
                    MethodDef epp   = module.EntryPoint;
                    for (int i = 0; i < module.EntryPoint.Body.Instructions.Count; i++)
                    {
                        if (module.EntryPoint.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                        {
                            if (module.EntryPoint.Body.Instructions[i].Operand.ToString().Length == 24)
                            {
                                ivKey = module.EntryPoint.Body.Instructions[i].Operand.ToString();
                            }
                        }
                    }
                    string key = "";
                    for (int i = 0; i < module.EntryPoint.Body.Instructions.Count; i++)
                    {
                        if (module.EntryPoint.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                        {
                            if (module.EntryPoint.Body.Instructions[i].Operand.ToString().Length == 44)
                            {
                                key = module.EntryPoint.Body.Instructions[i].Operand.ToString();
                            }
                        }
                    }
                    string arrayKey = "";
                    for (int i = 0; i < module.EntryPoint.Body.Instructions.Count; i++)
                    {
                        if (module.EntryPoint.Body.Instructions[i].OpCode == OpCodes.Ldstr)
                        {
                            if (module.EntryPoint.Body.Instructions[i].Operand.ToString().Length > 200)
                            {
                                arrayKey = module.EntryPoint.Body.Instructions[i].Operand.ToString();
                            }
                        }
                    }
                    RijndaelManaged rijndaelManaged = new RijndaelManaged();
                    rijndaelManaged.KeySize = 256;
                    rijndaelManaged.Key     = Convert.FromBase64String(key);
                    rijndaelManaged.IV      = Convert.FromBase64String(ivKey);
                    rijndaelManaged.Padding = PaddingMode.ISO10126;
                    MemoryStream memoryStream = new MemoryStream();
                    CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), CryptoStreamMode.Write);
                    byte[]       array        = Convert.FromBase64String(arrayKey);
                    cryptoStream.Write(array, 0, array.Length);
                    cryptoStream.Flush();
                    memoryStream.Seek(0L, SeekOrigin.Begin);
                    Protections.Base.ModuleDef = ModuleDefMD.Load(memoryStream.ToArray());
                    cryptoStream.Close();
                    memoryStream.Close();
                    cryptoStream.Dispose();
                    memoryStream.Dispose();
                    Base.CompressorRemoved = true;
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                    Console.Read();
                }
            }
        }
示例#26
0
        private static byte[] WriteMemoryStreamBytes(string plainText, ref byte[] saltBytes, ICryptoTransform encryptor, ref MemoryStream memoryStream, ref CryptoStream cryptoStream)
        {
            try
            {
                memoryStream = new MemoryStream();

                try
                {
                    cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

                    using (var streamWriter = new StreamWriter(cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }
                }
                finally
                {
                    if (cryptoStream != null)
                    {
                        cryptoStream.Dispose();
                    }
                }

                var cipherTextBytes = memoryStream.ToArray();
                Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length);

                return saltBytes;
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
            }
        }
    public static string Decrypt(string dataToDecrypt, string key)
    {
        AesManaged aes = null;
        MemoryStream memoryStream = null;

        try
        {
            //Create AES algorithm
            aes = new AesManaged();
            //Key derived from byte array with 32 pseudo-random key bytes
            aes.Key = Encoding.UTF8.GetBytes(key);
            //IV derived from byte array with 16 pseudo-random key bytes
            aes.IV = new byte[16];

            //Create Memory and Crypto Streams
            memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write);

            //Decrypt Data
            byte[] data = Convert.FromBase64String(dataToDecrypt);
            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();

            //Return Decrypted String
            byte[] decryptBytes = memoryStream.ToArray();

            //Dispose
            if (cryptoStream != null)
                cryptoStream.Dispose();

            //Retval
            return Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
        }
        finally
        {
            if (memoryStream != null)
                memoryStream.Dispose();

            if (aes != null)
                aes.Clear();
        }
    }