Example #1
2
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Plain, Byte[] Cipher)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        cs.FlushFinalBlock();
        CipherCalculated = ms.ToArray();
        cs.Close();

		Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
Example #2
0
 public static string Decrypt(string stringToDecrypt)
 {
     string sEncryptionKey = "thuynnxkey";
     byte[] key = { };
     byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
     byte[] inputByteArray = new byte[stringToDecrypt.Length];
     try
     {
         key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
         DESCryptoServiceProvider des = new DESCryptoServiceProvider();
         inputByteArray = Convert.FromBase64String(stringToDecrypt);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
         cs.Write(inputByteArray, 0, inputByteArray.Length);
         cs.FlushFinalBlock();
         cs.Close();
         Encoding encoding = Encoding.UTF8;
         return encoding.GetString(ms.ToArray());
     }
     catch (System.Exception ex)
     {
         SiAuto.Main.LogString("Lỗi :", ex.ToString());
         return (string.Empty);
     }
 }
    //This method is to decrypt the password given by user.
    public static string Decrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+"));
        if (rawData.Length < 8)
            throw new ArgumentException("Invalid input data");

        // setup the decryption algorithm
        byte[] salt = new byte[8];
        for (int i = 0; i < salt.Length; i++)
            salt[i] = rawData[i];

        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);
        // decrypt the data
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cryptoStream.Write(rawData, 8, rawData.Length - 8);
            cryptoStream.Close();

            byte[] decrypted = memoryStream.ToArray();
            return Encoding.Unicode.GetString(decrypted);
        }
    }
Example #4
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;
    }
Example #5
0
File: test.cs Project: mono/gert
	static int Main ()
	{
		string filename = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"encrypt.tmp");
		string data = "this is sensitive data";

		DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
		des.GenerateIV ();
		des.GenerateKey ();

		// -----------  WRITING ENCRYPTED SERIALIZED DATA ------------------
		Stream stream = new FileStream (filename, FileMode.Create, FileAccess.Write);
		stream = new CryptoStream (stream, des.CreateEncryptor (), CryptoStreamMode.Write);
		BinaryFormatter bformatter = new BinaryFormatter ();
		bformatter.Serialize (stream, data);
		stream.Close ();

		stream = null;
		bformatter = null;
		data = string.Empty;

		// -----------  READING ENCRYPTED SERIALIZED DATA ------------------
		stream = new FileStream (filename, FileMode.Open, FileAccess.Read);
		stream = new CryptoStream (stream, des.CreateDecryptor (), CryptoStreamMode.Read);
		bformatter = new BinaryFormatter ();
		data = (string) bformatter.Deserialize (stream);
		stream.Close ();

		//----------- CHECK RESULTS ----------------
		if (data != "this is sensitive data")
			return 1;

		return 0;
	}
Example #6
0
    public static byte[] Encrypt(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.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }

            }
            return result;
    }
    //This method is to encrypt the password given by user.
    public static string Encrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        // setup the encryption algorithm
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);

        // encrypt the data
        byte[] rawData = Encoding.Unicode.GetBytes(data);
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write))
        {
            memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
            cryptoStream.Write(rawData, 0, rawData.Length);
            cryptoStream.Close();

            byte[] encrypted = memoryStream.ToArray();
            return Convert.ToBase64String(encrypted);
        }
    }
Example #8
0
    public static Boolean Test() {
    	String Text = "This is some test text";
    	
    	Console.WriteLine("Original text : "  + Text);
    	
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, new ToBase64Transform(), CryptoStreamMode.Write);
		cs.Write(Encoding.ASCII.GetBytes(Text), 0, Text.Length);
		cs.Close();
		
    	Console.WriteLine("Encoded : " + Encoding.ASCII.GetString(ms.ToArray()));

        MemoryStream ms1 = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write);
		cs1.Write(ms.ToArray(), 0, (int)ms.ToArray().Length);
		cs1.Close();
    		
    	Console.WriteLine("Decoded : " + Encoding.ASCII.GetString(ms1.ToArray()));

    	String mod = Encoding.ASCII.GetString((Byte[])ms.ToArray().Clone());
    	mod = mod.Insert(17, "\n").Insert(4, "  ").Insert(8,"\t");
    	Byte[] modified = Encoding.ASCII.GetBytes(mod);
    	
        MemoryStream ms2 = new MemoryStream();
        CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write);
		cs2.Write(modified, 0, (int)modified.Length);
		cs2.Close();

    	Console.WriteLine("Decoded (with whitespaces) : " + Encoding.ASCII.GetString(ms2.ToArray()));
    	
    	if (!Compare(ms1.ToArray(), ms2.ToArray())) return false;
 
        return true;
    }
 /// <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";
         }
 }
	private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
	 {
	     //Create the file streams to handle the input and output files.
	     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
	     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
	     fout.SetLength(0);

	     //Create variables to help with read and write.
	     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
	     long rdlen = 0;              //This is the total number of bytes written.
	     long totlen = fin.Length;    //This is the total length of the input file.
	     int len;                     //This is the number of bytes to be written at a time.

	     SymmetricAlgorithm des = new DESCryptoServiceProvider();
         des.Padding = PaddingMode.PKCS7;
	     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

	     Console.WriteLine("Encrypting...");

	     //Read from the input file, then encrypt and write to the output file.
	     while(rdlen < totlen)
	     {
	         len = fin.Read(bin, 0, 100);
	         encStream.Write(bin, 0, len);
	         rdlen = rdlen + len;
             Console.WriteLine("{0} bytes processed", rdlen);
         }
	     encStream.Close();
    }
Example #11
0
	public static string DecryptString(string input, string cryptographicProvider_PublicKey, string cryptographicProvider_IV)
	{
		try
		{
			input = input.Replace(CryptographicProviderKey, String.Empty);

			using (var dataString = new MemoryStream())
			{
				var service = new TripleDESCryptoServiceProvider().CreateDecryptor(Encoding.UTF8.GetBytes(cryptographicProvider_PublicKey),
				 Encoding.UTF8.GetBytes(cryptographicProvider_IV));
				using (var cryptoStream = new CryptoStream(dataString, service, CryptoStreamMode.Write))
				{
					var inputData = Convert.FromBase64String(input);
					cryptoStream.Write(inputData, 0, inputData.Length);
					cryptoStream.FlushFinalBlock();

					var dataResult = dataString.ToArray();
					var resultString = Encoding.UTF8.GetString(Convert.FromBase64String(Convert.ToBase64String(dataResult)));
					cryptoStream.Close();

					return resultString;

				}
			}

		}
		catch (Exception e)
		{
			return e.ToString();
		}

	}
Example #12
0
    private string DeCryption(string content, string sKey, string sIV)
    {
        try
        {
            byte[] inputByteArray = Convert.FromBase64String(content);
            using (DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider())
            {
                //byte[] inputByteArray = Convert.FromBase64String(content);
                desProvider.Key = System.Text.Encoding.ASCII.GetBytes(sKey);
                desProvider.IV = System.Text.Encoding.ASCII.GetBytes(sIV);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms,desProvider.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    //cs.Clear();
                    cs.Write(inputByteArray,0,inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                string str = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        catch
        {
            return "String Not Base64 Encode!!!";
        }
    }
 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);
     }
 }
Example #14
0
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = 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.CreateEncryptor(), CryptoStreamMode.Write))
        {
          cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
          cs.Close();
        }
        encryptedBytes = ms.ToArray();
          }
        }

        return encryptedBytes;
        //end public byte[] AES_Encrypt
    }
Example #15
0
    // Decrypt a byte array into a byte array using a key and an IV
    public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
    {
        // Create a MemoryStream that is going to accept the decrypted bytes

        MemoryStream ms = new MemoryStream();

        // Create a symmetric algorithm.

        // We are going to use Rijndael because it is strong and available on all platforms.

        // You can use other algorithms, to do so substitute the next line with something like

        //                      TripleDES alg = TripleDES.Create();

        Rijndael alg = Rijndael.Create();

        // Now set the key and the IV.

        // We need the IV (Initialization Vector) because the algorithm is operating in its default

        // mode called CBC (Cipher Block Chaining). The IV is XORed with the first block (8 byte)

        // of the data after it is decrypted, and then each decrypted block is XORed with the previous

        // cipher block. This is done to make encryption more secure.

        // There is also a mode called ECB which does not need an IV, but it is much less secure.

        alg.Key = Key;

        alg.IV = IV;

        // Create a CryptoStream through which we are going to be pumping our data.

        // CryptoStreamMode.Write means that we are going to be writing data to the stream

        // and the output will be written in the MemoryStream we have provided.

        CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);

        // Write the data and make it do the decryption

        cs.Write(cipherData, 0, cipherData.Length);

        // Close the crypto stream (or do FlushFinalBlock).

        // This will tell it that we have done our decryption and there is no more data coming in,

        // and it is now a good time to remove the padding and finalize the decryption process.

        cs.Close();

        // Now get the decrypted data from the MemoryStream.

        // Some people make a mistake of using GetBuffer() here, which is not the right way.

        byte[] decryptedData = ms.ToArray();

        return decryptedData;
    }
    public static void Main() {
        string PlainText = "Titan";
        byte[] PlainBytes = new byte[5];
        PlainBytes = Encoding.ASCII.GetBytes(PlainText.ToCharArray());
        PrintByteArray(PlainBytes);
        byte[] CipherBytes = new byte[8];
        PasswordDeriveBytes pdb = new PasswordDeriveBytes("Titan", null);
        byte[] IV = new byte[8];
        byte[] Key = pdb.CryptDeriveKey("RC2", "SHA1", 40, IV);
        PrintByteArray(Key);
        PrintByteArray(IV);

        // Now use the data to encrypt something
        RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
        Console.WriteLine(rc2.Padding);
        Console.WriteLine(rc2.Mode);
        ICryptoTransform sse = rc2.CreateEncryptor(Key, IV);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs1 = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs1.Write(PlainBytes, 0, PlainBytes.Length);
        cs1.FlushFinalBlock();
        CipherBytes = ms.ToArray();
        cs1.Close();
        Console.WriteLine(Encoding.ASCII.GetString(CipherBytes));
        PrintByteArray(CipherBytes);

        ICryptoTransform ssd = rc2.CreateDecryptor(Key, IV);
        CryptoStream cs2 = new CryptoStream(new MemoryStream(CipherBytes), ssd, CryptoStreamMode.Read);
        byte[] InitialText = new byte[5];
        cs2.Read(InitialText, 0, 5);
        Console.WriteLine(Encoding.ASCII.GetString(InitialText));
    	PrintByteArray(InitialText);
    }
Example #17
0
        public static string Encode(this string str)
        {
            var          key = Encoding.ASCII.GetBytes("leaf");
            var          iv  = Encoding.ASCII.GetBytes("1234");
            MemoryStream ms  = null;
            CryptoStream cs  = null;
            StreamWriter sw  = null;

            var des = new DESCryptoServiceProvider();

            try
            {
                ms = new MemoryStream();
                cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                sw = new StreamWriter(cs);
                sw.Write(str);
                sw.Flush();
                cs.FlushFinalBlock();
                return(Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length));
            }
            finally
            {
                sw?.Close();
                cs?.Close();
                ms?.Close();
            }
        }
Example #18
0
	public static SaveData Load()
	{
		if (!File.Exists("save01.sav"))
			return null;
			
		SaveData data = null;
		using(Stream stream = File.Open("save01.sav", FileMode.Open)) {
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			binaryFormatter.Binder = new VersionDeserializationBinder(); 
			
			byte[] byKey = Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
			using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) {
				using (Stream cryptoStream = new CryptoStream(stream, des.CreateDecryptor(byKey, dv), CryptoStreamMode.Read))
				{
					Log.debug("Save", "Loading...");
					try {
						data = (SaveData) binaryFormatter.Deserialize(cryptoStream);
					} catch (Exception e) {
						Log.debug("Save", ""+e);
						return new SaveData();
					}
					Log.debug("Save", "Loaded (level={0})", data.level);
					cryptoStream.Close();
				}
			}
			stream.Close();
		}
		return data;
	}
Example #19
0
    /// <summary>
    /// Encrypt string using AES 128
    /// </summary>
    /// <param name="plaintext"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keybytes = Encoding.UTF8.GetBytes(key);

        RijndaelManaged aes = new RijndaelManaged();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.None;
        byte[] IVbytes = Encoding.ASCII.GetBytes("dongbinhuiasxiny");

        ICryptoTransform encryptor = aes.CreateEncryptor(keybytes, IVbytes);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

        byte[] plainBytes = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(plaintext)));

        cs.Write(plainBytes, 0, plainBytes.Length);

        cs.FlushFinalBlock();

        byte[] cipherBytes = ms.ToArray();

        ms.Close();
        cs.Close();

        return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
    }
Example #20
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
    }
Example #21
0
        public string Decrypt(string encryptedInput)
        {
            MemoryStream decryptCache = null;

            try
            {
                ICryptoTransform decryptor =
                    this._Aes.CreateDecryptor();

                decryptCache =
                    new MemoryStream();
                for (int i = 0; i < encryptedInput.Length; i += 2)
                {
                    string hex =
                        encryptedInput.Substring(i, 2);
                    decryptCache.WriteByte(
                        byte.Parse(hex, System.Globalization.NumberStyles.HexNumber));
                }
                decryptCache.Seek(0, SeekOrigin.Begin);

                CryptoStream decryptStream = null;
                try
                {
                    StringBuilder decrypted =
                        new StringBuilder();

                    decryptStream =
                        new CryptoStream(decryptCache, decryptor, CryptoStreamMode.Read);

                    byte[] buffer = new byte[2048];
                    int    rC;
                    do
                    {
                        rC = decryptStream.Read(buffer, 0, buffer.Length);

                        if (rC > 0)
                        {
                            decrypted.Append(Encoding.UTF8.GetString(buffer, 0, rC));
                        }
                    } while (rC > 0);

                    return(decrypted.ToString());
                }
                catch
                {
                    return(string.Empty);
                }
                finally
                {
                    decryptStream?.Close();
                }
            }
            finally
            {
                decryptCache?.Close();
            }
        }
Example #22
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;
    }
Example #23
0
 public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
 {
     MemoryStream ms = new MemoryStream();
     Rijndael alg = Rijndael.Create();
     alg.Key = Key;
     alg.IV = IV;
     CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
     cs.Write(cipherData, 0, (int)cipherData.Length);
     cs.Close();
     return ms.ToArray();
 }
Example #24
0
    public string DecryptString(string Value)
    {
        ICryptoTransform ct = mCSP.CreateDecryptor();

        byte[] byt = Convert.FromBase64String(Value);

        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
        cs.Write(byt, 0, byt.Length);
        cs.FlushFinalBlock();
        cs.Close();
        return Encoding.UTF8.GetString(ms.ToArray());
    }
Example #25
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;
 }
    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;
    }
Example #27
0
    /**
     * str_in is in format of FF-FF-FF-FF, hex string with the dashes seperating each byte
     */
    public static string DecryptAES(string str_in)
    {
        MemoryStream msAES = new MemoryStream();
        CryptoStream csAES = new CryptoStream(msAES, GetDecryptor(), CryptoStreamMode.Write);
        byte[] bstr = HexStringToBytes(str_in);
        csAES.Write(bstr, 0, bstr.Length);
        csAES.FlushFinalBlock();
        byte[] decMsg = msAES.ToArray();

        msAES.Close();
        csAES.Close();

        return BytesToString(decMsg);
    }
    static Boolean Test()
    {

        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, 2};
        Byte[]  IV = {1, 1, 1, 1, 1, 1, 1, 1};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
        des.Mode = CipherMode.ECB;
//        des.FeedbackSize = 0;
		des.Padding = PaddingMode.None;

        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...");

//        DESCryptoServiceProvider     des = new DESCryptoServiceProvider();
//        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[8];
        cs.Read(NewPlainText,0,8);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
Example #29
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
        string clave = "1234567890123456";

        byte[] cadenaBytes = Convert.FromBase64String(cadena);
        byte[] claveBytes = Encoding.UTF8.GetBytes(clave);

        // Creo un objeto de la clase Rijndael
        AesManaged  rij = new AesManaged();
        rij.BlockSize = 128;
        byte[] vector = new byte [rij.BlockSize/8];
        for (int ni = 0; ni < vector.Length; ni++) vector[ni] = 0 ;
        // Configuro para que use encriptacion de 256 bits.

        // Declaro un desencriptador que use mi clave secreta y un vector
        // de inicializacion aleatorio
        ICryptoTransform desencriptador;
        desencriptador = rij.CreateDecryptor(claveBytes, vector);

        // 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

        // Leo todos los bytes y lo almaceno en una cadena
        string resultado="";
        try
        {
            CryptoStream cifradoStream = new CryptoStream(memStream, desencriptador, CryptoStreamMode.Read);
            StreamReader lectorStream = new StreamReader(cifradoStream);
            resultado = lectorStream.ReadToEnd();
             memStream.Close();
             cifradoStream.Close();
        }
        catch
        {
        }
        resultado=resultado.Trim('\0');
        // Cierro los dos streams creados

        // Devuelvo la cadena
        return resultado;
    }
Example #30
0
        public string Encrypt(string input)
        {
            MemoryStream encrypted = null;

            try
            {
                ICryptoTransform encryptor =
                    this._Aes.CreateEncryptor();

                encrypted = new MemoryStream();

                CryptoStream encryptStream = null;
                try
                {
                    byte[] inputBytes =
                        Encoding.UTF8.GetBytes(input);

                    encryptStream =
                        new CryptoStream(encrypted, encryptor, CryptoStreamMode.Write);
                    encryptStream.Write(inputBytes, 0, inputBytes.Length);
                    encryptStream.FlushFinalBlock();

                    // notify session to be persist
                    Basics.Helpers.Context.Session["_sys_crypto"] =
                        Guid.NewGuid().ToString();
                }
                finally
                {
                    encryptStream?.Close();
                }

                byte[] encryptedBytes =
                    encrypted.ToArray();

                StringBuilder encryptedString =
                    new StringBuilder();
                foreach (byte encryptedByte in encryptedBytes)
                {
                    encryptedString.Append(
                        encryptedByte.ToString("X2"));
                }

                return(encryptedString.ToString());
            }
            finally
            {
                encrypted?.Close();
            }
        }
Example #31
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());
    }
Example #32
0
 /// <summary>
 /// 加密字符串并返回加密后的结果
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public string EncryptString(string str)
 {
     byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
     byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);//得到加密密钥
     byte[] toEncrypt = this.EncodingMode.GetBytes(str);//得到要加密的内容
     byte[] encrypted;
     ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);
     MemoryStream msEncrypt = new MemoryStream();
     CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
     csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
     csEncrypt.FlushFinalBlock();
     encrypted = msEncrypt.ToArray();
     csEncrypt.Close();
     msEncrypt.Close();
     return this.EncodingMode.GetString(encrypted);
 }
 private byte[] ConvertToBytes(byte[] buffer, bool decryptedOrEncrypted)
 {
     if (this.Algorithm is SymmetricAlgorithm)
     {
         SymmetricAlgorithm algorithm    = this.Algorithm as SymmetricAlgorithm;
         ICryptoTransform   transform    = decryptedOrEncrypted ? algorithm.CreateDecryptor() : algorithm.CreateEncryptor();
         MemoryStream       memoryStream = new MemoryStream();
         CryptoStream       cryptoStream = new CryptoStream((Stream)memoryStream, transform, CryptoStreamMode.Write);
         try
         {
             cryptoStream.Write(buffer, 0, buffer.Length);
             cryptoStream.FlushFinalBlock();
             return(memoryStream.ToArray());
         }
         finally
         {
             cryptoStream?.Close();
             GC.Collect();
         }
     }
     else
     {
         if (!(this.Algorithm is CSymmetricAlgorithm))
         {
             return(buffer);
         }
         CSymmetricAlgorithm algorithm     = this.Algorithm as CSymmetricAlgorithm;
         MemoryStream        memoryStream1 = new MemoryStream(buffer);
         if (memoryStream1.CanSeek)
         {
             memoryStream1.Seek(0L, SeekOrigin.Begin);
         }
         MemoryStream memoryStream2 = new MemoryStream();
         if (decryptedOrEncrypted)
         {
             algorithm.Decrypt((Stream)memoryStream1, (Stream)memoryStream2, algorithm.Key);
         }
         else
         {
             algorithm.Encrypt((Stream)memoryStream1, (Stream)memoryStream2, algorithm.Key);
         }
         return(memoryStream2.ToArray());
     }
 }
Example #34
0
        public static string Decode(this string str)
        {
            var          key = Encoding.ASCII.GetBytes("leaf");
            var          iv  = Encoding.ASCII.GetBytes("1234");
            MemoryStream ms  = null;
            CryptoStream cs  = null;
            StreamReader sr  = null;

            var des = new DESCryptoServiceProvider();

            try
            {
                ms = new MemoryStream(Convert.FromBase64String(str));
                cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
                sr = new StreamReader(cs);
                return(sr.ReadToEnd());
            }
            finally
            {
                sr?.Close();
                cs?.Close();
                ms?.Close();
            }
        }
Example #35
0
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="inFile">待解密文件</param>
        /// <param name="outFile">解密后输出文件</param>
        /// <param name="password">解密密码</param>
        public static void DecryptFile(string inFile, string outFile, string password)
        {
            // 创建打开文件流
            using (FileStream fin = File.OpenRead(inFile),
                   fout = File.OpenWrite(outFile))
            {
                int    size     = (int)fin.Length;
                byte[] bytes    = new byte[BUFFER_SIZE];
                int    read     = -1;
                int    value    = 0;
                int    outValue = 0;

                byte[] IV = new byte[16];
                fin.Read(IV, 0, 16);
                byte[] salt = new byte[16];
                fin.Read(salt, 0, 16);

                SymmetricAlgorithm sma = DESFileClass.CreateRijndael(password, salt);
                sma.IV = IV;

                value = 32;
                long lSize = -1;

                // 创建散列对象, 校验文件
                HashAlgorithm hasher = SHA256.Create();

                using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
                       chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
                {
                    // 读取文件长度
                    BinaryReader br = new BinaryReader(cin);
                    lSize = br.ReadInt64();
                    ulong tag = br.ReadUInt64();

                    if (FC_TAG != tag)
                    {
                        throw new CryptoHelpException("文件被破坏");
                    }

                    long numReads = lSize / BUFFER_SIZE;

                    long slack = (long)lSize % BUFFER_SIZE;

                    for (int i = 0; i < numReads; ++i)
                    {
                        read = cin.Read(bytes, 0, bytes.Length);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value    += read;
                        outValue += read;
                    }

                    if (slack > 0)
                    {
                        read = cin.Read(bytes, 0, (int)slack);
                        fout.Write(bytes, 0, read);
                        chash.Write(bytes, 0, read);
                        value    += read;
                        outValue += read;
                    }

                    chash.Flush();
                    chash.Close();

                    fout.Flush();
                    fout.Close();

                    byte[] curHash = hasher.Hash;

                    // 获取比较和旧的散列对象
                    byte[] oldHash = new byte[hasher.HashSize / 8];
                    read = cin.Read(oldHash, 0, oldHash.Length);
                    if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
                    {
                        throw new CryptoHelpException("文件被破坏");
                    }
                }

                if (outValue != lSize)
                {
                    throw new CryptoHelpException("文件大小不匹配");
                }
            }
        }
        XmlElement VerifyInput2(MessageBuffer buf)
        {
            Message      msg2 = buf.CreateMessage();
            StringWriter sw   = new StringWriter();

            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw))) {
                msg2.WriteMessage(w);
            }
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(sw.ToString());

            // decrypt the key with service certificate privkey
            PaddingMode  mode   = PaddingMode.PKCS7;          // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
            EncryptedXml encXml = new EncryptedXml(doc);

            encXml.Padding = mode;
            X509Certificate2    cert2 = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
            nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#");
            nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
            XmlNode n = doc.SelectSingleNode("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);

            Assert.IsNotNull(n, "premise: enckey does not exist");
            string raw = n.InnerText;

            byte [] rawbytes             = Convert.FromBase64String(raw);
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey;

            byte [] decryptedKey = EncryptedXml.DecryptKey(rawbytes, rsa, true);             //rsa.Decrypt (rawbytes, true);

#if false
            // create derived keys
            Dictionary <string, byte[]>  keys = new Dictionary <string, byte[]> ();
            InMemorySymmetricSecurityKey skey =
                new InMemorySymmetricSecurityKey(decryptedKey);
            foreach (XmlElement el in doc.SelectNodes("//o:Security/c:DerivedKeyToken", nsmgr))
            {
                n = el.SelectSingleNode("c:Offset", nsmgr);
                int offset = (n == null) ? 0 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Length", nsmgr);
                int length = (n == null) ? 32 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Label", nsmgr);
                byte [] label = (n == null) ? decryptedKey :
                                Convert.FromBase64String(n.InnerText);
                n = el.SelectSingleNode("c:Nonce", nsmgr);
                byte [] nonce = (n == null) ? new byte [0] :
                                Convert.FromBase64String(n.InnerText);
                byte [] derkey = skey.GenerateDerivedKey(
                    //SecurityAlgorithms.Psha1KeyDerivation,
                    "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
                    label,
                    nonce,
                    length * 8,
                    offset);

                keys [el.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
            }
#endif

            // decrypt the signature with the decrypted key
#if true
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedSignature = ms.ToArray();
#else
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;

            EncryptedData ed = new EncryptedData();
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            ed.LoadXml(n as XmlElement);
            byte [] decryptedSignature = encXml.DecryptData(ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

            // decrypt the body with the decrypted key
#if true
            n = doc.SelectSingleNode("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            ms      = new MemoryStream();
            cs      = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedBody = ms.ToArray();
#else
            // decrypt the body with the decrypted key
            EncryptedData ed2 = new EncryptedData();
            XmlElement    el  = doc.SelectSingleNode("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
            ed2.LoadXml(el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            byte [] decryptedBody = encXml.DecryptData(ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
            Console.Error.WriteLine(Encoding.UTF8.GetString(decryptedBody));
            Console.Error.WriteLine("============= Decrypted Body End ===========");

            // FIXME: find out what first 16 bytes mean.
            for (int mmm = 0; mmm < 16; mmm++)
            {
                decryptedBody [mmm] = 0x20;
            }
            doc.LoadXml(Encoding.UTF8.GetString(decryptedBody));
            Assert.AreEqual("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
            Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

            return(doc.DocumentElement);
        }
Example #37
0
        protected void SubmitPreferencesButton_Click(object sender, EventArgs e)
        {
            //No Need for Validation
            DBConnect dbConnection = new DBConnect();
            SqlCommand objCommand = new SqlCommand();
            objCommand.CommandType = CommandType.StoredProcedure;
            objCommand.CommandText = "TPUpdateUserPreference";
            SqlParameter inputParameter = new SqlParameter("@Email", Session["userEmail"].ToString());
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@Login", LoginPreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@Theme", ThemePreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@ProfileInfoPrivacy", ProfileInfoPrivacyPreferenceDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@PhotoPrivacy", PhotoPrivacyDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            inputParameter = new SqlParameter("@PersonalContactInfoPrivacy", PersonalContactInfoDropDown.SelectedValue);
            inputParameter.Direction = ParameterDirection.Input;
            inputParameter.SqlDbType = SqlDbType.NVarChar;
            objCommand.Parameters.Add(inputParameter);

            int ResponseRecevied = dbConnection.DoUpdateUsingCmdObj(objCommand);

            String plainTextEmail = Session["userEmail"].ToString();
            String plainTextPassword = Session["userPassword"].ToString();
            String encryptedEmail;
            String encryptedPassword;
            UTF8Encoding encoder = new UTF8Encoding();
            Byte[] emailBytes;
            Byte[] passwordBytes;

            emailBytes = encoder.GetBytes(plainTextEmail);
            passwordBytes = encoder.GetBytes(plainTextPassword);
            RijndaelManaged rmEncryption = new RijndaelManaged();
            MemoryStream memStream = new MemoryStream();
            CryptoStream encryptionStream = new CryptoStream(memStream, rmEncryption.CreateEncryptor(key, vector), CryptoStreamMode.Write);


            if (ResponseRecevied == 1)
            {
                //Preferences Updated 
                if (LoginPreferenceDropDown.SelectedValue == "NONE")
                {
                    //Do Nothing
                    Response.Redirect("Feed.aspx");
                }
                if (LoginPreferenceDropDown.SelectedValue == "Auto-Login")
                {
                    //Auto Login
                    //Email
                    encryptionStream.Write(emailBytes, 0, emailBytes.Length);
                    encryptionStream.FlushFinalBlock();

                    memStream.Position = 0;
                    Byte[] encryptedEmailBytes = new byte[memStream.Length];
                    memStream.Read(encryptedEmailBytes, 0, encryptedEmailBytes.Length);

                    encryptionStream.Close();
                    memStream.Close();

                    //password
                    memStream = new MemoryStream();
                    encryptionStream = new CryptoStream(memStream, rmEncryption.CreateEncryptor(key, vector), CryptoStreamMode.Write);

                    encryptionStream.Write(passwordBytes, 0, passwordBytes.Length);
                    encryptionStream.FlushFinalBlock();

                    memStream.Position = 0;
                    Byte[] encryptedPasswordBytes = new byte[memStream.Length];
                    memStream.Read(encryptedPasswordBytes, 0, encryptedPasswordBytes.Length);

                    encryptionStream.Close();
                    memStream.Close();

                    encryptedEmail = Convert.ToBase64String(encryptedEmailBytes);
                    encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);

                    HttpCookie myCookie = new HttpCookie("LoginCookie");
                    myCookie.Values["Email"] = encryptedEmail;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    myCookie.Values["Password"] = encryptedPassword;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    Response.Cookies.Add(myCookie);
                    Response.Redirect("Feed.aspx");
                }
                if (LoginPreferenceDropDown.SelectedValue == "Fast-Login")
                {
                    encryptionStream.Write(emailBytes, 0, emailBytes.Length);
                    encryptionStream.FlushFinalBlock();

                    memStream.Position = 0;
                    Byte[] encryptedEmailBytes = new byte[memStream.Length];
                    memStream.Read(encryptedEmailBytes, 0, encryptedEmailBytes.Length);

                    encryptionStream.Close();
                    memStream.Close();

                    encryptedEmail = Convert.ToBase64String(encryptedEmailBytes);

                    HttpCookie myCookie = new HttpCookie("LoginCookie");
                    myCookie.Values["Email"] = encryptedEmail;
                    myCookie.Expires = new DateTime(2020, 2, 1);
                    Response.Cookies.Add(myCookie);
                    Response.Redirect("Feed.aspx");
                }
            }
        }
Example #38
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream">Input stream for plaintext, any stream with read capability is allowed.</param>
        /// <param name="outputFile">File name for the encrypted content to be saved. Any existing file will be overridden.</param>
        /// <param name="strPublickey"></param>
        public static void Encrypt(Stream inputStream, string outputFile, string strPublickey)
        {
            if (!inputStream.CanRead)
            {
                throw new Exception("Input stream should be readable!");
            }

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportCspBlob(Convert.FromBase64String(strPublickey));

            if (!rsa.PublicOnly)
            {
                throw new Exception("Don't use the private key blob for public key operations. Keep it in a safe place!");
            }

            // Random Key ve IV üret
            byte[] key = new byte[KEY_SIZE_BYTES];
            byte[] iv  = new byte[IV_SIZE_BYTES];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(key);
                rng.GetBytes(iv);
            }

            // Key'i rsa ile şifrele
            byte[] encryptedKey = rsa.Encrypt(key, false);
            rsa.Clear();

            // Create byte arrays to contain
            // the length values of the key and IV.
            byte[] lenEncKey = new byte[4];
            byte[] lenIV     = new byte[4];

            lenEncKey = BitConverter.GetBytes(encryptedKey.Length);
            lenIV     = BitConverter.GetBytes(iv.Length);

            // Dosyayı key ve iv ile şifrele
            // IV ve şifreli dosyayı kaydet
            using (FileStream outputStream = new FileStream(outputFile, FileMode.Create))
            {
                outputStream.Write(lenEncKey, 0, 4);
                outputStream.Write(lenIV, 0, 4);
                outputStream.Write(encryptedKey, 0, encryptedKey.Length);
                outputStream.Write(iv, 0, iv.Length);

                using (AesManaged aes = new AesManaged())
                {
                    aes.Mode = CipherMode.CBC;
                    aes.Key  = key;
                    aes.IV   = iv;

                    ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                    using (CryptoStream outStreamEncrypted = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                    {
                        int    count          = 0;
                        int    blockSizeBytes = aes.BlockSize / 8;
                        byte[] data           = new byte[blockSizeBytes];
                        int    bytesRead      = 0;

                        do
                        {
                            count = inputStream.Read(data, 0, blockSizeBytes);
                            outStreamEncrypted.Write(data, 0, count);
                            bytesRead += blockSizeBytes;
                        }while (count > 0);

                        outStreamEncrypted.FlushFinalBlock();
                        outStreamEncrypted.Close();
                    }
                    outputStream.Close();
                }
                Array.Clear(key, 0, key.Length);
            }
        }
Example #39
0
    static string smethod_2(int int_3)
    {
        if (Class14.byte_3.Length == 0)
        {
            BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("15b96398-9597-4145-8e52-82e25906b4b2"));
            binaryReader.BaseStream.Position = 0L;
            byte[] array  = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
            byte[] array2 = new byte[32];
            array2[0]  = 126;
            array2[0]  = 124;
            array2[0]  = 146;
            array2[0]  = 48;
            array2[1]  = 152;
            array2[1]  = 88;
            array2[1]  = 254;
            array2[2]  = 96;
            array2[2]  = 27;
            array2[2]  = 244;
            array2[3]  = 102;
            array2[3]  = 110;
            array2[3]  = 124;
            array2[3]  = 140;
            array2[4]  = 98;
            array2[4]  = 152;
            array2[4]  = 174;
            array2[4]  = 128;
            array2[5]  = 185;
            array2[5]  = 85;
            array2[5]  = 173;
            array2[6]  = 69;
            array2[6]  = 147;
            array2[6]  = 87;
            array2[6]  = 86;
            array2[7]  = 130;
            array2[7]  = 124;
            array2[7]  = 101;
            array2[8]  = 109;
            array2[8]  = 134;
            array2[8]  = 157;
            array2[8]  = 243;
            array2[9]  = 132;
            array2[9]  = 86;
            array2[9]  = 47;
            array2[9]  = 101;
            array2[9]  = 197;
            array2[10] = 106;
            array2[10] = 135;
            array2[10] = 138;
            array2[10] = 182;
            array2[10] = 84;
            array2[10] = 214;
            array2[11] = 95;
            array2[11] = 140;
            array2[11] = 95;
            array2[11] = 92;
            array2[11] = 248;
            array2[12] = 157;
            array2[12] = 142;
            array2[12] = 11;
            array2[13] = 120;
            array2[13] = 62;
            array2[13] = 115;
            array2[13] = 138;
            array2[13] = 156;
            array2[13] = 145;
            array2[14] = 134;
            array2[14] = 138;
            array2[14] = 88;
            array2[14] = 164;
            array2[14] = 120;
            array2[14] = 105;
            array2[15] = 123;
            array2[15] = 112;
            array2[15] = 80;
            array2[15] = 122;
            array2[15] = 46;
            array2[16] = 165;
            array2[16] = 84;
            array2[16] = 132;
            array2[16] = 108;
            array2[16] = 108;
            array2[17] = 160;
            array2[17] = 143;
            array2[17] = 105;
            array2[17] = 94;
            array2[17] = 150;
            array2[17] = 166;
            array2[18] = 138;
            array2[18] = 90;
            array2[18] = 202;
            array2[19] = 162;
            array2[19] = 107;
            array2[19] = 186;
            array2[20] = 130;
            array2[20] = 128;
            array2[20] = 113;
            array2[20] = 148;
            array2[20] = 132;
            array2[20] = 165;
            array2[21] = 66;
            array2[21] = 171;
            array2[21] = 94;
            array2[21] = 194;
            array2[22] = 166;
            array2[22] = 155;
            array2[22] = 126;
            array2[22] = 121;
            array2[22] = 133;
            array2[22] = 14;
            array2[23] = 163;
            array2[23] = 106;
            array2[23] = 84;
            array2[23] = 195;
            array2[23] = 232;
            array2[24] = 154;
            array2[24] = 129;
            array2[24] = 142;
            array2[25] = 168;
            array2[25] = 153;
            array2[25] = 136;
            array2[25] = 94;
            array2[25] = 118;
            array2[25] = 131;
            array2[26] = 136;
            array2[26] = 102;
            array2[26] = 121;
            array2[27] = 150;
            array2[27] = 84;
            array2[27] = 102;
            array2[27] = 10;
            array2[28] = 141;
            array2[28] = 104;
            array2[28] = 120;
            array2[28] = 117;
            array2[29] = 145;
            array2[29] = 144;
            array2[29] = 85;
            array2[29] = 7;
            array2[30] = 84;
            array2[30] = 178;
            array2[30] = 157;
            array2[30] = 173;
            array2[30] = 88;
            array2[30] = 212;
            array2[31] = 75;
            array2[31] = 153;
            array2[31] = 139;
            byte[] rgbKey = array2;
            byte[] array3 = new byte[16];
            array3[0]  = 126;
            array3[0]  = 121;
            array3[0]  = 222;
            array3[1]  = 29;
            array3[1]  = 163;
            array3[1]  = 167;
            array3[1]  = 120;
            array3[1]  = 234;
            array3[2]  = 31;
            array3[2]  = 60;
            array3[2]  = 72;
            array3[3]  = 145;
            array3[3]  = 150;
            array3[3]  = 247;
            array3[4]  = 74;
            array3[4]  = 165;
            array3[4]  = 164;
            array3[5]  = 117;
            array3[5]  = 104;
            array3[5]  = 113;
            array3[5]  = 136;
            array3[5]  = 224;
            array3[6]  = 227;
            array3[6]  = 157;
            array3[6]  = 222;
            array3[6]  = 166;
            array3[6]  = 45;
            array3[7]  = 129;
            array3[7]  = 93;
            array3[7]  = 118;
            array3[7]  = 175;
            array3[7]  = 89;
            array3[7]  = 24;
            array3[8]  = 103;
            array3[8]  = 136;
            array3[8]  = 170;
            array3[8]  = 142;
            array3[9]  = 156;
            array3[9]  = 85;
            array3[9]  = 55;
            array3[9]  = 167;
            array3[9]  = 196;
            array3[9]  = 179;
            array3[10] = 104;
            array3[10] = 92;
            array3[10] = 147;
            array3[10] = 85;
            array3[10] = 219;
            array3[11] = 170;
            array3[11] = 192;
            array3[11] = 121;
            array3[11] = 140;
            array3[11] = 27;
            array3[12] = 122;
            array3[12] = 94;
            array3[12] = 108;
            array3[12] = 155;
            array3[13] = 75;
            array3[13] = 122;
            array3[13] = 49;
            array3[13] = 86;
            array3[13] = 120;
            array3[13] = 112;
            array3[14] = 156;
            array3[14] = 126;
            array3[14] = 90;
            array3[14] = 153;
            array3[14] = 170;
            array3[14] = 100;
            array3[15] = 205;
            array3[15] = 156;
            array3[15] = 212;
            array3[15] = 112;
            array3[15] = 136;
            byte[] array4         = array3;
            byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken();
            if (publicKeyToken != null && publicKeyToken.Length > 0)
            {
                array4[1]  = publicKeyToken[0];
                array4[3]  = publicKeyToken[1];
                array4[5]  = publicKeyToken[2];
                array4[7]  = publicKeyToken[3];
                array4[9]  = publicKeyToken[4];
                array4[11] = publicKeyToken[5];
                array4[13] = publicKeyToken[6];
                array4[15] = publicKeyToken[7];
            }
            ICryptoTransform transform = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            }.CreateDecryptor(rgbKey, array4);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            Class14.byte_3 = memoryStream.ToArray();
            if (Class14.byte_3.Length > 0)
            {
                Class14.string_0 = new string[Class14.byte_3.Length / 4 + 1];
                Class14.int_0    = new int[Class14.byte_3.Length / 4 + 1];
            }
            memoryStream.Close();
            cryptoStream.Close();
            binaryReader.Close();
            Assembly assembly = typeof(Class14).Assembly;
            Class14.int_2  = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt32();
            Class14.long_0 = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt64();
        }
        int num = int_3 / 4;

        if (Class14.int_0[num] > 0)
        {
            return(((string[])Class14.string_0)[Class14.int_0[num]]);
        }
        int num2 = BitConverter.ToInt32(Class14.byte_3, int_3);

        if (Class14.intptr_0 == IntPtr.Zero)
        {
            Class14.intptr_0 = Class14.OpenProcess(16u, 1, (uint)Process.GetCurrentProcess().Id);
        }
        byte[] array5 = new byte[4];
        if (IntPtr.Size == 4)
        {
            Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.int_2 + num2), array5, 4u, out Class14.intptr_1);
        }
        else
        {
            Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.long_0 + (long)num2), array5, 4u, out Class14.intptr_1);
        }
        int num3 = BitConverter.ToInt32(array5, 0);

        array5 = new byte[num3];
        if (IntPtr.Size == 4)
        {
            Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.int_2 + num2 + 4), array5, Convert.ToUInt32(num3), out Class14.intptr_1);
        }
        else
        {
            Class14.ReadProcessMemory(Class14.intptr_0, new IntPtr(Class14.long_0 + (long)num2 + 4L), array5, Convert.ToUInt32(num3), out Class14.intptr_1);
        }
        byte[] array6  = Class14.smethod_7(array5);
        string @string = Encoding.Unicode.GetString(array6, 0, array6.Length);

        Class14.int_0[num] = Class14.int_1;
        ((string[])Class14.string_0)[Class14.int_1] = @string;
        Class14.int_1++;
        return(@string);
    }
        public async Task <IActionResult> UploadFileViaModel(FileInputModel model)
        {
            if (model == null ||
                model.FileToUpload == null || model.FileToUpload.Length == 0)
            {
                return(Content("file not selected"));
            }

            string secretKey = model.SecretKey;

            var path = Path.Combine(
                Directory.GetCurrentDirectory(), "wwwroot/epin",
                model.FileToUpload.GetFilename());

            string fileName       = Path.GetFileNameWithoutExtension(model.FileToUpload.GetFilename());
            string sFileExtension = Path.GetExtension(fileName).ToLower();
            string inputFile      = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/epin", model.FileToUpload.GetFilename());
            string outputFile     = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/epin", "decry_" + fileName);

            // save encrypted file
            using (var stream = new FileStream(path, FileMode.Create))
            {
                await model.FileToUpload.CopyToAsync(stream);
            }

            // decrypt file
            try
            {
                byte[] key = ASCIIEncoding.UTF8.GetBytes(secretKey);
                byte[] IV  = ASCIIEncoding.UTF8.GetBytes(secretKey);

                RijndaelManaged aes = new RijndaelManaged();
                aes.Mode    = CipherMode.ECB;
                aes.Padding = PaddingMode.PKCS7;

                ICryptoTransform decryptor = aes.CreateDecryptor(key, IV);

                CryptoStream cs    = new CryptoStream(model.FileToUpload.OpenReadStream(), decryptor, CryptoStreamMode.Read);
                FileStream   fsOut = new FileStream(outputFile, FileMode.Create);
                int          data;
                while ((data = cs.ReadByte()) != -1)
                {
                    fsOut.WriteByte((byte)data);
                }
                model.FileToUpload.OpenReadStream().Close();
                fsOut.Close();
                cs.Close();
            }

            catch (Exception ex)
            {
                // failed to decrypt file
                Console.WriteLine("Errors : " + ex.Message);
            }

            // File Download
            var memory = new MemoryStream();

            using (var stream = new FileStream(outputFile, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return(File(memory, GetContentType(outputFile), Path.GetFileName(outputFile)));
        }
Example #41
0
        private void DecryptFile(string inFile)
        {
            // Create instance of Aes for
            // symetric decryption of the data.
            Aes aes = Aes.Create();

            // Create byte arrays to get the length of
            // the encrypted key and IV.
            // These values were stored as 4 bytes each
            // at the beginning of the encrypted package.
            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            // Construct the file name for the decrypted file.
            string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

            // Use FileStream objects to read the encrypted
            // file (inFs) and save the decrypted file (outFs).
            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);

                // Convert the lengths to integer values.
                int lenK  = BitConverter.ToInt32(LenK, 0);
                int lenIV = BitConverter.ToInt32(LenIV, 0);

                // Determine the start postition of
                // the ciphter text (startC)
                // and its length(lenC).
                int startC = lenK + lenIV + 8;
                int lenC   = (int)inFs.Length - startC;

                // Create the byte arrays for
                // the encrypted Aes key,
                // the IV, and the cipher text.
                byte[] KeyEncrypted = new byte[lenK];
                byte[] IV           = new byte[lenIV];

                // Extract the key and IV
                // starting from index 8
                // after the length values.
                inFs.Seek(8, SeekOrigin.Begin);
                inFs.Read(KeyEncrypted, 0, lenK);
                inFs.Seek(8 + lenK, SeekOrigin.Begin);
                inFs.Read(IV, 0, lenIV);
                Directory.CreateDirectory(DecrFolder);
                // Use RSACryptoServiceProvider
                // to decrypt the AES key.
                byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

                // Decrypt the key.
                ICryptoTransform transform = aes.CreateDecryptor(KeyDecrypted, IV);

                // Decrypt the cipher text from
                // from the FileSteam of the encrypted
                // file (inFs) into the FileStream
                // for the decrypted file (outFs).
                using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                {
                    int count  = 0;
                    int offset = 0;

                    // blockSizeBytes can be any arbitrary size.
                    int    blockSizeBytes = aes.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];

                    // By decrypting a chunk a time,
                    // you can save memory and
                    // accommodate large files.

                    // Start at the beginning
                    // of the cipher text.
                    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();
            }
        }
Example #42
0
        private void EncryptFile(string inFile)
        {
            // Create instance of Aes for
            // symmetric encryption of the data.
            Aes aes = Aes.Create();
            ICryptoTransform transform = aes.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // encrypt the AES key.
            // rsa is previously instantiated:
            //    rsa = new RSACryptoServiceProvider(cspp);
            byte[] keyEncrypted = rsa.Encrypt(aes.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            int lKey = keyEncrypted.Length;

            LenK = BitConverter.GetBytes(lKey);
            int lIV = aes.IV.Length;

            LenIV = BitConverter.GetBytes(lIV);

            // Write the following to the FileStream
            // for the encrypted file (outFs):
            // - length of the key
            // - length of the IV
            // - ecrypted key
            // - the IV
            // - the encrypted cipher content

            int startFileName = inFile.LastIndexOf("\\") + 1;
            // Change the file's extension to ".enc"
            string outFile = EncrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".wndr";

            using (FileStream outFs = new FileStream(outFile, FileMode.Create))
            {
                outFs.Write(LenK, 0, 4);
                outFs.Write(LenIV, 0, 4);
                outFs.Write(keyEncrypted, 0, lKey);
                outFs.Write(aes.IV, 0, lIV);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                {
                    // By encrypting a chunk at
                    // a time, you can save memory
                    // and accommodate large files.
                    int count  = 0;
                    int offset = 0;

                    // blockSizeBytes can be any arbitrary size.
                    int    blockSizeBytes = aes.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];
                    int    bytesRead      = 0;

                    using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamEncrypted.Write(data, 0, count);
                            bytesRead += blockSizeBytes;
                        }while (count > 0);
                        inFs.Close();
                    }
                    outStreamEncrypted.FlushFinalBlock();
                    outStreamEncrypted.Close();
                }
                outFs.Close();
            }
        }
Example #43
0
        private void UploadBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (FileInfo fileinfo in fil)
            {
                //string scanResult = scanFile(fileinfo.FullName);
                string scanResult = "Clean";
                if (scanResult.Equals("Clean"))
                {
                    string fileext  = fileinfo.Extension;
                    string filename = fileinfo.Name.Substring(0, fileinfo.Name.Length - fileext.Length);
                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                    {
                        string serverpub = ms.getPubkey();
                        rsa.FromXmlString(serverpub);
                        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                        {
                            byte[] key = new byte[32];
                            byte[] IV  = new byte[16];
                            rng.GetBytes(key);
                            rng.GetBytes(IV);
                            using (RijndaelManaged aes = new RijndaelManaged())
                            {
                                aes.Mode = CipherMode.CBC;
                                aes.IV   = IV;
                                aes.Key  = key;
                                using (FileStream fsInput = new FileStream(fileinfo.FullName, FileMode.Open, FileAccess.Read))
                                {
                                    using (FileStream fsEncrypted = new FileStream(encryptpath + filename + ".ee", FileMode.Create, FileAccess.Write))
                                    {
                                        ICryptoTransform encryptor = aes.CreateEncryptor();
                                        using (CryptoStream cryptostream = new CryptoStream(fsEncrypted, encryptor, CryptoStreamMode.Write))
                                        {
                                            int    bytesread;
                                            byte[] buffer = new byte[16384];
                                            while (true)
                                            {
                                                bytesread = fsInput.Read(buffer, 0, 16384);
                                                if (bytesread == 0)
                                                {
                                                    break;
                                                }
                                                cryptostream.Write(buffer, 0, bytesread);
                                            }
                                            cryptostream.Close();
                                            byte[] data = getFileData(encryptpath + filename + ".ee");

                                            bool result = ms.uploadFiles(fileinfo.Length, grouplist.SelectedItem as string, user, filename, fileext, Convert.ToBase64String(rsa.Encrypt(aes.Key, false)), Convert.ToBase64String(aes.IV), data);
                                            if (!result)
                                            {
                                                MessageBox.Show(filename + " already exists!", "Error");
                                            }
                                            File.Delete(encryptpath + filename + ".ee");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (scanResult.Equals("Error!"))
                {
                    System.Windows.Forms.MessageBox.Show("An error has occurred");
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(scanResult);
                }
            }
            this.Close();
        }
Example #44
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 AESDecrypt(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 = null;
            initVectorBytes = Encoding.ASCII.GetBytes(initVector);

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

            // Convert our ciphertext into a byte array.
            byte[] cipherTextBytes = null;
            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 = null;

            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 = null;
            keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = null;

            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 = null;

            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

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

            memoryStream = new MemoryStream(cipherTextBytes);

            // Define memory stream which will be used to hold encrypted data.
            CryptoStream cryptoStream = null;

            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 = null;
            plainTextBytes = new byte[cipherTextBytes.Length + 1];

            // Start decrypting.
            int decryptedByteCount = 0;

            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 = null;

            plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

            // Return decrypted string.
            return(plainText);
        }
Example #45
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);
                Directory.CreateDirectory(DecrFolder);

                byte[] KeyDecrypted = rsa.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();
            }
        }
Example #46
0
            // FIXME	[KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
            //			Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Decrypt)]
            public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
            {
                if (encryptedData == null)
                {
                    throw new ArgumentNullException("encryptedData");
                }

                byte[] decdata = null;

                Rijndael aes        = Rijndael.Create();
                RSA      rsa        = GetKey(scope);
                int      headerSize = (rsa.KeySize >> 3);
                bool     valid1     = (encryptedData.Length >= headerSize);

                if (!valid1)
                {
                    headerSize = encryptedData.Length;
                }

                byte[] header = new byte[headerSize];
                Buffer.BlockCopy(encryptedData, 0, header, 0, headerSize);

                byte[] secret = null;
                byte[] key    = null;
                byte[] iv     = null;
                bool   valid2 = false;
                bool   valid3 = false;
                bool   valid4 = false;
                SHA256 hash   = SHA256.Create();

                try
                {
                    try
                    {
                        RSAOAEPKeyExchangeDeformatter deformatter = new RSAOAEPKeyExchangeDeformatter(rsa);
                        secret = deformatter.DecryptKeyExchange(header);
                        valid2 = (secret.Length == 68);
                    }
                    catch
                    {
                        valid2 = false;
                    }

                    if (!valid2)
                    {
                        secret = new byte[68];
                    }

                    // known values for structure (version 1 or 2)
                    valid3 = ((secret[1] == 16) && (secret[18] == 16) && (secret[35] == 32));

                    key = new byte[16];
                    Buffer.BlockCopy(secret, 2, key, 0, 16);
                    iv = new byte[16];
                    Buffer.BlockCopy(secret, 19, iv, 0, 16);

                    if ((optionalEntropy != null) && (optionalEntropy.Length > 0))
                    {
                        // the decrypted data won't be valid if the entropy isn't
                        // the same as the one used to protect (encrypt) it
                        byte[] mask = hash.ComputeHash(optionalEntropy);
                        for (int i = 0; i < 16; i++)
                        {
                            key[i] ^= mask[i];
                            iv[i]  ^= mask[i + 16];
                        }
                        valid3 &= (secret[0] == 2); // with entropy
                    }
                    else
                    {
                        valid3 &= (secret[0] == 1); // without entropy
                    }

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ICryptoTransform t = aes.CreateDecryptor(key, iv);
                        using (CryptoStream cs = new CryptoStream(ms, t, CryptoStreamMode.Write))
                        {
                            try
                            {
                                cs.Write(encryptedData, headerSize, encryptedData.Length - headerSize);
                                cs.Close();
                            }
                            catch
                            {
                                // whatever, we keep going
                            }
                        }
                        decdata = ms.ToArray();
                    }

                    byte[] digest = hash.ComputeHash(decdata);
                    valid4 = true;
                    for (int i = 0; i < 32; i++)
                    {
                        if (digest[i] != secret[36 + i])
                        {
                            valid4 = false;
                        }
                    }
                }
                finally
                {
                    if (key != null)
                    {
                        Array.Clear(key, 0, key.Length);
                        key = null;
                    }
                    if (secret != null)
                    {
                        Array.Clear(secret, 0, secret.Length);
                        secret = null;
                    }
                    if (iv != null)
                    {
                        Array.Clear(iv, 0, iv.Length);
                        iv = null;
                    }
                    aes.Clear();
                    hash.Clear();
                }

                // single point of error (also limits timing informations)
                if (!valid1 || !valid2 || !valid3 || !valid4)
                {
                    if (decdata != null)
                    {
                        Array.Clear(decdata, 0, decdata.Length);
                        decdata = null;
                    }
                    throw new CryptographicException("Invalid data.");
                }
                return(decdata);
            }
        public void ReceiveTcp()
        {
            try
            {
                byte[] data = new byte[512];
                int    command;
                while (_accepting)
                {
                    _clipboardManager = new ClipboardManager();
                    _tcpClient        = _tcpListener.AcceptTcpClient();
                    _tcpClient.GetStream().ReadTimeout = Timeout.Infinite;
                    _tcpClient.Client.LingerState = new LingerOption(true, 0);
                    SetTcpKeepAlive(_tcpClient.Client, 3000, 1);
                    byte[] clientPublicKey = new byte[72];
                    _tcpClient.GetStream().Read(clientPublicKey, 0, 72);
                    byte[] derivedKey =
                        _exch.DeriveKeyMaterial(CngKey.Import(clientPublicKey, CngKeyBlobFormat.EccPublicBlob));
                    _tcpClient.GetStream().Write(_publicKey, 0, _publicKey.Length);
                    while (true)
                    {
                        try
                        {
                            StreamReader streamReader = new StreamReader(_tcpClient.GetStream());

                            // ReSharper disable once AssignNullToNotNullAttribute
                            command = int.Parse(streamReader.ReadLine());
                            Console.WriteLine(command);
                            switch (command)
                            {
                            case 0:         // LOGIN
                                Console.WriteLine("Mannaggia quel bastardo di padre pio");
                                // ReSharper disable once PossibleNullReferenceException
                                string currentUserName =
                                    System.Security.Principal.WindowsIdentity.GetCurrent()
                                    .Name.Split(new char[] { '\\' })[1];
                                Console.WriteLine("Mannaggia quel bastardo di gianpaolo");
                                string receivedUserName = streamReader.ReadLine();
                                Console.WriteLine("Mannaggia quel bastardo di geova");
                                string domain = streamReader.ReadLine();
                                Console.WriteLine("Mannaggia quei coglioni di medjugorie");
                                Aes aes = new AesCryptoServiceProvider();
                                aes.Key = derivedKey;
                                byte[] bytes = new byte[aes.BlockSize / 8];
                                Console.WriteLine("Mannaggia quel bastardo dei tre pastorelli");
                                bytes.Initialize();
                                System.Buffer.BlockCopy(currentUserName.ToCharArray(), 0, bytes, 0,
                                                        bytes.Length > currentUserName.Length * sizeof(char)
                                                ? currentUserName.Length * sizeof(char)
                                                : bytes.Length);
                                Console.WriteLine("Mannaggia quel bastardo di fatima " + currentUserName);
                                aes.IV = bytes;
                                MemoryStream     ms        = new MemoryStream(64);
                                ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);
                                CryptoStream     csEncrypt = new CryptoStream(ms, encryptor,
                                                                              CryptoStreamMode.Write);
                                Console.WriteLine("Mannaggia quel cane del clero");


                                Console.WriteLine("bastardo del signore");
                                //int passSize = Int32.Parse(streamReader.ReadLine());
                                //Console.WriteLine("Diaccio " + passSize);
                                string encpassword = streamReader.ReadLine();
                                byte[] buffer      = Convert.FromBase64String(encpassword);
                                /*int length = _tcpClient.GetStream().Read(buffer, 0, 256);*/
                                Console.WriteLine("Masalaccio");
                                csEncrypt.Write(buffer, 0, buffer.Length);
                                Console.WriteLine("cristaccio");
                                csEncrypt.Flush();
                                csEncrypt.Close();
                                Console.WriteLine("Mannaggia quel bastardo di giovanardi");
                                string password = Encoding.UTF8.GetString(ms.ToArray());
                                IntPtr th       = IntPtr.Zero;

                                _authorized = LogonUser(receivedUserName, domain, password, 3, 0, ref th);

                                Console.WriteLine("Mannaggia la madonna " + password + " " + receivedUserName);


                                Console.WriteLine("Mannaggia il cristo");
                                //_authorized = Start.pc.ValidateCredentials(receivedUserName, password);
                                Console.WriteLine("Mannaggia dio " + _authorized);



                                /* Window.Dispatcher.Invoke(new Action(() =>
                                 * {
                                 * MessageBox.Show("Gesu: " + _authorized);
                                 * }));*/
                                //_authorized = true;
                                Console.WriteLine("mannaggia cristo: " + _authorized);
                                byte[] auth = BitConverter.GetBytes(_authorized);
                                _tcpClient.GetStream().Write(auth, 0, sizeof(bool));
                                _tcpClient.GetStream().Flush();
                                if (_authorized)
                                {
                                    Thread t = new Thread(_clipboardManager.InitializeShare);
                                    t.Start();
                                    Thread t1 = new Thread(_clipboardManager.AddConnection);
                                    t1.Start((_tcpClient.Client.RemoteEndPoint as IPEndPoint).Address.ToString());
                                    Console.WriteLine("badogna");
                                    SendSAS(false);
                                    Console.WriteLine("bubba");
                                    //_clipboardManager.AddConnection((_tcpClient.Client.RemoteEndPoint as IPEndPoint).Address.ToString());
                                }
                                else
                                {
                                    _tcpClient.Close();
                                }
                                break;

                            case 1:
                                byte[] clip = _clipboardManager.GetClipboardData();
                                byte[] len  = BitConverter.GetBytes(clip != null ? clip.Length : 0);
                                _tcpClient.GetStream().Write(len, 0, sizeof(int));
                                if (clip != null)
                                {
                                    _tcpClient.GetStream().Write(clip, 0, clip.Length);
                                }
                                Window.Dispatcher.Invoke(new Action(() =>
                                {
                                    Window.UnderControl.StrokeThickness = 0;
                                }));
                                break;

                            case 2:
                                try
                                {
                                    byte[] recClipLen = new byte[sizeof(int)];
                                    _tcpClient.GetStream().Read(recClipLen, 0, sizeof(int));
                                    int recLen = BitConverter.ToInt32(recClipLen, 0);
                                    if (recLen > 0)
                                    {
                                        int    read    = 0;
                                        byte[] recClip = new byte[recLen];
                                        while (read < recLen)
                                        {
                                            read += _tcpClient.GetStream().Read(recClip, read, recLen - read);
                                        }

                                        using (var memStream = new MemoryStream())
                                        {
                                            var binForm = new BinaryFormatter();
                                            memStream.Write(recClip, 0, recClip.Length);
                                            memStream.Seek(0, SeekOrigin.Begin);
                                            var obj = binForm.Deserialize(memStream);
                                            Window.Dispatcher.Invoke(new Action(() =>
                                            {
                                                _clipboardManager.SetClipboard(
                                                    ((IPEndPoint)_tcpClient.Client.RemoteEndPoint).Address
                                                    .ToString(), obj);
                                                Window.UnderControl.StrokeThickness = 12;
                                            }));
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            _authorized = false;
                            Console.WriteLine("Bastardo di quel merda del bambinello " + e.Message);
                            Window.Dispatcher.Invoke(new Action(() =>
                            {
                                Window.UnderControl.StrokeThickness = 0;
                            }));

                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Si fotta anche il diaccio " + e.Message + e.StackTrace);
            }
        }
Example #48
0
            // FIXME	[KeyContainerPermission (SecurityAction.Assert, KeyContainerName = "DAPI",
            //			Flags = KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Create)]
            public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
            {
                if (userData == null)
                {
                    throw new ArgumentNullException("userData");
                }

                Rijndael aes = Rijndael.Create();

                aes.KeySize = 128;

                byte[] encdata = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    ICryptoTransform t = aes.CreateEncryptor();
                    using (CryptoStream cs = new CryptoStream(ms, t, CryptoStreamMode.Write))
                    {
                        cs.Write(userData, 0, userData.Length);
                        cs.Close();
                        encdata = ms.ToArray();
                    }
                }

                byte[] key    = null;
                byte[] iv     = null;
                byte[] secret = null;
                byte[] header = null;
                SHA256 hash   = SHA256.Create();

                try
                {
                    key    = aes.Key;
                    iv     = aes.IV;
                    secret = new byte[1 + 1 + 16 + 1 + 16 + 1 + 32];

                    byte[] digest = hash.ComputeHash(userData);
                    if ((optionalEntropy != null) && (optionalEntropy.Length > 0))
                    {
                        // the same optionalEntropy will be required to get the data back
                        byte[] mask = hash.ComputeHash(optionalEntropy);
                        for (int i = 0; i < 16; i++)
                        {
                            key[i] ^= mask[i];
                            iv[i]  ^= mask[i + 16];
                        }
                        secret[0] = 2; // entropy
                    }
                    else
                    {
                        secret[0] = 1; // without entropy
                    }

                    secret[1] = 16;  // key size
                    Buffer.BlockCopy(key, 0, secret, 2, 16);
                    secret[18] = 16; // iv size
                    Buffer.BlockCopy(iv, 0, secret, 19, 16);
                    secret[35] = 32; // digest size
                    Buffer.BlockCopy(digest, 0, secret, 36, 32);

                    RSAOAEPKeyExchangeFormatter formatter = new RSAOAEPKeyExchangeFormatter(GetKey(scope));
                    header = formatter.CreateKeyExchange(secret);
                }
                finally
                {
                    if (key != null)
                    {
                        Array.Clear(key, 0, key.Length);
                        key = null;
                    }
                    if (secret != null)
                    {
                        Array.Clear(secret, 0, secret.Length);
                        secret = null;
                    }
                    if (iv != null)
                    {
                        Array.Clear(iv, 0, iv.Length);
                        iv = null;
                    }
                    aes.Clear();
                    hash.Clear();
                }

                byte[] result = new byte[header.Length + encdata.Length];
                Buffer.BlockCopy(header, 0, result, 0, header.Length);
                Buffer.BlockCopy(encdata, 0, result, header.Length, encdata.Length);
                return(result);
            }
Example #49
0
    static void smethod_4()
    {
        if (!Class14.bool_0)
        {
            Class14.bool_0 = true;
            BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("f3c46ed4-ca21-4eb8-b5e5-759b2c563d8c"));
            binaryReader.BaseStream.Position = 0L;
            byte[] array  = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
            byte[] array2 = new byte[32];
            array2[0]  = 126;
            array2[0]  = 195;
            array2[0]  = 42;
            array2[0]  = 92;
            array2[1]  = 144;
            array2[1]  = 99;
            array2[1]  = 44;
            array2[2]  = 138;
            array2[2]  = 135;
            array2[2]  = 150;
            array2[2]  = 148;
            array2[2]  = 87;
            array2[2]  = 41;
            array2[3]  = 136;
            array2[3]  = 136;
            array2[3]  = 41;
            array2[4]  = 104;
            array2[4]  = 190;
            array2[4]  = 161;
            array2[5]  = 103;
            array2[5]  = 116;
            array2[5]  = 167;
            array2[5]  = 179;
            array2[5]  = 115;
            array2[5]  = 15;
            array2[6]  = 52;
            array2[6]  = 86;
            array2[6]  = 15;
            array2[7]  = 110;
            array2[7]  = 146;
            array2[7]  = 84;
            array2[7]  = 250;
            array2[8]  = 121;
            array2[8]  = 128;
            array2[8]  = 86;
            array2[8]  = 128;
            array2[8]  = 130;
            array2[8]  = 210;
            array2[9]  = 85;
            array2[9]  = 165;
            array2[9]  = 104;
            array2[10] = 160;
            array2[10] = 220;
            array2[10] = 124;
            array2[10] = 203;
            array2[10] = 162;
            array2[11] = 75;
            array2[11] = 118;
            array2[11] = 96;
            array2[11] = 158;
            array2[11] = 89;
            array2[12] = 85;
            array2[12] = 101;
            array2[12] = 154;
            array2[12] = 123;
            array2[12] = 184;
            array2[13] = 84;
            array2[13] = 147;
            array2[13] = 88;
            array2[13] = 34;
            array2[13] = 73;
            array2[13] = 238;
            array2[14] = 72;
            array2[14] = 57;
            array2[14] = 198;
            array2[14] = 142;
            array2[14] = 106;
            array2[14] = 34;
            array2[15] = 153;
            array2[15] = 168;
            array2[15] = 106;
            array2[15] = 177;
            array2[15] = 183;
            array2[16] = 101;
            array2[16] = 178;
            array2[16] = 114;
            array2[16] = 164;
            array2[16] = 125;
            array2[16] = 119;
            array2[17] = 138;
            array2[17] = 61;
            array2[17] = 207;
            array2[17] = 149;
            array2[17] = 111;
            array2[17] = 164;
            array2[18] = 118;
            array2[18] = 122;
            array2[18] = 147;
            array2[18] = 10;
            array2[18] = 110;
            array2[18] = 145;
            array2[19] = 108;
            array2[19] = 136;
            array2[19] = 142;
            array2[19] = 209;
            array2[19] = 76;
            array2[20] = 184;
            array2[20] = 138;
            array2[20] = 159;
            array2[20] = 8;
            array2[21] = 102;
            array2[21] = 91;
            array2[21] = 176;
            array2[21] = 104;
            array2[21] = 138;
            array2[22] = 114;
            array2[22] = 84;
            array2[22] = 146;
            array2[22] = 122;
            array2[23] = 97;
            array2[23] = 68;
            array2[23] = 108;
            array2[23] = 120;
            array2[23] = 120;
            array2[23] = 85;
            array2[24] = 116;
            array2[24] = 102;
            array2[24] = 96;
            array2[24] = 172;
            array2[25] = 133;
            array2[25] = 34;
            array2[25] = 136;
            array2[25] = 179;
            array2[26] = 153;
            array2[26] = 128;
            array2[26] = 230;
            array2[27] = 147;
            array2[27] = 105;
            array2[27] = 163;
            array2[27] = 132;
            array2[27] = 111;
            array2[28] = 101;
            array2[28] = 143;
            array2[28] = 111;
            array2[28] = 100;
            array2[28] = 164;
            array2[28] = 212;
            array2[29] = 151;
            array2[29] = 86;
            array2[29] = 78;
            array2[29] = 141;
            array2[29] = 112;
            array2[29] = 117;
            array2[30] = 101;
            array2[30] = 87;
            array2[30] = 137;
            array2[30] = 120;
            array2[30] = 238;
            array2[31] = 110;
            array2[31] = 170;
            array2[31] = 204;
            byte[] rgbKey = array2;
            byte[] array3 = new byte[16];
            array3[0]  = 126;
            array3[0]  = 88;
            array3[0]  = 25;
            array3[1]  = 40;
            array3[1]  = 172;
            array3[1]  = 113;
            array3[2]  = 165;
            array3[2]  = 102;
            array3[2]  = 126;
            array3[3]  = 31;
            array3[3]  = 178;
            array3[3]  = 164;
            array3[3]  = 113;
            array3[3]  = 98;
            array3[3]  = 123;
            array3[4]  = 134;
            array3[4]  = 153;
            array3[4]  = 200;
            array3[4]  = 25;
            array3[4]  = 149;
            array3[4]  = 134;
            array3[5]  = 102;
            array3[5]  = 186;
            array3[5]  = 112;
            array3[5]  = 70;
            array3[5]  = 163;
            array3[5]  = 77;
            array3[6]  = 161;
            array3[6]  = 115;
            array3[6]  = 140;
            array3[6]  = 117;
            array3[7]  = 165;
            array3[7]  = 132;
            array3[7]  = 159;
            array3[7]  = 29;
            array3[8]  = 166;
            array3[8]  = 54;
            array3[8]  = 124;
            array3[8]  = 104;
            array3[8]  = 254;
            array3[9]  = 148;
            array3[9]  = 145;
            array3[9]  = 190;
            array3[9]  = 85;
            array3[9]  = 80;
            array3[10] = 91;
            array3[10] = 151;
            array3[10] = 144;
            array3[10] = 149;
            array3[11] = 156;
            array3[11] = 151;
            array3[11] = 162;
            array3[11] = 126;
            array3[11] = 250;
            array3[12] = 116;
            array3[12] = 205;
            array3[12] = 108;
            array3[12] = 138;
            array3[12] = 100;
            array3[13] = 100;
            array3[13] = 145;
            array3[13] = 70;
            array3[13] = 101;
            array3[14] = 98;
            array3[14] = 149;
            array3[14] = 108;
            array3[14] = 133;
            array3[14] = 243;
            array3[15] = 106;
            array3[15] = 88;
            array3[15] = 141;
            array3[15] = 87;
            array3[15] = 159;
            array3[15] = 143;
            byte[] array4         = array3;
            byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken();
            if (publicKeyToken != null && publicKeyToken.Length > 0)
            {
                array4[1]  = publicKeyToken[0];
                array4[3]  = publicKeyToken[1];
                array4[5]  = publicKeyToken[2];
                array4[7]  = publicKeyToken[3];
                array4[9]  = publicKeyToken[4];
                array4[11] = publicKeyToken[5];
                array4[13] = publicKeyToken[6];
                array4[15] = publicKeyToken[7];
            }
            ICryptoTransform transform = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            }.CreateDecryptor(rgbKey, array4);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            byte[] buffer = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            binaryReader.Close();
            binaryReader = new BinaryReader(new MemoryStream(buffer));
            binaryReader.BaseStream.Position = 0L;
            IntPtr   intptr_  = IntPtr.Zero;
            Assembly assembly = typeof(Class14).Assembly;
            intptr_        = Class14.OpenProcess(56u, 1, (uint)Process.GetCurrentProcess().Id);
            Class14.int_2  = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt32();
            Class14.long_0 = Marshal.GetHINSTANCE(assembly.GetModules()[0]).ToInt64();
            IntPtr zero = IntPtr.Zero;
            int    num  = binaryReader.ReadInt32();
            binaryReader.ReadInt32();
            for (int i = 0; i < num; i++)
            {
                if (IntPtr.Size == 4)
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.int_2 + binaryReader.ReadInt32()), BitConverter.GetBytes(binaryReader.ReadInt32()), 4u, out zero);
                }
                else
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.long_0 + (long)binaryReader.ReadInt32()), BitConverter.GetBytes(binaryReader.ReadInt32()), 4u, out zero);
                }
            }
            while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length - 1L)
            {
                int    num2  = binaryReader.ReadInt32();
                int    num3  = binaryReader.ReadInt32();
                int    num4  = binaryReader.ReadInt32();
                byte[] byte_ = binaryReader.ReadBytes(num4);
                if (num3 > 0)
                {
                    Class14.sortedList_0[num3] = num2;
                }
                if (IntPtr.Size == 4)
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.int_2 + num2), byte_, Convert.ToUInt32(num4), out zero);
                }
                else
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.long_0 + (long)num2), byte_, Convert.ToUInt32(num4), out zero);
                }
            }
            int    metadataToken = new StackFrame(1).GetMethod().MetadataToken;
            object obj           = Class14.sortedList_0[metadataToken];
            if (obj != null)
            {
                if (IntPtr.Size == 4)
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.int_2 + (int)obj), new byte[]
                    {
                        255,
                        255,
                        255,
                        255
                    }, 4u, out zero);
                }
                else
                {
                    Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.long_0 + (long)((int)obj)), new byte[]
                    {
                        255,
                        255,
                        255,
                        255
                    }, 4u, out zero);
                }
                Class14.sortedList_0.Remove(metadataToken);
            }
            StackFrame stackFrame = new StackFrame(2);
            if (stackFrame.GetMethod() != null)
            {
                int    metadataToken2 = stackFrame.GetMethod().MetadataToken;
                object obj2           = Class14.sortedList_0[metadataToken2];
                if (obj2 != null)
                {
                    if (IntPtr.Size == 4)
                    {
                        Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.int_2 + (int)obj2), new byte[]
                        {
                            255,
                            255,
                            255,
                            255
                        }, 4u, out zero);
                    }
                    else
                    {
                        Class14.WriteProcessMemory(intptr_, new IntPtr(Class14.long_0 + (long)((int)obj2)), new byte[]
                        {
                            255,
                            255,
                            255,
                            255
                        }, 4u, out zero);
                    }
                    Class14.sortedList_0.Remove(metadataToken2);
                }
            }
            Class14.CloseHandle(intptr_);
            return;
        }
        StackFrame stackFrame2    = new StackFrame(1);
        int        metadataToken3 = stackFrame2.GetMethod().MetadataToken;
        object     obj3           = Class14.sortedList_0[metadataToken3];

        if (obj3 != null)
        {
            IntPtr intptr_2 = IntPtr.Zero;
            intptr_2 = Class14.OpenProcess(56u, 1, (uint)Process.GetCurrentProcess().Id);
            IntPtr zero2 = IntPtr.Zero;
            if (IntPtr.Size == 4)
            {
                Class14.WriteProcessMemory(intptr_2, new IntPtr(Class14.int_2 + (int)obj3), new byte[]
                {
                    255,
                    255,
                    255,
                    255
                }, 4u, out zero2);
            }
            else
            {
                Class14.WriteProcessMemory(intptr_2, new IntPtr(Class14.long_0 + (long)((int)obj3)), new byte[]
                {
                    255,
                    255,
                    255,
                    255
                }, 4u, out zero2);
            }
            Class14.sortedList_0.Remove(metadataToken3);
            Class14.CloseHandle(intptr_2);
        }
    }
Example #50
0
        public static void Decrypt(Stream encryptedFile, string outputFile, string strPrivatekey)
        {
            if (!encryptedFile.CanRead)
            {
                throw new Exception("Input stream should be readable!");
            }

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportCspBlob(Convert.FromBase64String(strPrivatekey));

            if (rsa.PublicOnly)
            {
                throw new Exception("The blob does not contain any private key!");
            }

            // Dosyadan iv ve encrypted key çıkar.

            // headerdan 8 byte oku, enckey ve iv boylarını öğren
            byte[] lenEncKey = new byte[4];
            byte[] lenIV     = new byte[4];

            encryptedFile.Read(lenEncKey, 0, 4);
            encryptedFile.Read(lenIV, 0, 4);

            int lEncKey = BitConverter.ToInt32(lenEncKey, 0);
            int lIV     = BitConverter.ToInt32(lenIV, 0);

            byte[] encryptedKey = new byte[lEncKey];
            encryptedFile.Read(encryptedKey, 0, lEncKey);

            byte[] iv = new byte[lIV];
            encryptedFile.Read(iv, 0, lIV);

            // encrypted key'i çöz
            byte[] key = rsa.Decrypt(encryptedKey, false);
            rsa.Clear();

            // dosyayı çöz
            using (FileStream outputStream = new FileStream(outputFile, FileMode.Create))
            {
                using (AesManaged aes = new AesManaged())
                {
                    aes.Mode = CipherMode.CBC;
                    aes.Key  = key;
                    aes.IV   = iv;

                    ICryptoTransform encryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                    using (CryptoStream outStreamEncrypted = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                    {
                        int    count          = 0;
                        int    blockSizeBytes = aes.BlockSize / 8;
                        byte[] data           = new byte[blockSizeBytes];
                        int    bytesRead      = 0;

                        do
                        {
                            count = encryptedFile.Read(data, 0, blockSizeBytes);
                            outStreamEncrypted.Write(data, 0, count);
                            bytesRead += blockSizeBytes;
                        }while (count > 0);

                        outStreamEncrypted.FlushFinalBlock();
                        outStreamEncrypted.Close();
                    }
                    outputStream.Close();
                }
                Array.Clear(key, 0, key.Length);
            }
        }
Example #51
0
    static bool smethod_0(int int_3)
    {
        if (Class14.byte_1.Length == 0)
        {
            BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("552aa579-b26a-42c6-927d-ada4908113cd"));
            binaryReader.BaseStream.Position = 0L;
            byte[] array  = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
            byte[] array2 = new byte[32];
            array2[0]  = 181;
            array2[0]  = 122;
            array2[0]  = 116;
            array2[0]  = 131;
            array2[1]  = 147;
            array2[1]  = 98;
            array2[1]  = 215;
            array2[2]  = 166;
            array2[2]  = 117;
            array2[2]  = 156;
            array2[2]  = 48;
            array2[2]  = 253;
            array2[3]  = 186;
            array2[3]  = 105;
            array2[3]  = 113;
            array2[3]  = 199;
            array2[4]  = 148;
            array2[4]  = 183;
            array2[4]  = 72;
            array2[4]  = 171;
            array2[4]  = 104;
            array2[4]  = 72;
            array2[5]  = 112;
            array2[5]  = 196;
            array2[5]  = 155;
            array2[6]  = 154;
            array2[6]  = 96;
            array2[6]  = 23;
            array2[7]  = 90;
            array2[7]  = 132;
            array2[7]  = 46;
            array2[8]  = 160;
            array2[8]  = 101;
            array2[8]  = 169;
            array2[8]  = 59;
            array2[8]  = 100;
            array2[8]  = 135;
            array2[9]  = 26;
            array2[9]  = 163;
            array2[9]  = 55;
            array2[9]  = 74;
            array2[9]  = 31;
            array2[10] = 116;
            array2[10] = 153;
            array2[10] = 59;
            array2[10] = 147;
            array2[10] = 122;
            array2[10] = 111;
            array2[11] = 81;
            array2[11] = 103;
            array2[11] = 103;
            array2[11] = 228;
            array2[12] = 219;
            array2[12] = 152;
            array2[12] = 53;
            array2[13] = 196;
            array2[13] = 164;
            array2[13] = 116;
            array2[13] = 108;
            array2[13] = 147;
            array2[13] = 138;
            array2[14] = 8;
            array2[14] = 88;
            array2[14] = 139;
            array2[15] = 100;
            array2[15] = 108;
            array2[15] = 165;
            array2[15] = 97;
            array2[15] = 213;
            array2[16] = 134;
            array2[16] = 95;
            array2[16] = 153;
            array2[16] = 134;
            array2[16] = 157;
            array2[16] = 48;
            array2[17] = 140;
            array2[17] = 152;
            array2[17] = 126;
            array2[17] = 96;
            array2[17] = 22;
            array2[18] = 216;
            array2[18] = 120;
            array2[18] = 155;
            array2[18] = 142;
            array2[18] = 217;
            array2[18] = 33;
            array2[19] = 91;
            array2[19] = 116;
            array2[19] = 96;
            array2[19] = 194;
            array2[19] = 4;
            array2[20] = 67;
            array2[20] = 119;
            array2[20] = 214;
            array2[21] = 117;
            array2[21] = 136;
            array2[21] = 90;
            array2[21] = 122;
            array2[21] = 215;
            array2[22] = 79;
            array2[22] = 111;
            array2[22] = 139;
            array2[22] = 177;
            array2[23] = 63;
            array2[23] = 86;
            array2[23] = 130;
            array2[23] = 120;
            array2[23] = 138;
            array2[23] = 175;
            array2[24] = 113;
            array2[24] = 92;
            array2[24] = 173;
            array2[24] = 122;
            array2[24] = 166;
            array2[25] = 129;
            array2[25] = 95;
            array2[25] = 98;
            array2[25] = 162;
            array2[25] = 89;
            array2[25] = 191;
            array2[26] = 124;
            array2[26] = 166;
            array2[26] = 37;
            array2[27] = 84;
            array2[27] = 47;
            array2[27] = 83;
            array2[27] = 135;
            array2[27] = 66;
            array2[27] = 218;
            array2[28] = 121;
            array2[28] = 140;
            array2[28] = 82;
            array2[28] = 149;
            array2[28] = 140;
            array2[28] = 29;
            array2[29] = 171;
            array2[29] = 160;
            array2[29] = 55;
            array2[29] = 77;
            array2[29] = 111;
            array2[29] = 163;
            array2[30] = 152;
            array2[30] = 118;
            array2[30] = 152;
            array2[30] = 153;
            array2[31] = 94;
            array2[31] = 171;
            array2[31] = 89;
            array2[31] = 35;
            byte[] rgbKey = array2;
            byte[] array3 = new byte[16];
            array3[0]  = 126;
            array3[0]  = 161;
            array3[0]  = 104;
            array3[1]  = 31;
            array3[1]  = 126;
            array3[1]  = 148;
            array3[1]  = 110;
            array3[1]  = 173;
            array3[1]  = 154;
            array3[2]  = 122;
            array3[2]  = 99;
            array3[2]  = 86;
            array3[2]  = 88;
            array3[2]  = 88;
            array3[2]  = 51;
            array3[3]  = 168;
            array3[3]  = 121;
            array3[3]  = 39;
            array3[3]  = 183;
            array3[3]  = 148;
            array3[3]  = 253;
            array3[4]  = 102;
            array3[4]  = 100;
            array3[4]  = 100;
            array3[4]  = 158;
            array3[4]  = 21;
            array3[5]  = 154;
            array3[5]  = 204;
            array3[5]  = 155;
            array3[5]  = 168;
            array3[5]  = 161;
            array3[6]  = 160;
            array3[6]  = 92;
            array3[6]  = 203;
            array3[7]  = 162;
            array3[7]  = 157;
            array3[7]  = 90;
            array3[7]  = 20;
            array3[8]  = 147;
            array3[8]  = 127;
            array3[8]  = 43;
            array3[9]  = 98;
            array3[9]  = 177;
            array3[9]  = 127;
            array3[9]  = 117;
            array3[10] = 154;
            array3[10] = 134;
            array3[10] = 205;
            array3[11] = 59;
            array3[11] = 172;
            array3[11] = 103;
            array3[11] = 170;
            array3[11] = 3;
            array3[12] = 134;
            array3[12] = 155;
            array3[12] = 88;
            array3[12] = 149;
            array3[12] = 216;
            array3[13] = 84;
            array3[13] = 138;
            array3[13] = 143;
            array3[13] = 115;
            array3[13] = 98;
            array3[13] = 139;
            array3[14] = 189;
            array3[14] = 88;
            array3[14] = 168;
            array3[14] = 136;
            array3[14] = 171;
            array3[15] = 187;
            array3[15] = 166;
            array3[15] = 209;
            byte[] array4         = array3;
            byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken();
            if (publicKeyToken != null && publicKeyToken.Length > 0)
            {
                array4[1]  = publicKeyToken[0];
                array4[3]  = publicKeyToken[1];
                array4[5]  = publicKeyToken[2];
                array4[7]  = publicKeyToken[3];
                array4[9]  = publicKeyToken[4];
                array4[11] = publicKeyToken[5];
                array4[13] = publicKeyToken[6];
                array4[15] = publicKeyToken[7];
            }
            ICryptoTransform transform = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            }.CreateDecryptor(rgbKey, array4);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            Class14.byte_1 = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            binaryReader.Close();
        }
        if (Class14.byte_0.Length == 0)
        {
            Class14.byte_0 = Class14.smethod_6(Class14.smethod_5(typeof(Class14).Assembly).ToString());
        }
        int num = 0;

        try
        {
            num = BitConverter.ToInt32(new byte[]
            {
                Class14.byte_1[int_3],
                Class14.byte_1[int_3 + 1],
                Class14.byte_1[int_3 + 2],
                Class14.byte_1[int_3 + 3]
            }, 0);
        }
        catch
        {
        }
        try
        {
            if (Class14.byte_0[num] == 128)
            {
                return(true);
            }
        }
        catch
        {
        }
        return(false);
    }
        public static string Encrypt <T>(string value)
            where T : SymmetricAlgorithm, new()
        {
            if (!File.Exists(value))
            {
                byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
                byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);
                byte[] valueBytes  = Encoding.UTF8.GetBytes(value);

                byte[] encrypted;
                using (var cipher = new T())
                {
                    var passwordBytes =
                        new PasswordDeriveBytes(_password, saltBytes, Hash, Iterations);
                    byte[] keyBytes = passwordBytes.GetBytes(KeySize / 8);

                    cipher.Mode = CipherMode.CBC;

                    using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
                    {
                        using (var to = new MemoryStream())
                        {
                            using (var writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
                            {
                                writer.Write(valueBytes, 0, valueBytes.Length);
                                writer.FlushFinalBlock();
                                encrypted = to.ToArray();
                            }
                        }
                    }
                    cipher.Clear();
                }
                return(Convert.ToBase64String(encrypted));
            }
            else
            {
                byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector);
                byte[] saltBytes   = Encoding.ASCII.GetBytes(_salt);

                using (var cipher = new T())
                {
                    var    passwordBytes = new PasswordDeriveBytes(_password, saltBytes, Hash, Iterations);
                    byte[] keyBytes      = passwordBytes.GetBytes(KeySize / 8);

                    var fsInput = new FileStream(value, FileMode.Open, FileAccess.Read);

                    var fsEncrypted = new FileStream(value + "_e", FileMode.Create, FileAccess.Write);

                    ICryptoTransform encrypt = cipher.CreateEncryptor(keyBytes, vectorBytes);
                    var cryptostream         = new CryptoStream(fsEncrypted, encrypt, CryptoStreamMode.Write);

                    var bytearrayinput = new byte[fsInput.Length];
                    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
                    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
                    cryptostream.Close();
                    fsInput.Close();
                    fsEncrypted.Close();

                    return(null);
                }
            }
        }
Example #53
0
        // Decrypt a byte array into a byte array using a key and an IV
        public static byte[] Decrypt(byte[] cipherData,
                                     byte[] Key, byte[] IV)
        {
            try
            {
                // Create a MemoryStream that is going to accept the
                // decrypted bytes
                MemoryStream ms = new MemoryStream();

                // Create a symmetric algorithm.
                // We are going to use Rijndael because it is strong and
                // available on all platforms.
                // You can use other algorithms, to do so substitute the next
                // line with something like
                //     TripleDES alg = TripleDES.Create();
                Rijndael alg = Rijndael.Create();

                // Now set the key and the IV.
                // We need the IV (Initialization Vector) because the algorithm
                // is operating in its default
                // mode called CBC (Cipher Block Chaining). The IV is XORed with
                // the first block (8 byte)
                // of the data after it is decrypted, and then each decrypted
                // block is XORed with the previous
                // cipher block. This is done to make encryption more secure.
                // There is also a mode called ECB which does not need an IV,
                // but it is much less secure.
                alg.Key = Key;
                alg.IV  = IV;

                // Create a CryptoStream through which we are going to be
                // pumping our data.
                // CryptoStreamMode.Write means that we are going to be
                // writing data to the stream
                // and the output will be written in the MemoryStream
                // we have provided.
                CryptoStream cs = new CryptoStream(ms,
                                                   alg.CreateDecryptor(), CryptoStreamMode.Write);

                // Write the data and make it do the decryption
                cs.Write(cipherData, 0, cipherData.Length);

                // Close the crypto stream (or do FlushFinalBlock).
                // This will tell it that we have done our decryption
                // and there is no more data coming in,
                // and it is now a good time to remove the padding
                // and finalize the decryption process.
                cs.Close();

                // Now get the decrypted data from the MemoryStream.
                // Some people make a mistake of using GetBuffer() here,
                // which is not the right way.
                byte[] decryptedData = ms.ToArray();

                return(decryptedData);
            }
            catch (Exception ex)
            {
                throw new Exception("解密错误:" + ex.Message, ex);
            }
        }
Example #54
0
        private bool EmpLogin(string _UserName, string _Password)
        {
            Sb = new StringBuilder();
            Sb.Append("SELECT E.Employee_ID,U.User_Password,E.Employee_FirstName,E.Employee_LastName");
            Sb.Append(" FROM Employee E");
            Sb.Append(" INNER JOIN User_Login U ON E.Employee_ID	= U.User_ID ");
            Sb.Append(" WHERE (U.User_ID=@UserName)");
            Sb.Append(" AND (U.User_Password=@Password)");
            string sqlLogin;

            sqlLogin = Sb.ToString();

            byte[] CurrentIV  = new byte[] { 51, 52, 53, 54, 55, 56, 57, 58 };
            byte[] CurrentKey = { };
            if (_UserName.Length == 8)
            {
                CurrentKey = Encoding.ASCII.GetBytes(_UserName);
            }
            else if (_UserName.Length > 8)
            {
                CurrentKey = Encoding.ASCII.GetBytes(_UserName.Substring(0, 8));
            }
            else
            {
                string AddString = _UserName.Substring(0, 1);
                int    TotalLoop = 8 - Convert.ToInt32(_UserName.Length);
                string tmpKey    = _UserName;

                for (int i = 1; i <= TotalLoop; i++)
                {
                    tmpKey = tmpKey + AddString;
                }
                CurrentKey = Encoding.ASCII.GetBytes(tmpKey);
            }

            desCrypt     = new DESCryptoServiceProvider();
            desCrypt.IV  = CurrentIV;
            desCrypt.Key = CurrentKey;

            ms          = new MemoryStream();
            ms.Position = 0;

            ICryptoTransform ce = desCrypt.CreateEncryptor();

            cs = new CryptoStream(ms, ce, CryptoStreamMode.Write);
            byte[] arrByte = Encoding.ASCII.GetBytes(_Password);
            cs.Write(arrByte, 0, arrByte.Length);
            cs.FlushFinalBlock();
            cs.Close();

            PwdWithEncrypt = Convert.ToBase64String(ms.ToArray());

            Cmd             = new SqlCommand();
            Cmd.CommandText = sqlLogin;
            Cmd.CommandType = CommandType.Text;
            Cmd.Connection  = Conn;
            Cmd.Parameters.Clear();
            Cmd.Parameters.Add("@UserName", SqlDbType.NVarChar).Value = _UserName;
            Cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = PwdWithEncrypt;
            Sdr = Cmd.ExecuteReader();
            if (Sdr.HasRows)
            {
                Sdr.Read();
                //CurrentAuthentication = Sdr.GetString(Sdr.GetOrdinal("Auth"));
                //   string UserName = dr.GetString(dr.GetOrdinal("UserId"));
                string UserName = Sdr.GetString(Sdr.GetOrdinal("Employee_ID"));
                string SureName = Sdr.GetString(Sdr.GetOrdinal("Employee_FirstName"));
                string LastName = Sdr.GetString(Sdr.GetOrdinal("Employee_LastName"));
                DBConnString.sUserIdLogin = UserName;
                DBConnString.sUserlogin   = SureName + " " + LastName;
                return(true);
            }
            else
            {
                Sdr.Close();
                return(false);
            }
        }
Example #55
0
        /// <summary>
        /// Encrypts specified plaintext using Rijndael symmetric key algorithm
        /// and returns a base64-encoded result.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be encrypted.
        /// </param>
        /// <param name="passPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="saltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="passwordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="keySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256.
        /// Longer keys are more secure than shorter keys.
        /// </param>
        /// <returns>
        /// Encrypted value formatted as a base64-encoded string.
        /// </returns>
        private static string Encrypt(string plainText,
                                      string passPhrase,
                                      string saltValue,
                                      string hashAlgorithm,
                                      int passwordIterations,
                                      string initVector,
                                      int keySize)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
            byte[] saltValueBytes  = Encoding.ASCII.GetBytes(saltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

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

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

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

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

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

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

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

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

            // Finish encrypting.
            cryptoStream.FlushFinalBlock();

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

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

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

            // Return encrypted string.
            return(cipherText);
        }
Example #56
0
        //########## Coped from hikvision decrypter. Also by me. ##########//
        public void doDecrypt(byte[] data)
        {
            byte[] key       = { 0x73, 0x8B, 0x55, 0x44 };
            byte[] xorOutput = new byte[data.Length];

            print(Color.DarkGreen, "Decrypting...");

            byte[] decryptedData;
            try
            {
                byte[] cipherBytes = data;
                using (Aes encryptor = Aes.Create())
                {
                    encryptor.Mode    = CipherMode.ECB;
                    encryptor.Padding = PaddingMode.Zeros;
                    encryptor.Key     = FromHex("27-99-77-f6-2f-6c-fd-2d-91-cd-75-b8-89-ce-0c-9a");
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        decryptedData = ms.ToArray();
                    }
                }
            }
            catch
            {
                print(Color.Red, "Decrypt error!");
                return;
            }
            print(Color.DarkGreen, "Xoring...");

            for (int i = 0; i < decryptedData.Length; i++)
            {
                xorOutput[i] = (byte)(decryptedData[i] ^ key[i % key.Length]);
            }

            string output = Encoding.UTF8.GetString(xorOutput);

            print(Color.DarkGreen, "Decrypted!");
            print(Color.DarkGreen, "Searching for credentials...");

            //this concludes decrypting.

            //strip unprintable characters. seperate strings with 0x00.
            byte[]      printables = new byte[] { 27, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x5c, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e };
            List <Byte> buffer     = new List <Byte> {
            };
            bool swit = true;

            foreach (byte b in xorOutput)
            {
                if (printables.Contains(b))
                {
                    buffer.Add(b);
                    swit = true;
                }
                else
                {
                    if (swit)
                    {
                        buffer.Add(0x00);
                        swit = false;
                    }
                }
            }

            string dat = Encoding.UTF8.GetString(buffer.ToArray());

            string[] rawSplit = dat.Split((char)0x00);


            string username = "";
            string password = "";

            List <String> possibles = new List <String> {
            };

            int count = 0;

            foreach (string s in rawSplit)
            {
                count++;
                //every hikvision has an "admin" account.
                if (s == "admin")
                {
                    username = "******";
                    password = rawSplit[count];

                    possibles.Add(username + ":" + password);
                }
            }

            testFoundCreds(possibles);

            if (possibles.Count() == 0)
            {
                print(Color.Orange, "Find manually.");
                print(Color.Orange, "Couldnt find credentials.");
            }

            if (cbSaveOutput.Checked || possibles.Count() == 0)
            {
                using (SaveFileDialog dlg = new SaveFileDialog())
                {
                    dlg.Title  = "Save decrypted data";
                    dlg.Filter = "Text Files | *.txt";

                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        if (cbPurgeNonprint.Checked)
                        {
                            File.WriteAllText(dlg.FileName, string.Join("\n", rawSplit));
                        }
                        else
                        {
                            File.WriteAllText(dlg.FileName, output);
                        }
                    }
                }
            }
        }
        // Encrypt a file using a public key.
        private static void EncryptFile(string inFile, RSACryptoServiceProvider rsaPublicKey)
        {
            using (AesManaged aesManaged = new AesManaged())
            {
                // Create instance of AesManaged for
                // symetric encryption of the data.
                aesManaged.KeySize   = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode      = CipherMode.CBC;
                using (ICryptoTransform transform = aesManaged.CreateEncryptor())
                {
                    RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey);
                    byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());

                    // Create byte arrays to contain
                    // the length values of the key and IV.
                    byte[] LenK  = new byte[4];
                    byte[] LenIV = new byte[4];

                    int lKey = keyEncrypted.Length;
                    LenK = BitConverter.GetBytes(lKey);
                    int lIV = aesManaged.IV.Length;
                    LenIV = BitConverter.GetBytes(lIV);

                    // Write the following to the FileStream
                    // for the encrypted file (outFs):
                    // - length of the key
                    // - length of the IV
                    // - ecrypted key
                    // - the IV
                    // - the encrypted cipher content

                    int startFileName = inFile.LastIndexOf("\\") + 1;
                    // Change the file's extension to ".enc"
                    string outFile = encrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc";
                    Directory.CreateDirectory(encrFolder);

                    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                    {
                        outFs.Write(LenK, 0, 4);
                        outFs.Write(LenIV, 0, 4);
                        outFs.Write(keyEncrypted, 0, lKey);
                        outFs.Write(aesManaged.IV, 0, lIV);

                        // Now write the cipher text using
                        // a CryptoStream for encrypting.
                        using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                        {
                            // By encrypting a chunk at
                            // a time, you can save memory
                            // and accommodate large files.
                            int count  = 0;
                            int offset = 0;

                            // blockSizeBytes can be any arbitrary size.
                            int    blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data           = new byte[blockSizeBytes];
                            int    bytesRead      = 0;

                            using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                            {
                                do
                                {
                                    count   = inFs.Read(data, 0, blockSizeBytes);
                                    offset += count;
                                    outStreamEncrypted.Write(data, 0, count);
                                    bytesRead += blockSizeBytes;
                                }while (count > 0);
                                inFs.Close();
                            }
                            outStreamEncrypted.FlushFinalBlock();
                            outStreamEncrypted.Close();
                        }
                        outFs.Close();
                    }
                }
            }
        }
Example #58
0
    private static byte[] smethod_7(byte[] byte_4)
    {
        MemoryStream memoryStream = new MemoryStream();
        Rijndael     rijndael     = Rijndael.Create();

        rijndael.Key = new byte[]
        {
            173,
            252,
            249,
            34,
            206,
            132,
            37,
            109,
            113,
            148,
            24,
            40,
            128,
            101,
            148,
            26,
            50,
            53,
            56,
            156,
            220,
            29,
            181,
            38,
            18,
            105,
            32,
            76,
            23,
            54,
            177,
            3
        };
        rijndael.IV = new byte[]
        {
            47,
            50,
            96,
            233,
            111,
            135,
            254,
            42,
            193,
            86,
            233,
            212,
            46,
            97,
            105,
            63
        };
        CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);

        cryptoStream.Write(byte_4, 0, byte_4.Length);
        cryptoStream.Close();
        return(memoryStream.ToArray());
    }
Example #59
0
    static string smethod_1(int int_3)
    {
        if (Class14.byte_2.Length == 0)
        {
            BinaryReader binaryReader = new BinaryReader(typeof(Class14).Assembly.GetManifestResourceStream("15b96398-9597-4145-8e52-82e25906b4b2"));
            binaryReader.BaseStream.Position = 0L;
            byte[] array  = binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);
            byte[] array2 = new byte[32];
            array2[0]  = 126;
            array2[0]  = 124;
            array2[0]  = 146;
            array2[0]  = 48;
            array2[1]  = 152;
            array2[1]  = 88;
            array2[1]  = 254;
            array2[2]  = 96;
            array2[2]  = 27;
            array2[2]  = 244;
            array2[3]  = 102;
            array2[3]  = 110;
            array2[3]  = 124;
            array2[3]  = 140;
            array2[4]  = 98;
            array2[4]  = 152;
            array2[4]  = 174;
            array2[4]  = 128;
            array2[5]  = 185;
            array2[5]  = 85;
            array2[5]  = 173;
            array2[6]  = 69;
            array2[6]  = 147;
            array2[6]  = 87;
            array2[6]  = 86;
            array2[7]  = 130;
            array2[7]  = 124;
            array2[7]  = 101;
            array2[8]  = 109;
            array2[8]  = 134;
            array2[8]  = 157;
            array2[8]  = 243;
            array2[9]  = 132;
            array2[9]  = 86;
            array2[9]  = 47;
            array2[9]  = 101;
            array2[9]  = 197;
            array2[10] = 106;
            array2[10] = 135;
            array2[10] = 138;
            array2[10] = 182;
            array2[10] = 84;
            array2[10] = 214;
            array2[11] = 95;
            array2[11] = 140;
            array2[11] = 95;
            array2[11] = 92;
            array2[11] = 248;
            array2[12] = 157;
            array2[12] = 142;
            array2[12] = 11;
            array2[13] = 120;
            array2[13] = 62;
            array2[13] = 115;
            array2[13] = 138;
            array2[13] = 156;
            array2[13] = 145;
            array2[14] = 134;
            array2[14] = 138;
            array2[14] = 88;
            array2[14] = 164;
            array2[14] = 120;
            array2[14] = 105;
            array2[15] = 123;
            array2[15] = 112;
            array2[15] = 80;
            array2[15] = 122;
            array2[15] = 46;
            array2[16] = 165;
            array2[16] = 84;
            array2[16] = 132;
            array2[16] = 108;
            array2[16] = 108;
            array2[17] = 160;
            array2[17] = 143;
            array2[17] = 105;
            array2[17] = 94;
            array2[17] = 150;
            array2[17] = 166;
            array2[18] = 138;
            array2[18] = 90;
            array2[18] = 202;
            array2[19] = 162;
            array2[19] = 107;
            array2[19] = 186;
            array2[20] = 130;
            array2[20] = 128;
            array2[20] = 113;
            array2[20] = 148;
            array2[20] = 132;
            array2[20] = 165;
            array2[21] = 66;
            array2[21] = 171;
            array2[21] = 94;
            array2[21] = 194;
            array2[22] = 166;
            array2[22] = 155;
            array2[22] = 126;
            array2[22] = 121;
            array2[22] = 133;
            array2[22] = 14;
            array2[23] = 163;
            array2[23] = 106;
            array2[23] = 84;
            array2[23] = 195;
            array2[23] = 232;
            array2[24] = 154;
            array2[24] = 129;
            array2[24] = 142;
            array2[25] = 168;
            array2[25] = 153;
            array2[25] = 136;
            array2[25] = 94;
            array2[25] = 118;
            array2[25] = 131;
            array2[26] = 136;
            array2[26] = 102;
            array2[26] = 121;
            array2[27] = 150;
            array2[27] = 84;
            array2[27] = 102;
            array2[27] = 10;
            array2[28] = 141;
            array2[28] = 104;
            array2[28] = 120;
            array2[28] = 117;
            array2[29] = 145;
            array2[29] = 144;
            array2[29] = 85;
            array2[29] = 7;
            array2[30] = 84;
            array2[30] = 178;
            array2[30] = 157;
            array2[30] = 173;
            array2[30] = 88;
            array2[30] = 212;
            array2[31] = 75;
            array2[31] = 153;
            array2[31] = 139;
            byte[] rgbKey = array2;
            byte[] array3 = new byte[16];
            array3[0]  = 126;
            array3[0]  = 121;
            array3[0]  = 222;
            array3[1]  = 29;
            array3[1]  = 163;
            array3[1]  = 167;
            array3[1]  = 120;
            array3[1]  = 234;
            array3[2]  = 31;
            array3[2]  = 60;
            array3[2]  = 72;
            array3[3]  = 145;
            array3[3]  = 150;
            array3[3]  = 247;
            array3[4]  = 74;
            array3[4]  = 165;
            array3[4]  = 164;
            array3[5]  = 117;
            array3[5]  = 104;
            array3[5]  = 113;
            array3[5]  = 136;
            array3[5]  = 224;
            array3[6]  = 227;
            array3[6]  = 157;
            array3[6]  = 222;
            array3[6]  = 166;
            array3[6]  = 45;
            array3[7]  = 129;
            array3[7]  = 93;
            array3[7]  = 118;
            array3[7]  = 175;
            array3[7]  = 89;
            array3[7]  = 24;
            array3[8]  = 103;
            array3[8]  = 136;
            array3[8]  = 170;
            array3[8]  = 142;
            array3[9]  = 156;
            array3[9]  = 85;
            array3[9]  = 55;
            array3[9]  = 167;
            array3[9]  = 196;
            array3[9]  = 179;
            array3[10] = 104;
            array3[10] = 92;
            array3[10] = 147;
            array3[10] = 85;
            array3[10] = 219;
            array3[11] = 170;
            array3[11] = 192;
            array3[11] = 121;
            array3[11] = 140;
            array3[11] = 27;
            array3[12] = 122;
            array3[12] = 94;
            array3[12] = 108;
            array3[12] = 155;
            array3[13] = 75;
            array3[13] = 122;
            array3[13] = 49;
            array3[13] = 86;
            array3[13] = 120;
            array3[13] = 112;
            array3[14] = 156;
            array3[14] = 126;
            array3[14] = 90;
            array3[14] = 153;
            array3[14] = 170;
            array3[14] = 100;
            array3[15] = 205;
            array3[15] = 156;
            array3[15] = 212;
            array3[15] = 112;
            array3[15] = 136;
            byte[] array4         = array3;
            byte[] publicKeyToken = typeof(Class14).Assembly.GetName().GetPublicKeyToken();
            if (publicKeyToken != null && publicKeyToken.Length > 0)
            {
                array4[1]  = publicKeyToken[0];
                array4[3]  = publicKeyToken[1];
                array4[5]  = publicKeyToken[2];
                array4[7]  = publicKeyToken[3];
                array4[9]  = publicKeyToken[4];
                array4[11] = publicKeyToken[5];
                array4[13] = publicKeyToken[6];
                array4[15] = publicKeyToken[7];
            }
            ICryptoTransform transform = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            }.CreateDecryptor(rgbKey, array4);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(array, 0, array.Length);
            cryptoStream.FlushFinalBlock();
            Class14.byte_2 = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            binaryReader.Close();
        }
        int num = BitConverter.ToInt32(Class14.byte_2, int_3);

        try
        {
            byte[] array5 = new byte[num];
            Array.Copy(Class14.byte_2, int_3 + 4, array5, 0, num);
            return(Encoding.Unicode.GetString(array5, 0, array5.Length));
        }
        catch
        {
        }
        return("");
    }
Example #60
-1
        public static string Decrypt(string cipherText)
        {

            try
            {
                string EncryptionKey = "MAKV2SPBNI99212";
                cipherText = cipherText.Replace(" ", "+");
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return cipherText;
            }
            catch (Exception ex)
            {

                return "0";
            }
        }