Esempio n. 1
1
    static byte[] Decrypt(byte[] asm)
    {
        byte[] dat;
        byte[] iv;
        byte[] key;
        using (BinaryReader rdr = new BinaryReader(new MemoryStream(asm)))
        {
            dat = rdr.ReadBytes(rdr.ReadInt32());
            iv = rdr.ReadBytes(rdr.ReadInt32());
            key = rdr.ReadBytes(rdr.ReadInt32());
        }
        int key0 = Mutation.Key0I;
        for (int j = 0; j < key.Length; j += 4)
        {
            key[j + 0] ^= (byte)((key0 & 0x000000ff) >> 0);
            key[j + 1] ^= (byte)((key0 & 0x0000ff00) >> 8);
            key[j + 2] ^= (byte)((key0 & 0x00ff0000) >> 16);
            key[j + 3] ^= (byte)((key0 & 0xff000000) >> 24);
        }
        RijndaelManaged rijn = new RijndaelManaged();
        using (var s = new CryptoStream(new MemoryStream(dat), rijn.CreateDecryptor(key, iv), CryptoStreamMode.Read))
        {
            byte[] l = new byte[4];
            s.Read(l, 0, 4);
            uint len = BitConverter.ToUInt32(l, 0);

            LzmaDecoder decoder = new LzmaDecoder();
            byte[] prop = new byte[5];
            s.Read(prop, 0, 5);
            decoder.SetDecoderProperties(prop);
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = s.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            byte[] ret = new byte[outSize];
            long compressedSize = len - 13;
            decoder.Code(s, new MemoryStream(ret, true), compressedSize, outSize);

            return ret;
        }
    }
Esempio n. 2
0
	public AES()
	{
		RijndaelManaged rm = new RijndaelManaged();
		_encryptor = rm.CreateEncryptor(_key, _vector);
		_decryptor = rm.CreateDecryptor(_key, _vector);
		encoder = new UTF8Encoding();
	}
    /// <summary>
    /// Decrypt byte array
    /// </summary>
    /// <param name="dataStream">encrypted data array</param>
    /// <param name="password">password</param>
    /// <returns>unencrypted data array</returns>
    private static byte[] DecryptStream(byte[] dataStream, string password)
    {
        SqlPipe pipe = SqlContext.Pipe;
        //the decrypter
        RijndaelManaged cryptic = new RijndaelManaged
        {
            Key = Encoding.ASCII.GetBytes(password),
            IV = Encoding.ASCII.GetBytes("1qazxsw23edcvfr4"),
            Padding = PaddingMode.ISO10126,
        };

        //Get a decryptor that uses the same key and IV as the encryptor used.
        ICryptoTransform decryptor = cryptic.CreateDecryptor();

        //Now decrypt encrypted data stream
        MemoryStream msDecrypt = new MemoryStream(dataStream);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

        byte[] fromEncrypt = new byte[dataStream.Length];

        //Read the data out of the crypto stream.
        try
        {
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        }
        catch (Exception e)
        {
            pipe.Send("Failed to decrypt data");
            pipe.Send(e.Message);
            throw;
        }

        return fromEncrypt;
    }
Esempio n. 4
0
 public static string Decrypt(string cipherText, string passPhrase)
 {
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
     {
         byte[] keyBytes = password.GetBytes(keysize / 8);
         using (RijndaelManaged symmetricKey = new RijndaelManaged())
         {
             symmetricKey.Mode = CipherMode.CBC;
             using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
             {
                 using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                 {
                     try
                     {
                         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                         {
                             byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                             int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
                         }
                     }
                     catch
                     {
                         return "ERROR";
                     }
                 }
             }
         }
     }
 }
Esempio n. 5
0
    public static string DecryptRijndael(string encryptedString)
    {
        byte[] encrypted;

        byte[] fromEncrypted;

        UTF8Encoding utf8Converter = new UTF8Encoding();

        encrypted = Convert.FromBase64String(encryptedString);

        RijndaelManaged myRijndael = new RijndaelManaged();

        ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV);

        MemoryStream ms = new MemoryStream(encrypted);

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

        fromEncrypted = new byte[encrypted.Length];

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

        string decryptedString = utf8Converter.GetString(fromEncrypted);
        int indexNull = decryptedString.IndexOf("\0");
        if (indexNull > 0)
        {
            decryptedString = decryptedString.Substring(0, indexNull);
        }
        return decryptedString;
    }
Esempio n. 6
0
    public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        // Set your salt here, change it to meet your flavor:
        // The salt bytes must be at least 8 bytes.
        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
          using (RijndaelManaged AES = new RijndaelManaged())
          {
        AES.KeySize = 256;
        AES.BlockSize = 128;

        var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);

        AES.Mode = CipherMode.CBC;

        using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
        {
          cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
          cs.Close();
        }
        decryptedBytes = ms.ToArray();
          }
          //end public byte[] AES_Decrypt
        }

        return decryptedBytes;
    }
 // Token: 0x06000EF8 RID: 3832 RVA: 0x00045384 File Offset: 0x00043584
 public static string Decrypt(string encrypted)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     ICryptoTransform decryptor = rijndaelManaged.CreateDecryptor(SimpleAES.key, SimpleAES.vector);
     UTF8Encoding uTF8Encoding = new UTF8Encoding();
     return uTF8Encoding.GetString(SimpleAES.Decrypt(Convert.FromBase64String(encrypted), decryptor));
 }
Esempio n. 8
0
        public static byte[] Decrypt(byte[] cipherText, string passPhrase,bool padding)
        {
            byte[] cipherTextBytes = cipherText;
            using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
            {
                byte[] keyBytes = password.GetBytes(keysize / 8);
                using (RijndaelManaged symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.Mode = CipherMode.CBC;
                    if(!padding)
                        symmetricKey.Padding = PaddingMode.None;
                    using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
                    {
                        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                        {

                                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                {
                                    byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                                    cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                    return plainTextBytes;
                                }

                        }
                    }
                }
            }
        }
 /// <summary>
 /// Decrypts a Base64 encoded string previously generated with a specific crypt class, returns a string
 /// </summary>
 /// <param name="cipherText">A base64 encoded string containing encryption information</param>
 /// <param name="passPhrase">The passphrase used to encrypt the inputed text</param>
 /// <returns></returns>
 public string Decrypt(string cipherText, string passPhrase)
 {
     try
         {
             var ciphertextS = DecodeFrom64(cipherText);
             var ciphersplit = Regex.Split(ciphertextS, "-");
             var passsalt = Convert.FromBase64String(ciphersplit[1]);
             var initVectorBytes = Convert.FromBase64String(ciphersplit[0]);
             var cipherTextBytes = Convert.FromBase64String(ciphersplit[2]);
             var password = new PasswordDeriveBytes(passPhrase, passsalt, "SHA512", 100);
             var keyBytes = password.GetBytes(256/8);
             var symmetricKey = new RijndaelManaged();
             symmetricKey.Mode = CipherMode.CBC;
             var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
             var memoryStream = new MemoryStream(cipherTextBytes);
             var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
             var plainTextBytes = new byte[cipherTextBytes.Length];
             var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
             memoryStream.Close();
             cryptoStream.Close();
             return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
         }
         catch (Exception m)
         {
             return "error";
         }
 }
Esempio n. 10
0
    private static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                try
                {
                    AES.KeySize = AESKeySize_256;
                    AES.Key = passwordBytes;
                    AES.Mode = AESCipherMode_ECB;
                    AES.Padding = AESPadding_PKCS7;

                    using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
                catch (CryptographicException e)
                {
                    throw e;
                }
            }
        }

        return decryptedBytes;
    }
Esempio n. 11
0
    public static void DecryptFile(string path)
    {
        if (!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

        XmlDocument xmlFile = new XmlDocument();
        xmlFile.Load(path);
        XmlElement xmlRoot = xmlFile.DocumentElement;

        if (xmlRoot.ChildNodes.Count <= 1)
        {
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("86759426197648123460789546213421");
            byte[] toEncryptArray = Convert.FromBase64String (xmlRoot.InnerXml);
            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);
            xmlRoot.InnerXml = UTF8Encoding.UTF8.GetString (resultArray);
        }
    }
    //Decrypts the save file for loading purposes
    public static void DecryptFile(string path)
    {
        if(!File.Exists(path))
        {
            Debug.Log("File Not Found At: " + path);
            return;
        }

        XDocument xmlFile = XDocument.Load (path);
        XmlReader reader = xmlFile.CreateReader ();

        reader.MoveToContent ();
        if(xmlFile.Root.Elements() != null)
        {
            Debug.Log("decrypting");
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes ("86759426197648123460789546213421");
            byte[] toEncryptArray = Convert.FromBase64String (reader.ReadInnerXml());
            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);
            string data = (UTF8Encoding.UTF8.GetString (resultArray));
            data = "<Root>" + data + "</Root>";
            xmlFile = (XDocument.Parse(data));

        }

        xmlFile.Save(path);
    }
Esempio n. 13
0
    public static byte[] Decrypt(byte[] data, string password)
    {
        byte[] result = null;
            byte[] passwordBytes = Encoding.Default.GetBytes(password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = keySize;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(passwordBytes, salt, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }
            }

            return result;
    }
Esempio n. 14
0
    internal static bool DecryptFile(string inputPath, string outputPath, string password)
    {
        var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

        // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
        // 1.The block size is set to 128 bits
        // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
        RijndaelManaged algorithm = new RijndaelManaged {KeySize = 256, BlockSize = 128};

        algorithm.Mode = CipherMode.CBC;

        var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

        algorithm.Key = key.GetBytes(algorithm.KeySize/8);
        algorithm.IV = key.GetBytes(algorithm.BlockSize/8);

        try
        {
        using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
        {
        CopyStream(input, decryptedStream);
        return true;
        }
        }
        catch (CryptographicException)
        {
        throw new InvalidDataException("Please supply a correct password");
        }
        catch (Exception ex)
        {
        throw new Exception(ex.Message);
        }
    }
Esempio n. 15
0
    /// <summary>
    /// Decrypts a previously encrypted string.
    /// </summary>
    /// <param name="inputText">The encrypted string to decrypt.</param>
    /// <returns>A decrypted string.</returns>
    public static string Decrypt(string inputText)
    {
        string decrypted = null;
        try
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        decrypted = Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }
        catch (Exception)
        {
        }
        return decrypted;
    }
 protected string DecryptString(string InputText, string Password)
 {
     try
     {
         RijndaelManaged RijndaelCipher = new RijndaelManaged();
         byte[] EncryptedData = Convert.FromBase64String(InputText);
         byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
         PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
         // Create a decryptor from the existing SecretKey bytes.
         ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(16), SecretKey.GetBytes(16));
         MemoryStream memoryStream = new MemoryStream(EncryptedData);
         // Create a CryptoStream. (always use Read mode for decryption).
         CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
         // Since at this point we don't know what the size of decrypted data
         // will be, allocate the buffer long enough to hold EncryptedData;
         // DecryptedData is never longer than EncryptedData.
         byte[] PlainText = new byte[EncryptedData.Length];
         // Start decrypting.
         int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
         memoryStream.Close();
         cryptoStream.Close();
         // Convert decrypted data into a string.
         string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
         // Return decrypted string.
         return DecryptedData;
     }
     catch (Exception exception)
     {
         return (exception.Message);
     }
 }
Esempio n. 17
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
    }
Esempio n. 18
0
    public List<string> GetAllData()
    {
        string line = "";
        string input_file = "./Saved Data/characters.xml";
        List<string> keyList = new List<string>();
        List<string> elemList = new List<string>();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] key = null;
        RijndaelManaged RMCrypto = new RijndaelManaged();
        string tagID;
        string tagIDend;
        int indexStart = 0;
        int indexEnd = 0;

        key = encoding.GetBytes(Data_Handler_Key.keyvalue);
        FileStream decrypted_file = new FileStream(input_file, FileMode.Open);
        CryptoStream cryptography_stream = new CryptoStream(decrypted_file, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
        using (MemoryStream msDecrypt = new MemoryStream())
        {
            using (BufferedStream readBuffer = new BufferedStream(cryptography_stream))
            using (StreamReader srDecrypt = new StreamReader(readBuffer))
            {
                    while ((line = srDecrypt.ReadLine()) != null)
                    {
                        elemList.Add(line);
                    }
            }
        }
        cryptography_stream.Close();
        decrypted_file.Close();
        tagID = "<id>" + Character_Info.id + "</id>";
        tagIDend = "<idend>" + Character_Info.id + "</idend>";
        int i = 0;
        foreach(var content in elemList)
        {
            if(content == tagID)
            {
                indexStart = i;
            }

            if(content == tagIDend)
            {
                indexEnd = i;
            }
            i++;
        }
        if (indexStart != indexEnd)
        {
            elemList.RemoveRange(indexStart, indexEnd - indexStart);
        }
        elemList.Remove("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        elemList.Remove("<savedcharacters>");
        elemList.Remove("</savedcharacters>");
        return elemList;
    }
Esempio n. 19
0
    private ICryptoTransform InitDecrypt(string a_key)
    {
        byte[] keyBytes = Encoding.Unicode.GetBytes(a_key);
        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(a_key, keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
        ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();
        rijndaelCSP.Clear();
        return decryptor;
    }
Esempio n. 20
0
    public SimpleAES()
    {
        //Метод шифрования
        RijndaelManaged rm = new RijndaelManaged();

        //Создаем метод шифрования и дешифрования, используя для этого ключ и вектор
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Используем чтобы перевести байты в текст и наоборот
        UTFEncoder = new System.Text.UTF8Encoding();
    }
Esempio n. 21
0
    public SimpleAES()
    {
        //This is our encryption method
        RijndaelManaged rm = new RijndaelManaged();

        //Create an encryptor and a decryptor using our encryption method, key, and vector.
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Used to translate bytes to text and vice versa
        UTFEncoder = new System.Text.UTF8Encoding();
    }
Esempio n. 22
0
    private static string DecryptStringFromBytes(byte[] cipherText, byte[] key, byte[] iv)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
        {
            throw new ArgumentNullException("cipherText");
        }
        if (key == null || key.Length <= 0)
        {
            throw new ArgumentNullException("key");
        }
        if (iv == null || iv.Length <= 0)
        {
            throw new ArgumentNullException("key");
        }

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

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (var rijAlg = new RijndaelManaged())
        {
            //Settings
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.PKCS7;
            rijAlg.FeedbackSize = 128;

            rijAlg.Key = key;
            rijAlg.IV = iv;

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

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

        return plaintext;
    }
Esempio n. 23
0
    /// <summary>
    /// Constructor
    ///
    /// <param name="password">Public key
    public CsharpCryptography(string password)
    {
        //Encode digest
        var md5 = new MD5CryptoServiceProvider();
        _password = md5.ComputeHash(Encoding.UTF8.GetBytes(password));

        //Initialize objects
        _cipher = new RijndaelManaged();
        _cipher.Padding = PaddingMode.PKCS7;
        _decryptor = _cipher.CreateDecryptor(_password, IV);
        _encryptor = _cipher.CreateEncryptor(_password, IV);

    }
Esempio n. 24
0
 private string decryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
 {
     if (cipherText == null || cipherText.Length <= 0)
     {
         throw new ArgumentNullException("cipherText");
     }
     if (Key == null || Key.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     if (IV == null || IV.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     MemoryStream memoryStream = null;
     CryptoStream cryptoStream = null;
     StreamReader streamReader = null;
     RijndaelManaged rijndaelManaged = null;
     string result = null;
     try
     {
         rijndaelManaged = new RijndaelManaged();
         rijndaelManaged.Key = Key;
         rijndaelManaged.IV = IV;
         var transform = rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV);
         memoryStream = new MemoryStream(cipherText);
         cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read);
         streamReader = new StreamReader(cryptoStream);
         result = streamReader.ReadToEnd();
     }
     finally
     {
         if (streamReader != null)
         {
             streamReader.Close();
         }
         if (cryptoStream != null)
         {
             cryptoStream.Close();
         }
         if (memoryStream != null)
         {
             memoryStream.Close();
         }
         if (rijndaelManaged != null)
         {
             rijndaelManaged.Clear();
         }
     }
     return result;
 }
Esempio n. 25
0
    /// <summary> 
    /// Decrypt the given string.  Assumes the string was encrypted using  
    /// EncryptStringAES(), using an identical sharedSecret. 
    /// </summary> 
    /// <param name="cipherText">The text to decrypt.</param> 
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param> 
    public static string DecryptStringAES( string cipherText, string sharedSecret )
    {
        if ( string.IsNullOrEmpty( cipherText ) )
            throw new ArgumentNullException( "cipherText" );
        if ( string.IsNullOrEmpty( sharedSecret ) )
            throw new ArgumentNullException( "sharedSecret" );

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

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

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes( sharedSecret, _salt );

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String( cipherText );
            using ( MemoryStream msDecrypt = new MemoryStream( bytes ) )
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes( aesAlg.KeySize / 8 );
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray( msDecrypt );
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor( aesAlg.Key, aesAlg.IV );
                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();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if ( aesAlg != null )
                aesAlg.Clear();
        }

        return plaintext;
    }
    static Boolean Test(CipherMode md)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        RijndaelManaged     des = new RijndaelManaged();
        des.Mode = md;
//        des.FeedbackSize = 0;
//		des.Padding = PaddingMode.PKCS7;

        Console.WriteLine("DES default key size = " + des.KeySize);
        ICryptoTransform sse = des.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + des.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

//        RijndaelManaged     des = new RijndaelManaged();
//        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
        ICryptoTransform ssd = des.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + des.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
Esempio n. 27
0
    public static string DecryptID(string toDecrypt)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        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);
    }
Esempio n. 28
0
	public string Decrypt(string toD)
	{
		//加密和解密采用相同的key,具体值自己填,但是必须为32位//
		byte[] keyArray = UTF8Encoding.UTF8.GetBytes(KEY);
		RijndaelManaged rDel = new RijndaelManaged();
		rDel.Key = keyArray;
		rDel.Mode = CipherMode.ECB;
		rDel.Padding = PaddingMode.PKCS7;
		ICryptoTransform cTransform = rDel.CreateDecryptor();
		
		byte[] toEncryptArray = Convert.FromBase64String(toD);
		byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);
		
		return UTF8Encoding.UTF8.GetString(resultArray);
	}
Esempio n. 29
0
    public static string Decrypt(string encryptedText)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }
Esempio n. 30
0
 public string Decrypt(string cipherText, string passPhrase)
 {
     byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
     byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
     PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
     byte[] keyBytes = password.GetBytes(keysize / 8);
     RijndaelManaged symmetricKey = new RijndaelManaged();
     symmetricKey.Mode = CipherMode.CBC;
     ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
     MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
     CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
     byte[] plainTextBytes = new byte[cipherTextBytes.Length];
     int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
     memoryStream.Close();
     cryptoStream.Close();
     return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
 }
Esempio n. 31
0
        public void TestDecrytp()
        {
            //for (int i = 0; i < 10000; i++)
            {
                ECDiffieHellmanCng bob = new ECDiffieHellmanCng
                {
                    KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                    HashAlgorithm         = CngAlgorithm.Rsa
                };

                string clientPubKeyString  = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs";
                var    clientPublicKeyBlob = Base64Url.Decode(clientPubKeyString);

                //GetCryptoServiceProvider(clientPublicKeyBlob);


                //clientPublicKeyBlob = FixPublicKey(clientPublicKeyBlob);

                Assert.AreEqual(120, clientPublicKeyBlob.Length);

                //var clientPubKey = ECDiffieHellmanCngPublicKey.FromByteArray(clientPublicKeyBlob, CngKeyBlobFormat.EccPublicBlob);

                //string serverSecKeyString = "MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB";
                //var serverSecKeyBlob = Base64Url.Decode(serverSecKeyString);
                //serverSecKeyBlob = FixPublicKey(serverSecKeyBlob);
                //Assert.AreEqual(40, serverSecKeyBlob.Length);
                //var serverPrivKey = ECDiffieHellmanCngPublicKey.FromByteArray(serverSecKeyBlob, CngKeyBlobFormat.Pkcs8PrivateBlob);


                //byte[] bobKey = bob.DeriveKeyMaterial(bob.PublicKey);

                using (RijndaelManaged rijAlg = new RijndaelManaged())
                {
                    rijAlg.BlockSize    = 128;
                    rijAlg.Padding      = PaddingMode.None;
                    rijAlg.Mode         = CipherMode.CFB;
                    rijAlg.FeedbackSize = 8;

                    rijAlg.Key = Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4=");
                    rijAlg.IV  = Base64Url.Decode("ZOBpyzki/M8UZv5tiBih0w==");

                    Assert.AreEqual(32, rijAlg.Key.Length);

                    Assert.AreEqual(rijAlg.Key.Take(16).ToArray(), rijAlg.IV);

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

                    // Create the streams used for decryption.
                    using (MemoryStream msDecrypt = new MemoryStream())
                    {
                        byte[] buffer1 = SoapHexBinary.Parse("4B4FCA0C2A4114155D67F8092154AAA5EF").Value;
                        byte[] buffer2 = SoapHexBinary.Parse("DF53B9764DB48252FA1AE3AEE4").Value;
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Position = 0;
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] result1 = new byte[17];
                            csDecrypt.Read(result1, 0, 17);

                            msDecrypt.Position = 0;
                            msDecrypt.SetLength(0);
                            ;

                            msDecrypt.Write(buffer2, 0, buffer2.Length);
                            msDecrypt.Position = 0;

                            byte[] result2 = new byte[13];
                            csDecrypt.Read(result2, 0, 13);

                            Assert.AreEqual(SoapHexBinary.Parse("0400000000499602D2FC2FCB233F34D5DD").Value, result1);
                            Assert.AreEqual(SoapHexBinary.Parse("3C000000085A446D11C0C7AA5A").Value, result2);


                            // Hashing
                            MemoryStream hashStream = new MemoryStream();
                            Assert.True(BitConverter.IsLittleEndian);
                            hashStream.Write(BitConverter.GetBytes(1L), 0, 8);
                            byte[] text = SoapHexBinary.Parse("3C00000008").Value;
                            hashStream.Write(text, 0, text.Length);
                            hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);

                            SHA256Managed crypt  = new SHA256Managed();
                            var           buffer = hashStream.ToArray();
                            byte[]        crypto = crypt.ComputeHash(buffer, 0, buffer.Length).Take(8).ToArray();
                            Assert.AreEqual(SoapHexBinary.Parse("5A446D11C0C7AA5A").Value, crypto);
                        }
                    }
                    using (MemoryStream msDecrypt = new MemoryStream())
                    {
                        byte[] buffer1 = SoapHexBinary.Parse("4B4FCA0C2A4114155D67F8092154AAA5EF").Value;
                        byte[] buffer2 = SoapHexBinary.Parse("DF53B9764DB48252FA1AE3AEE4").Value;
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Write(buffer2, 0, buffer2.Length);
                        msDecrypt.Position = 0;
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] result1 = new byte[buffer1.Length];
                            csDecrypt.Read(result1, 0, result1.Length);

                            byte[] result2 = new byte[13];
                            csDecrypt.Read(result2, 0, 13);

                            Assert.AreEqual(SoapHexBinary.Parse("0400000000499602D2FC2FCB233F34D5DD").Value, result1);
                            Assert.AreEqual(SoapHexBinary.Parse("3C000000085A446D11C0C7AA5A").Value, result2);


                            // Hashing
                            MemoryStream hashStream = new MemoryStream();
                            Assert.True(BitConverter.IsLittleEndian);
                            hashStream.Write(BitConverter.GetBytes(1L), 0, 8);
                            byte[] text = SoapHexBinary.Parse("3C00000008").Value;
                            hashStream.Write(text, 0, text.Length);
                            hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);

                            SHA256Managed crypt  = new SHA256Managed();
                            var           buffer = hashStream.ToArray();
                            byte[]        crypto = crypt.ComputeHash(buffer, 0, buffer.Length).Take(8).ToArray();
                            Assert.AreEqual(SoapHexBinary.Parse("5A446D11C0C7AA5A").Value, crypto);
                        }
                    }
                }
            }
        }
        public string DecryptText(string encryptedText)
        {
            byte[] key = Encoding.UTF8.GetBytes(_keyString);
            byte[] iv  = Encoding.UTF8.GetBytes(_ivString);

            using (RijndaelManaged rijndaelManaged = new RijndaelManaged {
                Key = key, IV = iv, Mode = CipherMode.CBC
            })
            {
                using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(encryptedText)))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                    {
                        return(new StreamReader(cryptoStream).ReadToEnd());
                    }
                }
            }
        }
Esempio n. 33
0
        private void LoadImageDataBasic()
        {
            UInt32 memorySize = 0;
            int    blockCount = xexData.file_format_info.basic_blocks.Count;

            for (int i = 0; i < blockCount; i++)
            {
                XexFileBasicCompressionBlock block = xexData.file_format_info.basic_blocks[i];
                memorySize += block.data_size + block.zero_size;
            }

            UInt32 maxImageSize = 128 << 20;

            if (memorySize >= maxImageSize)
            {
                throw new BadImageFormatException($"Computed image size is to big ({memorySize}), the exe offset = 0x{xexData.header.header_size}");
            }

            byte[] memory = new byte[memorySize];

            byte[]   ivec = new byte[16];
            Rijndael aes  = new RijndaelManaged()
            {
                BlockSize = 128,
                KeySize   = 128,
                Key       = xexData.session_key,
                IV        = ivec,
                Mode      = CipherMode.CBC,
                Padding   = PaddingMode.None
            };
            var dec = aes.CreateDecryptor();

            int sourceOffset = (int)xexData.header.header_size;
            int destOffset   = 0;

            for (int n = 0; n < blockCount; n++)
            {
                XexFileBasicCompressionBlock block = xexData.file_format_info.basic_blocks[n];
                UInt32 data_size = block.data_size;
                UInt32 zero_size = block.zero_size;

                XEXEncryptionType encType = xexData.file_format_info.encryption_type;
                switch (encType)
                {
                case XEXEncryptionType.XEX_ENCRYPTION_NONE:
                    Array.Copy(rdr.Bytes, sourceOffset, memory, destOffset, data_size);
                    break;

                case XEXEncryptionType.XEX_ENCRYPTION_NORMAL:
                    byte[] pt = dec.TransformFinalBlock(rdr.Bytes, sourceOffset, (int)data_size);
                    Array.Copy(pt, 0, memory, destOffset, data_size);
                    break;
                }
                sourceOffset += (int)(data_size);
                destOffset   += (int)(data_size + zero_size);
            }

            int consumed = sourceOffset;

            if (consumed > rdr.Bytes.Length)
            {
                throw new BadImageFormatException();
            }
            else if (consumed < rdr.Bytes.Length)
            {
                decompilerEventListener.Warn(new NullCodeLocation(""),
                                             $"XEX: {rdr.Bytes.Length - consumed} bytes of data was not consumed in block decompression (out of {rdr.Bytes.Length})"
                                             );
            }

            int numOutputed = destOffset;

            if (numOutputed > memorySize)
            {
                throw new BadImageFormatException($"XEX: To much data was outputed in block decompression ({numOutputed} > {memorySize})");
            }
            else if (numOutputed < memorySize)
            {
                decompilerEventListener.Warn(new NullCodeLocation(""),
                                             $"XEX: {memorySize - numOutputed} bytes of data was not outputed in block decompression (out of {memorySize})"
                                             );
            }

            xexData.memoryData = memory;
            xexData.memorySize = memorySize;
        }
Esempio n. 34
0
        public void TestRealDecrytp()
        {
            // YFtS5MGIU/UQ2w2n3RdqMoBcHOzqEQqISOyKD+W9Prk=

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.BlockSize    = 128;
                rijAlg.Padding      = PaddingMode.None;
                rijAlg.Mode         = CipherMode.CFB;
                rijAlg.FeedbackSize = 8;

                rijAlg.Key = Base64Url.Decode("Tv9JFj4vhftDXgcjpNWNocWZrVKaVpF+icEh51M8MvI=");
                rijAlg.IV  = rijAlg.Key.Take(16).ToArray();

                Assert.AreEqual(rijAlg.Key.Take(16).ToArray(), rijAlg.IV);

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream())
                {
                    byte[] buffer1 = SoapHexBinary.Parse("172e0592aba239d86b7ca2384cfad4e4fa5b883ff6db73931ecd").Value;
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Position = 0;
                        byte[] checksum;
                        byte[] clearBytes;
                        using (var clearBuffer = new MemoryStream())
                        {
                            var buffer = new byte[1024];
                            var read   = csDecrypt.Read(buffer, 0, buffer.Length);
                            while (read > 0)
                            {
                                clearBuffer.Write(buffer, 0, read);
                                read = csDecrypt.Read(buffer, 0, buffer.Length);
                            }
                            csDecrypt.Flush();

                            var fullResult = clearBuffer.ToArray();
                            clearBytes = (byte[])fullResult.Take(fullResult.Length - 8).ToArray();
                            checksum   = fullResult.Skip(fullResult.Length - 8).ToArray();
                        }

                        Assert.AreEqual(6, clearBytes[0]);

                        Package message = PackageFactory.CreatePackage(clearBytes[0], clearBytes, "mcpe");
                        Assert.NotNull(message);
                        Assert.AreEqual(typeof(McpeWrapper), message.GetType());

                        List <Package> messages           = HandleBatch((McpeWrapper)message);
                        McpeClientToServerHandshake magic = (McpeClientToServerHandshake)messages.FirstOrDefault();
                        Assert.AreEqual(typeof(McpeClientToServerHandshake), magic?.GetType());

                        //Hashing - Checksum - Validation
                        MemoryStream hashStream = new MemoryStream();
                        Assert.True(BitConverter.IsLittleEndian);
                        hashStream.Write(BitConverter.GetBytes(0L), 0, 8);
                        hashStream.Write(clearBytes, 0, clearBytes.Length);
                        hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);
                        SHA256Managed crypt              = new SHA256Managed();
                        var           hashBuffer         = hashStream.ToArray();
                        byte[]        validationCheckSum = crypt.ComputeHash(hashBuffer, 0, hashBuffer.Length).Take(8).ToArray();
                        Assert.AreEqual(checksum, validationCheckSum);
                    }
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        ///     Decrypts a file and saves it to the opath destination.
        /// </summary>
        /// <param name="ifile">file to be decrypted.</param>
        /// <param name="backup">location of encrypted files.</param>
        /// <param name="oroot">targeted root directory to save decrypted file in.</param>
        /// <returns>a bool if it succeeded or not.</returns>
        public static bool DecryptFile(string ifile, string backup, string oroot)
        {
            RijndaelManaged AES = new RijndaelManaged();

            AES.KeySize   = 256;
            AES.BlockSize = 128;
            AES.Padding   = PaddingMode.PKCS7;
            AES.Mode      = CipherMode.CBC;

            using (FileStream fsCrypt = new FileStream(ifile, FileMode.Open))
            {
                byte[] salt = new byte[Hash.m_SaltSize];
                fsCrypt.Read(salt, 0, Hash.m_SaltSize);

                if (m_dHash == null)
                {
                    GetHash(salt, 2, out m_dHash);
                }

                Console.WriteLine("\tDEBUG DecryptFile:\n\t\tSalt Obtained: {0}\n\t\tHash: {1}", Encoding.UTF8.GetString(salt), m_dHash.ToString());


                Rfc2898DeriveBytes key = m_dHash.GetDerivedBytes();
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV  = key.GetBytes(AES.BlockSize / 8);

                string cleanedPath = CleanBackup(ifile, backup);
                string filename    = Path.GetFileName(CleanExtension(ifile));
                string subchild    = Path.Combine(cleanedPath, filename);
                string outFile     = Path.GetFullPath(oroot + subchild);

                // Create our directory for the file if it doesn't exist.
                Program.CreateDirectory(Path.GetFullPath(oroot + cleanedPath));

                try
                {
                    using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read))
                        using (FileStream fs = new FileStream(outFile, FileMode.Create))
                        {
                            byte[] buffer = new byte[1048576];
                            int    read;

                            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fs.Write(buffer, 0, read);
                            }
                        }

                    m_dHash.KeyReset();
                    return(true);
                }
                catch (CryptographicException ce)
                {
                    Console.WriteLine(Error.Print(m_offset, "Potential password issue", ce));
                }
                catch (Exception e)
                {
                    Console.WriteLine(Error.Print(m_offset, "Unknown issue occured", e));
                }

                m_dHash.KeyReset();
                return(false);
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Read all bytes from an encrypted SecureFile
        /// </summary>
        /// <param name="filename">A string containing the path to the file to read</param>
        /// <param name="passphrase">A string containing the passphrase used to encrypt the orginal
        /// file</param>
        /// <param name="iv">A byte array containing the initialization vector (IV) used to encrypt
        /// the orginal file</param>
        /// <returns>An array of bytes representing the unecrypted file's contents</returns>
        public static byte[] ReadAllBytes(string filename, string passphrase, byte[] iv)
        {
            try
            {
                // Only do this if the specified file exists:
                if (File.Exists(filename))
                {
                    // Open the file through a FileStream:
                    FileStream fs = new FileStream(filename, FileMode.Open);

                    // Don't go any further if the file is too big to work with:
                    if (fs.Length < Convert.ToInt64(Int32.MaxValue))
                    {
                        // Read all of its contents into a byte array:
                        byte[] rawData    = new byte[(int)fs.Length];
                        int    totalBytes = fs.Read(rawData, 0, (int)fs.Length);
                        fs.Close();

                        // As long as there's something to work with:
                        if (totalBytes > 0)
                        {
                            // Set up the decryption transform and streams:
                            if (rijndael.ValidKeySize(256))
                            {
                                rijndael.KeySize = 256;
                            }
                            rijndael.Padding = PaddingMode.PKCS7;
                            ICryptoTransform decryptor =
                                rijndael.CreateDecryptor(HashPassphrase(passphrase), iv);
                            MemoryStream ms = new MemoryStream(rawData);
                            CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

                            // Create a new byte array to hold the decrypted data, then read the
                            // decrypted data into it.  The Close()s should remove the padding from
                            // the data automatically.
                            byte[] fromEncrypt = new byte[totalBytes];
                            cs.Read(fromEncrypt, 0, fromEncrypt.Length);
                            cs.Close();
                            ms.Close();

                            // Now we need to decompress the data.  We'll reuse the same memory stream
                            // and wrap a GZipStream around it:
                            ms = new MemoryStream(fromEncrypt);
                            GZipStream unzipper = new GZipStream(ms, CompressionMode.Decompress);
                            // We have no idea how big the uncompressed data will be, but we'll pad
                            // that with some extra space, just in case:
                            byte[] uncompressedData = new byte[fromEncrypt.Length *
                                                               uncompressArrayPadding];
                            // Now read the bytes from the decompression stream:
                            totalBytes = ReadAllBytesFromStream(unzipper, uncompressedData);
                            unzipper.Close();
                            ms.Close();

                            // Next we need to validate the header to make sure the password was entered
                            // correctly.  Find out how long the header should be in bytes and make sure
                            // the uncompressed, unencrypted data is at least that long:
                            int headerByteLength = utf8.GetBytes(header).Length;
                            if (totalBytes > headerByteLength)
                            {
                                // Read the first so many bytes from the data, as many as should be in
                                // the header, and convert that to a string.  Then compare the string to the
                                // header and make sure they match.  Also make sure that the length of the
                                // data minus the header is something worth processing.
                                string headerCheck = utf8.GetString(uncompressedData, 0,
                                                                    headerByteLength);
                                if (headerCheck == header &&
                                    uncompressedData.Length - headerByteLength > 0)
                                {
                                    // If everything checks out, then the file was read successfully.
                                    // Copy the bytes minus the header to another array and return it:
                                    byte[] result = new byte[totalBytes - headerByteLength];
                                    Array.Copy(uncompressedData, headerByteLength, result, 0,
                                               result.Length);
                                    return(result);
                                }
                                // Header did not match:
                                else
                                {
                                    throw new SecureFileException("Invalid passphrase for file " +
                                                                  filename);
                                }
                            }
                            // The file didn't have enough bytes to contain the header
                            else
                            {
                                throw new SecureFileException("The file " + filename + " appears " +
                                                              "to be invalid (the file is shorter than the expected header)");
                            }
                        }
                        // The file didn't have any data:
                        else
                        {
                            throw new SecureFileException("The file " + filename + " appears to " +
                                                          "be empty");
                        }
                    }
                    // The file was over 2GB:
                    else
                    {
                        throw new SecureFileException("The file " + filename + " is too large for " +
                                                      "me to process");
                    }
                }
                // If the file didn't exist, just return null:
                else
                {
                    throw new SecureFileException("The file " + filename + " does not exist");
                }
            }
            #region Catch Exceptions
            catch (UnauthorizedAccessException)
            {
                throw new SecureFileException("You do not appear to have the necessar permissions " +
                                              "to read the file " + filename);
            }
            catch (System.Security.SecurityException)
            {
                throw new SecureFileException("You do not appear to have the necessar permissions " +
                                              "to read the file " + filename);
            }
            catch (ArgumentException)
            {
                throw new SecureFileException("The path to the specified file is either empty or " +
                                              "contains invalid characters");
            }
            catch (IOException)
            {
                throw new SecureFileException("An I/O error occurred while trying to read the file " +
                                              filename);
            }
            // Rethrow any SecureFileExceptions thrown above:
            catch (SecureFileException sfe) { throw sfe; }
            // Catch anything else that wasn't caught:
            catch (Exception ex)
            {
                throw new SecureFileException(ex.Message);
            }
            #endregion
        }
Esempio n. 37
0
 private StreamReader CreateRijndaelDecryptor(List <byte> parts)
 {
     return(new StreamReader(new CryptoStream(new MemoryStream(parts.ToArray()), _rijndael.CreateDecryptor(), CryptoStreamMode.Read)));
 }
Esempio n. 38
0
        protected void DecodeCert(McpeLogin message)
        {
            _playerInfo = new PlayerInfo();

            // Get bytes
            byte[] buffer = message.payload;

            //Log.Debug($"Unknown byte in login packet is: {message.unknown}");

            if (message.payload.Length != buffer.Length)
            {
                Log.Debug($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
                throw new Exception($"Wrong lenght {message.payload.Length} != {message.payload.Length}");
            }
            // Decompress bytes

            Log.Debug("Lenght: " + message.payload.Length + ", Message: " + Convert.ToBase64String(buffer));

            MemoryStream stream = new MemoryStream(buffer);

            if (stream.ReadByte() != 0x78)
            {
                throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
            }
            stream.ReadByte();

            string certificateChain;
            string skinData;

            using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
            {
                // Get actual package out of bytes
                using (MemoryStream destination = MiNetServer.MemoryStreamManager.GetStream())
                {
                    defStream2.CopyTo(destination);
                    destination.Position = 0;
                    fNbt.NbtBinaryReader reader = new fNbt.NbtBinaryReader(destination, false);

                    try
                    {
                        var countCertData = reader.ReadInt32();
                        Log.Debug("Count cert: " + countCertData);
                        certificateChain = Encoding.UTF8.GetString(reader.ReadBytes(countCertData));
                        Log.Debug("Decompressed certificateChain " + certificateChain);

                        var countSkinData = reader.ReadInt32();
                        Log.Debug("Count skin: " + countSkinData);
                        skinData = Encoding.UTF8.GetString(reader.ReadBytes(countSkinData));
                        Log.Debug("Decompressed skinData" + skinData);
                    }
                    catch (Exception e)
                    {
                        Log.Error("Parsing login", e);
                        return;
                    }
                }
            }


            try
            {
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("Input JSON string: " + certificateChain);
                    }

                    dynamic json = JObject.Parse(certificateChain);

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"JSON:\n{json}");
                    }

                    string validationKey = null;
                    foreach (dynamic o in json.chain)
                    {
                        IDictionary <string, dynamic> headers = JWT.Headers(o.ToString());

                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug("Raw chain element:\n" + o.ToString());
                            Log.Debug($"JWT Header: {string.Join(";", headers)}");

                            dynamic jsonPayload = JObject.Parse(JWT.Payload(o.ToString()));
                            Log.Debug($"JWT Payload:\n{jsonPayload}");
                        }

                        // x5u cert (string): MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V
                        if (headers.ContainsKey("x5u"))
                        {
                            string certString = headers["x5u"];

                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"x5u cert (string): {certString}");
                                ECDiffieHellmanPublicKey publicKey = CryptoUtils.CreateEcDiffieHellmanPublicKey(certString);
                                Log.Debug($"Cert:\n{publicKey.ToXmlString()}");
                            }

                            // Validate
                            CngKey          newKey = CryptoUtils.ImportECDsaCngKeyFromString(certString);
                            CertificateData data   = JWT.Decode <CertificateData>(o.ToString(), newKey);

                            if (data != null)
                            {
                                if (Log.IsDebugEnabled)
                                {
                                    Log.Debug("Decoded token success");
                                }

                                if (CertificateData.MojangRootKey.Equals(certString, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    Log.Debug("Got Mojang key. Is valid = " + data.CertificateAuthority);
                                    validationKey = data.IdentityPublicKey;
                                }
                                else if (validationKey != null && validationKey.Equals(certString, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    _playerInfo.CertificateData = data;
                                }
                                else
                                {
                                    if (data.ExtraData == null)
                                    {
                                        continue;
                                    }

                                    // Self signed, make sure they don't fake XUID
                                    if (data.ExtraData.Xuid != null)
                                    {
                                        Log.Warn("Received fake XUID from " + data.ExtraData.DisplayName);
                                        data.ExtraData.Xuid = null;
                                    }

                                    _playerInfo.CertificateData = data;
                                }
                            }
                            else
                            {
                                Log.Error("Not a valid Identity Public Key for decoding");
                            }
                        }
                    }

                    //TODO: Implement disconnect here

                    {
                        _playerInfo.Username = _playerInfo.CertificateData.ExtraData.DisplayName;
                        _session.Username    = _playerInfo.Username;
                        string identity = _playerInfo.CertificateData.ExtraData.Identity;

                        if (Log.IsDebugEnabled)
                        {
                            Log.Debug($"Connecting user {_playerInfo.Username} with identity={identity}");
                        }
                        _playerInfo.ClientUuid = new UUID(new Guid(identity));

                        _session.CryptoContext = new CryptoContext
                        {
                            UseEncryption = Config.GetProperty("UseEncryptionForAll", false) || (Config.GetProperty("UseEncryption", true) && !string.IsNullOrWhiteSpace(_playerInfo.CertificateData.ExtraData.Xuid)),
                        };

                        if (_session.CryptoContext.UseEncryption)
                        {
                            ECDiffieHellmanPublicKey publicKey = CryptoUtils.CreateEcDiffieHellmanPublicKey(_playerInfo.CertificateData.IdentityPublicKey);
                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"Cert:\n{publicKey.ToXmlString()}");
                            }

                            // Create shared shared secret
                            ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(384);
                            ecKey.HashAlgorithm         = CngAlgorithm.Sha256;
                            ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
                            ecKey.SecretPrepend         = Encoding.UTF8.GetBytes("RANDOM SECRET");                     // Server token

                            byte[] secret = ecKey.DeriveKeyMaterial(publicKey);

                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"SECRET KEY (b64):\n{Convert.ToBase64String(secret)}");
                            }

                            {
                                RijndaelManaged rijAlg = new RijndaelManaged
                                {
                                    BlockSize    = 128,
                                    Padding      = PaddingMode.None,
                                    Mode         = CipherMode.CFB,
                                    FeedbackSize = 8,
                                    Key          = secret,
                                    IV           = secret.Take(16).ToArray(),
                                };

                                // Create a decrytor to perform the stream transform.
                                ICryptoTransform decryptor      = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
                                MemoryStream     inputStream    = new MemoryStream();
                                CryptoStream     cryptoStreamIn = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read);

                                ICryptoTransform encryptor       = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
                                MemoryStream     outputStream    = new MemoryStream();
                                CryptoStream     cryptoStreamOut = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write);

                                _session.CryptoContext.Algorithm       = rijAlg;
                                _session.CryptoContext.Decryptor       = decryptor;
                                _session.CryptoContext.Encryptor       = encryptor;
                                _session.CryptoContext.InputStream     = inputStream;
                                _session.CryptoContext.OutputStream    = outputStream;
                                _session.CryptoContext.CryptoStreamIn  = cryptoStreamIn;
                                _session.CryptoContext.CryptoStreamOut = cryptoStreamOut;
                            }

                            var response = McpeServerExchange.CreateObject();
                            response.NoBatch         = true;
                            response.ForceClear      = true;
                            response.serverPublicKey = Convert.ToBase64String(ecKey.PublicKey.GetDerEncoded());
                            response.tokenLength     = (short)ecKey.SecretPrepend.Length;
                            response.token           = ecKey.SecretPrepend;

                            _session.SendPackage(response);

                            if (Log.IsDebugEnabled)
                            {
                                Log.Warn($"Encryption enabled for {_session.Username}");
                            }
                        }
                    }
                }

                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug("Input SKIN string: " + skinData);
                    }

                    IDictionary <string, dynamic> headers = JWT.Headers(skinData);
                    dynamic payload = JObject.Parse(JWT.Payload(skinData));

                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Header: {string.Join(";", headers)}");
                    }
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Skin JWT Payload:\n{payload.ToString()}");
                    }

                    // Skin JWT Payload:

                    //{
                    //	"ADRole": 2,
                    //	"ClientRandomId": -1256727416,
                    //	"CurrentInputMode": 2,
                    //	"DefaultInputMode": 2,
                    //	"DeviceModel": "SAMSUNG GT-P5210",
                    //	"DeviceOS": 1,
                    //	"GameVersion": "1.0.3.0",
                    //	"GuiScale": 0,
                    //	"ServerAddress": "192.168.0.3:19132",
                    //	"SkinData": "AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP9UJgn/RyEI/1YpCP9GJAj/QR8E/08qCv9NKQn/SyQF//KuaP/yrmj/8q5o//KuaP/yrmj/8q5o//KuaP/yrmj/AAAA/wAAAP8AAAD/AAAA/wAAAP8AA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H/9/8B//f/AgIC/wICAv8UFBT/Af/3/wICAv8CAgL/AgIC/wICAv8CAgL/AAAA/wAAAP8AAAD/AAAA/wkJCf8FBQX/BgYG/wgICP8ICAj/AAAA/wgICP8ICAj/CAgI/wAAAP8AAAD/AAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgIC/wICAv8CAgL/AgIC/wICAv8CAgL/AgIC/wICAv8CAgL/AgIC/wICAv8CAgL/AgIC/wICAv8CAgL/AgIC//KuaP/yrmj/8q5o//KuaP/yrmj/AQEB/wAAAP8AAAD/BAMD/wgICP8AAAD/CQkJ/wkICP8AAAD/AAAA//KuaP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v/yrmj/8q5o//KuaP/yrmj/8q5o//KuaP8AAAD/Af/3/wH/9/8B//f/Af/3/wH/9/8B//f/AwIC//KuaP/yrmj/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
                    //	"SkinId": "Standard_Custom",
                    //	"TenantId": "",
                    //	"UIProfile": 1
                    //}

                    _playerInfo.ServerAddress = payload.ServerAddress;
                    _playerInfo.ClientId      = payload.ClientRandomId;

                    try
                    {
                        _playerInfo.CurrentInputMode = payload.CurrentInputMode;
                        _playerInfo.DefaultInputMode = payload.DefaultInputMode;
                        _playerInfo.DeviceModel      = payload.DeviceModel;
                        _playerInfo.DeviceOS         = payload.DeviceOS;
                        _playerInfo.GameVersion      = payload.GameVersion;
                        _playerInfo.GuiScale         = payload.GuiScale;
                        _playerInfo.UIProfile        = payload.UIProfile;
                    }
                    catch
                    {
                    }

                    _playerInfo.Skin = new Skin()
                    {
                        SkinType = payload.SkinId,
                        Texture  = Convert.FromBase64String((string)payload.SkinData),
                    };
                }

                if (!_session.CryptoContext.UseEncryption)
                {
                    _session.MessageHandler.HandleMcpeClientMagic(null);
                }
            }
            catch (Exception e)
            {
                Log.Error("Decrypt", e);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            switch (button3.Text)
            {
            default: break;

            case "Encryption":
            {
                try
                {
                    string          password    = textBox3.Text;
                    UnicodeEncoding UE          = new UnicodeEncoding();
                    byte[]          key         = UE.GetBytes(password);
                    String          cryptedfile = textBox2.Text;
                    FileStream      FsCrypt     = new FileStream(cryptedfile, FileMode.Create);
                    RijndaelManaged RMCrypt     = new RijndaelManaged();
                    CryptoStream    CS          = new CryptoStream(FsCrypt, RMCrypt.CreateEncryptor(key, key), CryptoStreamMode.Write);
                    FileStream      FSIN        = new FileStream(textBox1.Text, FileMode.Open);
                    int             data;
                    while ((data = FSIN.ReadByte()) != -1)
                    {
                        CS.WriteByte((byte)data);
                    }
                    FSIN.Close();
                    CS.Close();
                    FsCrypt.Close();
                    MessageBox.Show("Data Encrypted Successfully!", "Successfuly Encrypted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception)
                {
                    label2.Text = "The Encryption Operation Failed";
                    MessageBox.Show("Please Browse the Data You want to Encrypt and Insert  a Valid Password with 8 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                break;
            }


            case "Decryption":

            {
                try
                {
                    string          password    = textBox3.Text;
                    UnicodeEncoding UE          = new UnicodeEncoding();
                    byte[]          key         = UE.GetBytes(password);
                    String          cryptedfile = textBox1.Text;
                    FileStream      FsCrypt     = new FileStream(cryptedfile, FileMode.Open);
                    RijndaelManaged RMCrypt     = new RijndaelManaged();
                    CryptoStream    CS          = new CryptoStream(FsCrypt, RMCrypt.CreateDecryptor(key, key), CryptoStreamMode.Read);
                    FileStream      FSout       = new FileStream(textBox2.Text, FileMode.Create);
                    int             data;
                    while ((data = CS.ReadByte()) != -1)
                    {
                        FSout.WriteByte((byte)data);
                    }
                    FSout.Close();
                    CS.Close();
                    FsCrypt.Close();
                    MessageBox.Show("Data Decrypted Successfully!", "Successfuly Decrypted", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception)
                {
                    label2.Text = "Decryption Operation Failed";
                    MessageBox.Show("Please Browse the Encrypted Data You want to Decrypt and Insert a Valid Password with 8 Characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            }
            }
        }
        /// <summary>
        /// Decrypts the specified file and saves it to the given Filepath.
        /// </summary>
        /// <param name="cryptedFilePath">The file to be decrypted.</param>
        /// <param name="password">The password to use for the decryption.</param>
        /// <returns>The decrypted file as string.</returns>
        public static CryptographicOperationResult DecryptFileToFile(string cryptedFilePath, string newFilePath, string password, Encoding encoding, string salt = "asdk23904uasdfji", byte[] initVector = null)
        {
            if (initVector == null)
            {
                initVector = INIT_VECTOR;
            }

            if (string.IsNullOrEmpty(password))
            {
                return new CryptographicOperationResult()
                       {
                           IsSuccessful = false, IsPasswordWrong = true
                       }
            }
            ;

            SecureString securePwd = new SecureString();

            foreach (char c in password)
            {
                securePwd.AppendChar(c);
            }

            securePwd.MakeReadOnly();

            byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);

            //read file
            byte[] cipherTextBytes = null;
            using (StreamReader sr = new StreamReader(cryptedFilePath))
            {
                try
                {
                    cipherTextBytes = Convert.FromBase64String(sr.ReadToEnd());
                }
                catch (Exception e)
                {
                    Logger.AddLogEntry(Logger.LogEntryCategories.Error, "Exception while reading file '" + cryptedFilePath, e, "Security");
                    return(new CryptographicOperationResult()
                    {
                        IsSourceFaulty = true, IsSuccessful = false, Password = securePwd, Exception = e
                    });
                }
            }

            if (cipherTextBytes == null)
            {
                return new CryptographicOperationResult()
                       {
                           IsSuccessful = false, Password = securePwd
                       }
            }
            ;

            Rfc2898DeriveBytes passwordBytes = new Rfc2898DeriveBytes(password, saltValueBytes, 1000);

            byte[] keyBytes = passwordBytes.GetBytes(256 / 8);

            RijndaelManaged symmetricKey = new RijndaelManaged();

            symmetricKey.Mode = CipherMode.CBC;

            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVector);

            byte[] plainTextBytes;
            int    decryptedByteCount;

            try
            {
                using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        // Since at this point we don't know what the size of decrypted data will be, allocate the buffer long enough to hold ciphertext; plaintext is never longer than ciphertext.
                        plainTextBytes = new byte[cipherTextBytes.Length];

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

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

                using (StreamWriter sw = new StreamWriter(newFilePath, false, encoding))
                {
                    sw.Write(plainText);
                }
            }
            catch (CryptographicException ce) //usually means a wrong password
            {
                return(new CryptographicOperationResult()
                {
                    IsPasswordWrong = true, IsSuccessful = false, Password = securePwd, Exception = ce
                });
            }
            catch (Exception ex)
            {
                Logger.AddLogEntry(Logger.LogEntryCategories.Error, "Unhandled exception while decrypting file '" + cryptedFilePath + "' to file '" + newFilePath + "'.", ex, "Security");
                return(new CryptographicOperationResult()
                {
                    IsTargetFaulty = true, IsSuccessful = false, Password = securePwd, Exception = ex
                });
            }

            return(new CryptographicOperationResult()
            {
                IsSuccessful = true, Password = securePwd
            });
        }
Esempio n. 41
0
        /// <summary>
        /// Reads encrypted file into the <see cref="CryptoStream"/>.
        /// </summary>
        /// <param name="fileName">The path to the file to dencrypt.</param>
        /// <returns><see cref="CryptoStream"/> linked to the encrypted file data.</returns>
        public CryptoStream ReadEncryptedFile(string fileName)
        {
            FileInfo   fi = new FileInfo(fileName);
            FileStream inFile;

            #region Check for possible errors (includes verification of the signature).

            if (!_validParameters)
            {
                Trace.WriteLine("Invalid parameters - cannot perform requested action");
                return(null);
            }
            if (!fi.Exists)
            {
                Trace.WriteLine("Cannot perform decryption: File " + fileName + " does not exist.");
                return(null);
            }
            if (fi.Length > Int32.MaxValue)
            {
                Trace.WriteLine("This decryption method can only handle files up to 2GB in size.");
                return(null);
            }

            try
            {
                inFile = new FileStream(fileName, FileMode.Open);
            }
            catch (Exception exc)
            {
                Trace.WriteLine(exc.Message + "Cannot perform decryption");
                return(null);
            }
            if (!VerifySignature(inFile))
            {
                inFile.Close();
                Trace.WriteLine("Invalid signature - file was not encrypted using this program");
                return(null);
            }

            #endregion

            if (_rijn == null)
            {
                _rijn = new RijndaelManaged {
                    Padding = _paddingMode
                };
            }

            if (_decryptor == null)
            {
                _decryptor = _rijn.CreateDecryptor(_md5Key, _md5Iv);
            }

            // Allocate byte array buffer to read only the xml part of the file (ie everything following the signature).
            byte[] encryptedData = new byte[(int)fi.Length - _signature.Length];
            inFile.Position = _signature.Length;
            inFile.Read(encryptedData, 0, encryptedData.Length);

            // Convert the byte array to a MemoryStream object so that it can be passed on to the CryptoStream
            MemoryStream encryptedStream = new MemoryStream(encryptedData);
            // Create a CryptoStream, bound to the MemoryStream containing the encrypted xml data
            CryptoStream csDecrypt = new CryptoStream(encryptedStream, _decryptor, CryptoStreamMode.Read);

            // flush & close files.
            //encryptedXmlStream.Flush();
            //encryptedXmlStream.Close();
            inFile.Close();

            return(csDecrypt);
        }
Esempio n. 42
0
 private static byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
 {
     return(rijndaelManaged.CreateDecryptor()
            .TransformFinalBlock(encryptedData, 0, encryptedData.Length));
 }
Esempio n. 43
0
    public static byte[] _rAESMethod_(byte[] _rarg1_, bool _rarg2_ = false)
    {
        var _rarg3_ = Encoding.ASCII.GetBytes("#IV");
        var _rarg4_ = new Rfc2898DeriveBytes("#KEY", Encoding.ASCII.GetBytes("#SALT"), 100);
        var _rarg5_ = new RijndaelManaged()
        {
            KeySize = 256, Mode = CipherMode.CBC
        };
        var _rarg6_ = _rarg2_ ? _rarg5_.CreateEncryptor(_rarg4_.GetBytes(16), _rarg3_) : _rarg5_.CreateDecryptor(_rarg4_.GetBytes(16), _rarg3_);

        using (var _rarg7_ = new MemoryStream())
        {
            using (var _rarg8_ = new CryptoStream(_rarg7_, _rarg6_, CryptoStreamMode.Write))
            {
                _rarg8_.Write(_rarg1_, 0, _rarg1_.Length);
                _rarg8_.Close();
            }
            return(_rarg7_.ToArray());
        }
    }
Esempio n. 44
0
        //Decrypt a file into a XML Document
        public static XmlDocument DecryptFileToXmlDocument(string filePath, string password)
        {
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] salt          = new byte[32];

            //Open the crypted file
            FileStream fsCrypt = new FileStream(filePath, FileMode.Open);

            //Read the salt's byte
            fsCrypt.Read(salt, 0, salt.Length);

            RijndaelManaged AES = CreateRijndaelManaged(passwordBytes, salt);

            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);

            MemoryStream memoryStream = new MemoryStream();

            memoryStream.Flush();
            memoryStream.Position = 0;
            XmlDocument xmlDocument = new XmlDocument();

            int read;

            byte[] buffer = new byte[1048576];
            //Read the cryptoStream that read the file's byte and write decrypted byte into the memoryStream
            try
            {
                cs.Read(buffer, 0, 3);
                while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    memoryStream.Write(buffer, 0, read);
                }
                //Save into the xmlDocument the memoryStream's byte converted to string
                xmlDocument.LoadXml(Encoding.Default.GetString(memoryStream.ToArray()));
            }
            catch (CryptographicException ex_CryptographicException)
            {
                Console.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
            }
            catch (XmlException ex)
            {
                Console.WriteLine("Error: " + ex.Message + " linenumber : " + ex.LineNumber + " lineposition : " + ex.LinePosition);
            }

            //Close the differents streams
            try
            {
                cs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error by closing CryptoStream: " + ex.Message);
            }
            finally
            {
                memoryStream.Close();
                fsCrypt.Close();
            }

            return(xmlDocument);
        }
        /// <summary>
        /// Use this constructor if you are planning to perform encryption/
        /// decryption with the key derived from the explicitly specified
        /// parameters.
        /// </summary>
        /// <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 the
        /// passphrase is an ASCII string. Passphrase value must be kept in
        /// secret.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long. IV value does not have to be kept
        /// in secret.
        /// </param>
        /// <param name="minSaltLen">
        /// Min size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is less than 4, the default min value will be used (currently 4
        /// bytes).
        /// </param>
        /// <param name="maxSaltLen">
        /// Max size (in bytes) of randomly generated salt which will be added at
        /// the beginning of plain text before encryption is performed. When this
        /// value is negative or greater than 255, the default max value will be
        /// used (currently 8 bytes). If max value is 0 (zero) or if it is smaller
        /// than the specified min value (which can be adjusted to default value),
        /// salt will not be used and plain text value will be encrypted as is.
        /// In this case, salt will not be processed during decryption either.
        /// </param>
        /// <param name="keySize">
        /// Size of symmetric key (in bits): 128, 192, or 256.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hashing algorithm: "MD5" or "SHA1". SHA1 is recommended.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used for password hashing during key generation. This is
        /// not the same as the salt we will use during encryption. This parameter
        /// can be any string.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to hash password. More iterations are
        /// considered more secure but may take longer.
        /// </param>
        public RijndaelEnhanced(string passPhrase,
                                string initVector,
                                int minSaltLen,
                                int maxSaltLen,
                                int keySize,
                                string hashAlgorithm,
                                string saltValue,
                                int passwordIterations)
        {
            // Save min salt length; set it to default if invalid value is passed.
            if (minSaltLen < MIN_ALLOWED_SALT_LEN)
            {
                this.minSaltLen = DEFAULT_MIN_SALT_LEN;
            }
            else
            {
                this.minSaltLen = minSaltLen;
            }

            // Save max salt length; set it to default if invalid value is passed.
            if (maxSaltLen < 0 || maxSaltLen > MAX_ALLOWED_SALT_LEN)
            {
                this.maxSaltLen = DEFAULT_MAX_SALT_LEN;
            }
            else
            {
                this.maxSaltLen = maxSaltLen;
            }

            // Set the size of cryptographic key.
            if (keySize <= 0)
            {
                keySize = DEFAULT_KEY_SIZE;
            }

            // Set the name of algorithm. Make sure it is in UPPER CASE and does
            // not use dashes, e.g. change "sha-1" to "SHA1".
            if (hashAlgorithm == null)
            {
                hashAlgorithm = DEFAULT_HASH_ALGORITHM;
            }
            else
            {
                hashAlgorithm = hashAlgorithm.ToUpper().Replace("-", "");
            }

            // Initialization vector converted to a byte array.
            byte[] initVectorBytes = null;

            // Salt used for password hashing (to generate the key, not during
            // encryption) converted to a byte array.
            byte[] saltValueBytes = null;

            // Get bytes of initialization vector.
            if (initVector == null)
            {
                initVectorBytes = new byte[0];
            }
            else
            {
                initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            }

            // Get bytes of salt (used in hashing).
            if (saltValue == null)
            {
                saltValueBytes = new byte[0];
            }
            else
            {
                saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
            }

            // Generate password, which will be used to derive the key.
            PasswordDeriveBytes password = new PasswordDeriveBytes(
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations);

            // Convert key to a byte array adjusting the size from bits to bytes.
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Initialize Rijndael key object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // If we do not have initialization vector, we cannot use the CBC mode.
            // The only alternative is the ECB mode (which is not as good).
            if (initVectorBytes.Length == 0)
            {
                symmetricKey.Mode = CipherMode.ECB;
            }
            else
            {
                symmetricKey.Mode = CipherMode.CBC;
            }

            // Create encryptor and decryptor, which we will use for cryptographic
            // operations.
            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        }
Esempio n. 46
0
        public WebProductKeyInfo ValidateWebProductKey(string productKey)
        {
            if (string.IsNullOrEmpty(productKey))
            {
                throw new ArgumentNullException("Product Key is null or empty.");
            }

            byte[] keyBytes;
            try
            {
                keyBytes = Convert.FromBase64String(productKey);
            }
            catch (FormatException e)
            {
                throw new InvalidProductKeyException("Product key is invalid.", e);
            }

            if (keyBytes.Length != 82)
            {
                throw new InvalidProductKeyException("Product key is invalid.");
            }

            byte[] signBytes   = new byte[2];
            byte[] hiddenBytes = new byte[80];
            using (MemoryStream stream = new MemoryStream(keyBytes))
            {
                stream.Read(hiddenBytes, 0, 8);
                stream.Read(signBytes, 0, 2);
                stream.Read(hiddenBytes, 8, hiddenBytes.Length - 8);
                keyBytes = stream.ToArray();
            }

            byte[] sign = _cryptoService.SignData(signBytes, new SHA1CryptoServiceProvider());
            byte[] rkey = new byte[32];
            byte[] rjiv = new byte[16];
            Array.Copy(sign, rkey, 32);
            Array.Copy(sign, 32, rjiv, 0, 16);

            SymmetricAlgorithm algorithm = new RijndaelManaged();

            byte[] hiddenData;
            try
            {
                hiddenData = algorithm.CreateDecryptor(rkey, rjiv).TransformFinalBlock(hiddenBytes, 0, hiddenBytes.Length);
            }
            catch (Exception ex)
            {
                throw new InvalidProductKeyException("Product key is invalid.", ex);
            }

            byte[] proid          = new byte[2];
            byte[] pinfo          = new byte[2];
            byte[] xinfo          = new byte[2];
            byte[] ticks          = new byte[8];
            byte[] usernameBytes  = new byte[20];
            byte[] companyBytes   = new byte[20];
            byte[] userEmailBytes = new byte[20];

            using (MemoryStream memStream = new MemoryStream(hiddenData))
            {
                memStream.Read(proid, 0, 2);
                memStream.Read(pinfo, 0, 2);
                memStream.Read(xinfo, 0, 2);
                memStream.Read(ticks, 0, 8);
                memStream.Read(usernameBytes, 0, 20);
                memStream.Read(companyBytes, 0, 20);
                memStream.Read(userEmailBytes, 0, 20);
            }

            if (signBytes[0] == proid[0] && signBytes[1] == proid[1])
            {
                DateTime generatedDate = new DateTime(BitConverter.ToInt64(ticks, 0));
                if (generatedDate.Year > 2000 && generatedDate.Year < 2100)
                {
                    return(new WebProductKeyInfo()
                    {
                        ProductID = BitConverter.ToInt16(proid, 0),
                        TrialDays = BitConverter.ToInt16(pinfo, 0),
                        NumberOfUsers = BitConverter.ToInt16(xinfo, 0),
                        GeneratedDate = generatedDate,

                        UsernameHash = Encoding.ASCII.GetString(usernameBytes),
                        CompanyHash = Encoding.ASCII.GetString(companyBytes),
                        UserEmailHash = Encoding.ASCII.GetString(userEmailBytes),
                    });
                }
                else
                {
                    throw new InvalidProductKeyException("Product key date is incorrect.");
                }
            }
            else
            {
                throw new InvalidProductKeyException("Product key info is incorrect.");
            }
        }
Esempio n. 47
0
        private void DecryptFile(string inFile)
        {
            RijndaelManaged rjndl = new RijndaelManaged();

            rjndl.KeySize   = 256;
            rjndl.BlockSize = 256;
            rjndl.Mode      = CipherMode.CBC;

            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

            using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
            {
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Seek(0, SeekOrigin.Begin);
                inFs.Read(LenK, 0, 3);
                inFs.Seek(4, SeekOrigin.Begin);
                inFs.Read(LenIV, 0, 3);

                int lenK  = BitConverter.ToInt32(LenK, 0);
                int lenIV = BitConverter.ToInt32(LenIV, 0);

                int startC = lenK + lenIV + 8;
                int lenC   = (int)inFs.Length - startC;

                byte[] KeyEncrypted = new byte[lenK];
                byte[] IV           = new byte[lenIV];

                inFs.Seek(8, SeekOrigin.Begin);
                inFs.Read(KeyEncrypted, 0, lenK);
                inFs.Seek(8 + lenK, SeekOrigin.Begin);
                inFs.Read(IV, 0, lenIV);

                var private_key = (RSAParameters)Session["private_key"];
                myRSA.ImportParameters(private_key);

                byte[] KeyDecrypted = myRSA.Decrypt(KeyEncrypted, false);

                ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);

                using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                {
                    int count  = 0;
                    int offset = 0;

                    int    blockSizeBytes = rjndl.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];

                    inFs.Seek(startC, SeekOrigin.Begin);
                    using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamDecrypted.Write(data, 0, count);
                        }while (count > 0);

                        outStreamDecrypted.FlushFinalBlock();
                        outStreamDecrypted.Close();
                    }
                    outFs.Close();
                }
                inFs.Close();
            }
        }
Esempio n. 48
0
        /// <summary>
        ///     Decrypt the given string.  Assumes the string was encrypted using
        ///     EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public static string DecryptStringAES(string cipherText)
        {
            try
            {
                if (string.IsNullOrEmpty(cipherText))
                {
                    throw new ArgumentNullException("cipherText");
                }
                if (string.IsNullOrEmpty(SharedSecret))
                {
                    throw new ArgumentNullException("sharedSecret");
                }

                // Declare the RijndaelManaged object
                // used to decrypt the data.
                RijndaelManaged aesAlg = null;

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

                try
                {
                    // generate the key from the shared secret and the salt
                    var key = new Rfc2898DeriveBytes(SharedSecret, Salt);

                    // Create the streams used for decryption.
                    byte[] bytes = Convert.FromBase64String(cipherText);
                    using (var msDecrypt = new MemoryStream(bytes))
                    {
                        // Create a RijndaelManaged object
                        // with the specified key and IV.
                        aesAlg     = new RijndaelManaged();
                        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                        // Get the initialization vector from the encrypted stream
                        aesAlg.IV = ReadByteArray(msDecrypt);
                        // Create a decrytor to perform the stream transform.
                        ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                        using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new StreamReader(csDecrypt))

                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
                finally
                {
                    // Clear the RijndaelManaged object.
                    if (aesAlg != null)
                    {
                        aesAlg.Clear();
                    }
                }

                return(plaintext);
            }
            catch (Exception ex)
            {
                ex.ToExceptionless().Submit();
            }
            return(null);
        }
Esempio n. 49
0
        protected override string EncryptOrDecrypt(bool type, string plainStr)
        {
            {
#if (SILVERLIGHT || WINDOWS_PHONE)
                AesManaged aesEncryption = new AesManaged();
                aesEncryption.KeySize   = 256;
                aesEncryption.BlockSize = 128;
                //get ASCII bytes of the string
                aesEncryption.IV  = System.Text.Encoding.UTF8.GetBytes("0123456789012345");
                aesEncryption.Key = System.Text.Encoding.UTF8.GetBytes(GetEncryptionKey());
#else
                RijndaelManaged aesEncryption = new RijndaelManaged();
                aesEncryption.KeySize   = 256;
                aesEncryption.BlockSize = 128;
                //Mode CBC
                aesEncryption.Mode = CipherMode.CBC;
                //padding
                aesEncryption.Padding = PaddingMode.PKCS7;
                //get ASCII bytes of the string
                aesEncryption.IV  = System.Text.Encoding.ASCII.GetBytes("0123456789012345");
                aesEncryption.Key = System.Text.Encoding.ASCII.GetBytes(GetEncryptionKey());
#endif

                if (type)
                {
                    ICryptoTransform crypto = aesEncryption.CreateEncryptor();
                    plainStr = EncodeNonAsciiCharacters(plainStr);
#if (SILVERLIGHT || WINDOWS_PHONE)
                    byte[] plainText = Encoding.UTF8.GetBytes(plainStr);
#else
                    byte[] plainText = Encoding.ASCII.GetBytes(plainStr);
#endif

                    //encrypt
                    byte[] cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);
                    return(Convert.ToBase64String(cipherText));
                }
                else
                {
                    try
                    {
                        ICryptoTransform decrypto = aesEncryption.CreateDecryptor();
                        //decode
                        byte[] decryptedBytes = Convert.FromBase64CharArray(plainStr.ToCharArray(), 0, plainStr.Length);

                        //decrypt
#if (SILVERLIGHT || WINDOWS_PHONE)
                        var    data      = decrypto.TransformFinalBlock(decryptedBytes, 0, decryptedBytes.Length);
                        string decrypted = Encoding.UTF8.GetString(data, 0, data.Length);
#else
                        string decrypted = System.Text.Encoding.ASCII.GetString(decrypto.TransformFinalBlock(decryptedBytes, 0, decryptedBytes.Length));
#endif

                        return(decrypted);
                    }
                    catch (Exception ex)
                    {
                        LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose);
                        throw ex;
                        //LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose);
                        //return "**DECRYPT ERROR**";
                    }
                }
            }
        }
Esempio n. 50
0
        private void LoadHeaders()
        {
            ImageData imageData = xexData;

            xexData.header = rdr.ReadStruct <XexHeader>();

            XexHeader header = xexData.header;

            switch (header.magic)
            {
            case XEX2_MAGIC:
            case XEX1_MAGIC:
                break;

            default:
                throw new BadImageFormatException("Invalid XEX Magic");
            }

            for (uint i = 0; i < header.header_count; i++)
            {
                bool add = true;
                XexOptionalHeader st_optionalHeader = rdr.ReadStruct <XexOptionalHeader>();
                OptionalHeader    optionalHeader    = new OptionalHeader(st_optionalHeader);

                switch ((byte)optionalHeader.key)
                {
                // just the data
                case 0x00:
                case 0x01:
                    optionalHeader.value  = optionalHeader.offset;
                    optionalHeader.offset = 0;
                    break;

                case 0xFF:
                    optionalHeader.length = rdr.ReadAt <UInt32>(optionalHeader.offset, (r) =>
                    {
                        return(r.ReadUInt32());
                    });
                    optionalHeader.offset += 4;

                    if (optionalHeader.length + optionalHeader.offset > rdr.Bytes.Length)
                    {
                        decompilerEventListener.Warn(
                            new NullCodeLocation(""),
                            $"Optional header {i} (0x{optionalHeader.key:X}) crosses file boundary. Will not be read"
                            );
                        add = false;
                    }
                    break;

                default:
                    optionalHeader.length = ((uint)(byte)optionalHeader.key) * 4;

                    if (optionalHeader.length + optionalHeader.offset > rdr.Bytes.Length)
                    {
                        decompilerEventListener.Warn(
                            new NullCodeLocation(""),
                            $"Optional header {i} (0x{optionalHeader.key:X}) crosses file boundary. Will not be read"
                            );
                        add = false;
                    }
                    break;
                }

                if (add)
                {
                    optional_headers.Add(optionalHeader);
                }
            }

            for (int i = 0; i < optional_headers.Count; i++)
            {
                OptionalHeader opt = optional_headers[i];

                // go to the header offset
                if (opt.length > 0 && opt.offset != 0)
                {
                    rdr.Offset = opt.offset;
                }

                // process the optional headers
                switch (opt.key)
                {
                case XEXHeaderKeys.XEX_HEADER_SYSTEM_FLAGS:
                    imageData.system_flags = (XEXSystemFlags)opt.value;
                    break;

                case XEXHeaderKeys.XEX_HEADER_RESOURCE_INFO:
                    uint count = (opt.length - 4) / 16;
                    xexData.resources = new List <XexResourceInfo>((int)count);

                    for (uint n = 0; n < count; n++)
                    {
                        xexData.resources.Insert(i, rdr.ReadStruct <XexResourceInfo>());
                    }
                    break;

                case XEXHeaderKeys.XEX_HEADER_EXECUTION_INFO:
                    imageData.execution_info = rdr.ReadStruct <XexExecutionInfo>();
                    break;

                case XEXHeaderKeys.XEX_HEADER_GAME_RATINGS:
                    break;

                case XEXHeaderKeys.XEX_HEADER_TLS_INFO:
                    imageData.tls_info = rdr.ReadStruct <XexTlsInfo>();
                    break;

                case XEXHeaderKeys.XEX_HEADER_IMAGE_BASE_ADDRESS:
                    imageData.exe_address = opt.value;
                    break;

                case XEXHeaderKeys.XEX_HEADER_ENTRY_POINT:
                    imageData.exe_entry_point = opt.value;
                    break;

                case XEXHeaderKeys.XEX_HEADER_DEFAULT_STACK_SIZE:
                    imageData.exe_stack_size = opt.value;
                    break;

                case XEXHeaderKeys.XEX_HEADER_DEFAULT_HEAP_SIZE:
                    imageData.exe_heap_size = opt.value;
                    break;

                case XEXHeaderKeys.XEX_HEADER_FILE_FORMAT_INFO:
                    XexEncryptionHeader encHeader = rdr.ReadStruct <XexEncryptionHeader>();

                    imageData.file_format_info.encryption_type  = encHeader.encryption_type;
                    imageData.file_format_info.compression_type = encHeader.compression_type;

                    switch (encHeader.compression_type)
                    {
                    case XEXCompressionType.XEX_COMPRESSION_NONE:
                        break;

                    case XEXCompressionType.XEX_COMPRESSION_DELTA:
                        throw new NotImplementedException("XEX: image::Binary is using unsupported delta compression");

                    case XEXCompressionType.XEX_COMPRESSION_BASIC:
                        uint block_count = (opt.length - 8) / 8;
                        imageData.file_format_info.basic_blocks = new List <XexFileBasicCompressionBlock>((int)block_count);

                        for (int ib = 0; ib < block_count; ib++)
                        {
                            imageData.file_format_info.basic_blocks.Insert(ib, rdr.ReadStruct <XexFileBasicCompressionBlock>());
                        }
                        break;

                    case XEXCompressionType.XEX_COMPRESSION_NORMAL:
                        imageData.file_format_info.normal = rdr.ReadStruct <XexFileNormalCompressionInfo>();
                        break;
                    }

                    if (encHeader.encryption_type != XEXEncryptionType.XEX_ENCRYPTION_NONE)
                    {
                        //
                    }
                    break;

                case XEXHeaderKeys.XEX_HEADER_IMPORT_LIBRARIES:
                    XexImportLibraryBlockHeader blockHeader = rdr.ReadStruct <XexImportLibraryBlockHeader>();

                    long string_table = rdr.Offset;
                    for (int j = 0; j < blockHeader.count; j++)
                    {
                        string name = rdr.ReadCString(PrimitiveType.Char, Encoding.ASCII).ToString();
                        imageData.libNames.Add(name);
                    }
                    rdr.Offset = string_table + blockHeader.string_table_size;

                    for (int m = 0; m < blockHeader.count; m++)
                    {
                        XexImportLibaryHeader imp_header = rdr.ReadStruct <XexImportLibaryHeader>();

                        string name       = null;
                        int    name_index = (byte)imp_header.name_index;
                        if (name_index < blockHeader.count)
                        {
                            name = imageData.libNames[name_index];
                        }

                        for (uint ri = 0; ri < imp_header.record_count; ++ri)
                        {
                            UInt32 recordEntry = rdr.ReadUInt32();
                            xexData.import_records.Add(recordEntry);
                        }
                    }
                    break;
                }
            }

            // load the loader info
            {
                rdr.Offset = header.security_offset;

                switch (header.magic)
                {
                case XEX1_MAGIC:
                    Xex1LoaderInfo info1 = rdr.ReadStruct <Xex1LoaderInfo>();
                    xexData.loader_info.aes_key = info1.aes_key;
                    break;

                case XEX2_MAGIC:
                    Xex2LoaderInfo info2 = rdr.ReadStruct <Xex2LoaderInfo>();
                    xexData.loader_info.aes_key = info2.aes_key;
                    break;
                }
            }

            // load the sections
            {
                rdr.Offset = header.security_offset + 0x180;

                UInt32 sectionCount = rdr.ReadUInt32();
                xexData.sections = new List <XexSection>((int)sectionCount);

                for (int si = 0; si < sectionCount; si++)
                {
                    xexData.sections.Insert(0, rdr.ReadStruct <XexSection>());
                }
            }

            // decrypt the XEX key
            {
                byte[] keyToUse = xe_xex2_devkit_key;
                if (header.magic != XEX1_MAGIC && xexData.execution_info.title_id != 0)
                {
                    keyToUse = xe_xex2_retail_key;
                }

                Rijndael aes = new RijndaelManaged()
                {
                    BlockSize = 128,
                    KeySize   = 128,
                    Mode      = CipherMode.ECB,
                    Key       = keyToUse,
                    Padding   = PaddingMode.None
                };

                xexData.session_key = aes
                                      .CreateDecryptor()
                                      .TransformFinalBlock(xexData.loader_info.aes_key, 0, 16);
                decompilerEventListener.Info(
                    new NullCodeLocation(""),
                    "XEX Session key: " + BitConverter.ToString(xexData.session_key).Replace("-", "")
                    );
            }
        }
Esempio n. 51
0
        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="cipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except cipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        public static string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
        {
            // Convert strings defining encryption key characteristics 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 ciphertext into a byte array.
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            // First, we must create a password, from which the key will be
            // derived. This password will be generated from the specified
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            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 decryptor from the existing key bytes and initialization
            // vector. Key size will be defined based on the number of the key
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                keyBytes,
                initVectorBytes);

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

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

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

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

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

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

            // Return decrypted string.
            return(plainText);
        }
Esempio n. 52
0
        public static string Decrypt(string ciphertextBase64, string password)
        {
            if (string.IsNullOrWhiteSpace(ciphertextBase64) || string.IsNullOrEmpty(password))
            {
                return(ciphertextBase64);
            }

            try
            {
                string plaintext;

                using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
                {
                    using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                    {
                        byte[] key = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
                        rijndaelManaged.Key = key;
                    }

                    byte[] ciphertext = Convert.FromBase64String(ciphertextBase64);

                    using (MemoryStream memoryStream = new MemoryStream(ciphertext))
                    {
                        const int ivLength = 16;
                        byte[]    iv       = new byte[ivLength];
                        memoryStream.Read(iv, 0, ivLength);
                        rijndaelManaged.IV = iv;

                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            using (StreamReader streamReader = new StreamReader(cryptoStream, Encoding.UTF8, true))
                            {
                                plaintext = streamReader.ReadToEnd();
                            }
                            rijndaelManaged.Clear();
                        }
                        // cryptoStream
                    }
                    // memoryStream
                }
                // rijndaelManaged

                return(plaintext);
            }
            catch (Exception ex)
            {
                // Ignore CryptographicException "Padding is invalid and cannot be removed." when password is incorrect.
                if (!(ex is CryptographicException))
                {
                    Runtime.MessageCollector.AddMessage(Messages.MessageClass.ErrorMsg, string.Format(global::My.Language.strErrorDecryptionFailed, ex.Message));
                }
            }

            return(ciphertextBase64);
        }
Esempio n. 53
0
        public static string Desencriptar(string cadena)
        {
            // Convierto la cadena y la clave en arreglos de bytes
            // para poder usarlas en las funciones de encriptacion
            // En este caso la cadena la convierta usando base 64
            // que es la codificacion usada en el metodo encriptar
            byte[] cadenaBytes = Convert.FromBase64String(cadena);
            byte[] claveBytes  = Encoding.UTF8.GetBytes(ClaveSecreta);


            // Creo un objeto de la clase Rijndael
            RijndaelManaged rij = new RijndaelManaged();


            // Configuro para que utilice el modo ECB
            rij.Mode = CipherMode.ECB;


            // Configuro para que use encriptacion de 256 bits.
            rij.BlockSize = 256;


            // Declaro que si necesitara mas bytes agregue ceros.
            rij.Padding = PaddingMode.Zeros;


            // Declaro un desencriptador que use mi clave secreta y un vector
            // de inicializacion aleatorio
            ICryptoTransform desencriptador;

            desencriptador = rij.CreateDecryptor(claveBytes, rij.IV);


            // Declaro un stream de memoria para que guarde los datos
            // encriptados
            MemoryStream memStream = new MemoryStream(cadenaBytes);


            // Declaro un stream de cifrado para que pueda leer de aqui
            // la cadena a desencriptar. Esta clase utiliza el desencriptador
            // y el stream de memoria para realizar la desencriptacion
            CryptoStream cifradoStream;

            cifradoStream = new CryptoStream(memStream, desencriptador, CryptoStreamMode.Read);


            // Declaro un lector para que lea desde el stream de cifrado.
            // A medida que vaya leyendo se ira desencriptando.
            StreamReader lectorStream = new StreamReader(cifradoStream);


            // Leo todos los bytes y lo almaceno en una cadena
            string resultado = lectorStream.ReadToEnd();


            // Cierro los dos streams creados
            memStream.Close();
            cifradoStream.Close();


            // Devuelvo la cadena
            return(resultado);
        }