Наследование: AsymmetricKeyExchangeDeformatter
        public byte[] Decrypt(byte[] rgb, bool fOAEP)
        {
            if (rgb == null)
            {
                throw new ArgumentNullException("rgb");
            }

            // size check -- must be at most the modulus size
            if (rgb.Length > (KeySize / 8))
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));
            }

            if (m_disposed)
            {
                throw new ObjectDisposedException("rsa");
            }
            // choose between OAEP or PKCS#1 v.1.5 padding
            AsymmetricKeyExchangeDeformatter def = null;

            if (fOAEP)
            {
                def = new RSAOAEPKeyExchangeDeformatter(rsa);
            }
            else
            {
                def = new RSAPKCS1KeyExchangeDeformatter(rsa);
            }

            return(def.DecryptKeyExchange(rgb));
        }
		public void Properties () 
		{
			RSAOAEPKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter ();
			keyex.SetKey (key);
			Assertion.AssertNull("RSAOAEPKeyExchangeDeformatter.Parameters", keyex.Parameters);
			Assertion.AssertEquals("RSAOAEPKeyExchangeDeformatter.ToString()", "System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter", keyex.ToString ());
		}
Пример #3
0
        /// <summary>
        /// Decrypt binary.
        /// </summary>
        /// <param name="binary">The data to encrypt.</param>
        /// <param name="privateKey">The private key.</param>
        /// <param name="symmetricAlgorithmName">Optional. The name of the symmetric algorithm to use. Defaults to "Rijndael" (128 bits AES). See http://msdn.microsoft.com/en-us/library/k74a682y(v=vs.100).aspx for a list of valid values.</param>
        /// <returns></returns>
        public static byte[] Decrypt(this byte[] binary, RSA privateKey, string symmetricAlgorithmName = "Rijndael")
        {
            if (binary == null) throw new ArgumentNullException("binary");
            if (privateKey == null) throw new ArgumentNullException("privateKey");

            //create sym key of given type
            var symmetricKey = SymmetricAlgorithm.Create(symmetricAlgorithmName);

            if(symmetricKey == null)
                throw new ArgumentException("Unsupported symmetricAlgorithmName: '{0}'".FormatWith(symmetricAlgorithmName), "symmetricAlgorithmName");

            //retrieve encrypted sym key
            var encryptedSymmetricKey = new byte[privateKey.KeySize >> 3];
            Buffer.BlockCopy(binary, 0, encryptedSymmetricKey, 0, encryptedSymmetricKey.Length);

            //decrypt sym key using asym key
            var key = new RSAOAEPKeyExchangeDeformatter(privateKey).DecryptKeyExchange(encryptedSymmetricKey);

            //get IV (public)
            var iv = new byte[symmetricKey.IV.Length];
            Buffer.BlockCopy(binary, encryptedSymmetricKey.Length, iv, 0, iv.Length);

            //decrypt binary using sym key and IV
            return symmetricKey.CreateDecryptor(key, iv).TransformFinalBlock(binary, encryptedSymmetricKey.Length + iv.Length, binary.Length - (encryptedSymmetricKey.Length + iv.Length));
        }
		public void Properties () 
		{
			RSAOAEPKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter ();
			keyex.SetKey (key);
			Assert.IsNull (keyex.Parameters, "RSAOAEPKeyExchangeDeformatter.Parameters");
			Assert.AreEqual("System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter", keyex.ToString ());
		}
		public void ExchangeMin() 
		{
			AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter (key);
			byte[] M = { 0x01 };
			try {
				byte[] EM = keyex.CreateKeyExchange (M);
				AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter Min", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
		public void CapiExchangeMin () 
		{
			byte[] M = { 0x01 };
			byte[] EM = { 0x4D, 0x5F, 0x26, 0x67, 0x88, 0x07, 0xF1, 0xB5, 0x85, 0x33, 0xDA, 0x8B, 0xD6, 0x9E, 0x9B, 0x56, 0xE6, 0x54, 0x49, 0xF3, 0x4A, 0x8B, 0x5B, 0xB2, 0xCB, 0x10, 0x50, 0x91, 0x85, 0xBC, 0xE1, 0x5E, 0xDC, 0x8A, 0xAE, 0x63, 0xAD, 0x57, 0xC3, 0x03, 0x78, 0xDD, 0xCE, 0xCD, 0x46, 0x71, 0x43, 0x2F, 0x7F, 0xA4, 0x6A, 0x93, 0xE4, 0xB7, 0x4C, 0x36, 0x92, 0x5C, 0xFF, 0xAC, 0x32, 0xE8, 0x71, 0x1E, 0x69, 0xD6, 0x8C, 0xB5, 0x65, 0xA5, 0x83, 0xC2, 0x3F, 0xED, 0x35, 0x6F, 0x03, 0x0D, 0x4B, 0xE1, 0x0F, 0x7B, 0x5D, 0x0A, 0x68, 0x90, 0x71, 0xA0, 0xD6, 0xC0, 0xEC, 0x6B, 0x24, 0x45, 0x3D, 0x9C, 0x11, 0xD9, 0xC8, 0xFB, 0xC8, 0x8F, 0xDB, 0x48, 0x70, 0x1F, 0xC4, 0x7D, 0x83, 0x58, 0x95, 0xDC, 0x36, 0xA0, 0x68, 0xE1, 0xCF, 0x2D, 0xA9, 0x8A, 0xF0, 0xB8, 0xA6, 0x0D, 0x6E, 0xA6, 0x9C, 0xBC };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeDeformatter 1", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
        /// <summary>Decrypts data with the <see cref="T:System.Security.Cryptography.RSA" /> algorithm.</summary>
        /// <returns>The decrypted data, which is the original plain text before encryption.</returns>
        /// <param name="rgb">The data to be decrypted. </param>
        /// <param name="fOAEP">true to perform direct <see cref="T:System.Security.Cryptography.RSA" /> decryption using OAEP padding (only available on a computer running Microsoft Windows XP or later); otherwise, false to use PKCS#1 v1.5 padding. </param>
        /// <exception cref="T:System.Security.Cryptography.CryptographicException">The cryptographic service provider (CSP) cannot be acquired.-or- The <paramref name="fOAEP" /> parameter is true and the length of the <paramref name="rgb" /> parameter is greater than <see cref="P:System.Security.Cryptography.RSACryptoServiceProvider.KeySize" />.-or- The <paramref name="fOAEP" /> parameter is true and OAEP is not supported. </exception>
        /// <exception cref="T:System.ArgumentNullException">
        ///   <paramref name="rgb " />is null.</exception>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.KeyContainerPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" />
        /// </PermissionSet>
        public byte[] Decrypt(byte[] rgb, bool fOAEP)
        {
            if (this.m_disposed)
            {
                throw new ObjectDisposedException("rsa");
            }
            AsymmetricKeyExchangeDeformatter asymmetricKeyExchangeDeformatter;

            if (fOAEP)
            {
                asymmetricKeyExchangeDeformatter = new RSAOAEPKeyExchangeDeformatter(this.rsa);
            }
            else
            {
                asymmetricKeyExchangeDeformatter = new RSAPKCS1KeyExchangeDeformatter(this.rsa);
            }
            return(asymmetricKeyExchangeDeformatter.DecryptKeyExchange(rgb));
        }
Пример #8
0
        public byte[] Decrypt(byte[] rgb, bool fOAEP)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("rsa");
            }
            // choose between OAEP or PKCS#1 v.1.5 padding
            AsymmetricKeyExchangeDeformatter def = null;

            if (fOAEP)
            {
                def = new RSAOAEPKeyExchangeDeformatter(rsa);
            }
            else
            {
                def = new RSAPKCS1KeyExchangeDeformatter(rsa);
            }

            return(def.DecryptKeyExchange(rgb));
        }
		public void ExchangeTooBig() 
		{
			AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (key);
			byte[] EM = new byte [(key.KeySize >> 3) + 1];
			// invalid format
			byte[] M = keyex.DecryptKeyExchange (EM);
		}
		public void MonoExchangeMax() 
		{
			byte[] M = new byte [(key.KeySize >> 3) - 2 * 20 - 2];
			byte[] EM = { 0x6C, 0x3E, 0x71, 0x14, 0xAD, 0xDE, 0x46, 0x26, 0x42, 0xA8, 0x84, 0x40, 0xCC, 0x06, 0x73, 0xCC, 0x88, 0x76, 0x40, 0x08, 0x93, 0xE5, 0x5F, 0xFF, 0x7D, 0x02, 0x88, 0xE9, 0x2D, 0xF6, 0x90, 0xA1, 0x8F, 0x64, 0x9A, 0x79, 0x67, 0x63, 0xA5, 0xBE, 0xCE, 0x7F, 0x48, 0x65, 0x8F, 0x53, 0x24, 0x70, 0x4F, 0x2A, 0x61, 0x7C, 0x95, 0xB6, 0xD0, 0x1D, 0x6F, 0x92, 0xA5, 0x2B, 0xB9, 0x13, 0x6B, 0xD2, 0xEB, 0x1D, 0x4F, 0x1E, 0x51, 0x6D, 0x65, 0xA6, 0x97, 0xE8, 0x60, 0x4B, 0x19, 0xE4, 0x23, 0xDC, 0x22, 0xED, 0x23, 0x02, 0x5E, 0x0C, 0x0B, 0x99, 0x5D, 0xBA, 0xFC, 0xBD, 0x75, 0x2F, 0x3E, 0xCD, 0x33, 0xBF, 0x08, 0xD5, 0x31, 0x68, 0x7C, 0x51, 0x2E, 0xBF, 0x8A, 0xBF, 0xA9, 0x8F, 0x0A, 0xDF, 0xB0, 0x91, 0xB1, 0x95, 0x03, 0x37, 0x3C, 0x77, 0x61, 0x75, 0x06, 0x61, 0xD8, 0x94, 0x04, 0x42 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter Max", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
		public void MonoExchange192() 
		{
			byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49, 0x00, 0x00, 0x00, 0x00 };
			byte[] EM = { 0xAD, 0xFA, 0x95, 0x2E, 0xCE, 0x23, 0xBE, 0xA5, 0x77, 0x81, 0x34, 0x98, 0x64, 0x58, 0x02, 0xAB, 0x62, 0x28, 0x97, 0x84, 0x6D, 0xF3, 0xE1, 0x9D, 0xB2, 0x04, 0xA8, 0xB0, 0x1D, 0x48, 0xFC, 0x94, 0x1A, 0x3A, 0xB1, 0x72, 0x39, 0xE1, 0xFE, 0x25, 0xF6, 0x6E, 0x64, 0xA5, 0x84, 0xA3, 0x2F, 0x3D, 0x49, 0x4F, 0x7F, 0xD1, 0x45, 0x74, 0xFB, 0x42, 0x6F, 0x50, 0x5C, 0x19, 0x44, 0xB8, 0x0F, 0x3B, 0x31, 0x94, 0x8E, 0xC2, 0x44, 0x47, 0xA2, 0xE9, 0x6E, 0x7F, 0x58, 0x49, 0x38, 0xB9, 0x2C, 0xB8, 0x0E, 0xA9, 0x7A, 0x86, 0x2B, 0xDB, 0xED, 0x5A, 0x16, 0x48, 0x41, 0x84, 0x3B, 0xE3, 0xA8, 0x26, 0x01, 0xAE, 0x09, 0x41, 0xB3, 0x95, 0xC5, 0xA4, 0x5A, 0x82, 0xC3, 0x37, 0x57, 0xD9, 0x03, 0x53, 0x8D, 0x28, 0x24, 0xA4, 0x37, 0x2A, 0xA9, 0xC7, 0x66, 0xAD, 0xAC, 0x5F, 0x3A, 0xF0, 0xE5, 0x90 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 192", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
		public void MonoExchange128() 
		{
			byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 };
			byte[] EM = { 0x3A, 0x18, 0xE7, 0xF7, 0x45, 0x32, 0x5B, 0x60, 0x46, 0x2A, 0x20, 0x1A, 0x69, 0x98, 0x84, 0x68, 0x76, 0xC0, 0x01, 0x7D, 0x37, 0xE7, 0xEB, 0x72, 0x18, 0xD7, 0xF3, 0xE5, 0x1B, 0x2C, 0xB2, 0x47, 0x86, 0x9D, 0x90, 0xE8, 0x38, 0x43, 0x0C, 0x58, 0x59, 0xDB, 0x2A, 0x46, 0xBA, 0x15, 0xD9, 0x79, 0x77, 0xB5, 0x8B, 0xA7, 0x06, 0x15, 0xE1, 0xBF, 0xA2, 0xA7, 0x69, 0xC6, 0x6A, 0x6C, 0x4F, 0x87, 0xA3, 0xA1, 0xBC, 0x21, 0x46, 0x68, 0x61, 0xEC, 0x1E, 0xE1, 0x2B, 0xEF, 0xD7, 0xE0, 0x61, 0xAF, 0xF5, 0xDA, 0x27, 0xCB, 0xFC, 0x98, 0x0C, 0x12, 0x59, 0x45, 0x64, 0x75, 0x58, 0xB5, 0x5B, 0x7A, 0x9B, 0x76, 0x68, 0x14, 0x9F, 0xAB, 0x64, 0xC7, 0x4E, 0xB7, 0xFF, 0x7D, 0x3D, 0xA3, 0x11, 0x9E, 0xE8, 0x06, 0xAF, 0x5D, 0xA3, 0xEB, 0x8E, 0x1E, 0x38, 0x5D, 0x0D, 0xC3, 0x8C, 0xC3, 0xF0, 0x57 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 128", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
Пример #13
0
		public static byte[] DecryptKey (byte[] keyData, RSA rsa, bool fOAEP)
		{
			AsymmetricKeyExchangeDeformatter deformatter = null;
			if (fOAEP) 
				deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
			else
				deformatter = new RSAPKCS1KeyExchangeDeformatter (rsa);
			return deformatter.DecryptKeyExchange (keyData);
		}
		public void Exchange128() 
		{
			AsymmetricKeyExchangeFormatter keyex = new RSAOAEPKeyExchangeFormatter (key);
			byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 };
			try {
				byte[] EM = keyex.CreateKeyExchange (M, typeof (Rijndael));
				AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 128", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
		public void ExchangeDSAKey () 
		{
			DSA dsa = DSA.Create ();
			AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (dsa);
		}
		public void CapiExchange128 () 
		{
			byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 };
			byte[] EM = { 0x6D, 0xAA, 0xBC, 0x7C, 0xE7, 0x7C, 0xE6, 0x16, 0x72, 0x6F, 0xBE, 0xAF, 0x26, 0xBF, 0x87, 0x77, 0xB5, 0x47, 0x25, 0x37, 0x01, 0xC7, 0xD8, 0x18, 0xA8, 0x09, 0x0F, 0x1F, 0x13, 0x24, 0xD0, 0x2A, 0xD4, 0xDC, 0x5A, 0x2D, 0x91, 0x6D, 0x11, 0x6C, 0x1A, 0x67, 0xB2, 0xFC, 0xA3, 0xE7, 0xF4, 0xEF, 0xDC, 0xEC, 0xB2, 0xAF, 0x42, 0xB5, 0xD9, 0x7A, 0x6D, 0xE5, 0x76, 0xBA, 0x7D, 0x04, 0xCA, 0x17, 0xB0, 0x06, 0x88, 0x4D, 0xE8, 0xCC, 0x82, 0xEA, 0x13, 0xC8, 0x12, 0x05, 0x05, 0xC6, 0xB0, 0x4B, 0x53, 0x1D, 0x07, 0xFA, 0x09, 0x64, 0x30, 0xCD, 0x5C, 0xE3, 0x41, 0xB1, 0x25, 0x94, 0x05, 0x5A, 0xC2, 0xD8, 0x2E, 0xC4, 0x39, 0x51, 0x73, 0x75, 0x0C, 0x4B, 0x2F, 0x4B, 0xAD, 0x04, 0x54, 0x32, 0x30, 0x94, 0xF4, 0xFE, 0x92, 0xF4, 0xB4, 0x54, 0x07, 0x22, 0xCD, 0xB5, 0xB2, 0x01, 0x95, 0xA0 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
Пример #17
0
		public byte[] Decrypt (byte[] rgb, bool fOAEP) 
		{
			if (rgb == null)
				throw new ArgumentNullException("rgb");

			// size check -- must be at most the modulus size
			if (rgb.Length > (KeySize / 8))
				throw new CryptographicException(Environment.GetResourceString("Cryptography_Padding_DecDataTooBig", KeySize / 8));
			
			if (m_disposed)
				throw new ObjectDisposedException ("rsa");
			// choose between OAEP or PKCS#1 v.1.5 padding
			AsymmetricKeyExchangeDeformatter def = null;
			if (fOAEP)
				def = new RSAOAEPKeyExchangeDeformatter (rsa);
			else
				def = new RSAPKCS1KeyExchangeDeformatter (rsa);

			return def.DecryptKeyExchange (rgb);
		}
        /// <summary>
        /// Decrypts the symmetric key.
        /// </summary>
        /// <param name="cert">The cert.</param>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <returns>The decrypted key.</returns>
        public static byte[] DecryptSymmetricKey(X509Certificate2 cert, byte[] encryptedData)
        {
            AsymmetricAlgorithm rsaPrivateKey = null;
            RSAOAEPKeyExchangeDeformatter keyFormatter = null;

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            if (!cert.HasPrivateKey)
            {
                throw new ArgumentException("Certificate does not have a private key which is a requirment for decryption.", "cert");
            }

            try
            {
                rsaPrivateKey = cert.PrivateKey;
            }
            catch (CryptographicException ce)
            {
                if (ce.Message.Contains("Keyset does not exist"))
                {
                    IdentityReference currentUser = WindowsIdentity.GetCurrent().Owner as IdentityReference;
                    string message = string.Format(CultureInfo.CurrentCulture, "Unable to create the RSAOAEPKeyExchangeDeformatter likely due to the access permissions on the private key.  Check to see if the current user has access to the private key for the certificate with thumbprint={0}.  Current User is {1}.", cert.Thumbprint, currentUser.ToString());
                    throw new InvalidOperationException(message, ce);
                }
                else
                {
                    throw;
                }
            }

            keyFormatter = new RSAOAEPKeyExchangeDeformatter(rsaPrivateKey);

            return keyFormatter.DecryptKeyExchange(encryptedData);
        }
Пример #19
0
        // decrypts the supplied data using an RSA key and specifies whether we want to use OAEP 
        // padding or PKCS#1 v1.5 padding as described in the PKCS specification
        public static byte[] DecryptKey (byte[] keyData, RSA rsa, bool useOAEP) {
            if (keyData == null)
                throw new ArgumentNullException("keyData");
            if (rsa == null)
                throw new ArgumentNullException("rsa");

            if (useOAEP) {
                RSAOAEPKeyExchangeDeformatter rsaDeformatter = new RSAOAEPKeyExchangeDeformatter(rsa);
                return rsaDeformatter.DecryptKeyExchange(keyData);
            } else {
                RSAPKCS1KeyExchangeDeformatter rsaDeformatter = new RSAPKCS1KeyExchangeDeformatter(rsa);
                return rsaDeformatter.DecryptKeyExchange(keyData);
            }
        }
Пример #20
0
        static void HandleConnection(System.IO.DirectoryInfo info, TcpClient client)
        {
            Area ws = null;
            ClientStateInfo clientInfo = new ClientStateInfo();
            using (client)
            using (SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo())
            {
                try
                {
                    var stream = client.GetStream();
                    Handshake hs = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Handshake>(stream, ProtoBuf.PrefixStyle.Fixed32);
                    DomainInfo domainInfo = null;
                    lock (SyncObject)
                    {
                        if (hs.RequestedModule == null)
                            hs.RequestedModule = string.Empty;
                        if (!Domains.TryGetValue(hs.RequestedModule, out domainInfo))
                        {
                            domainInfo = Domains.Where(x => x.Key.Equals(hs.RequestedModule, StringComparison.OrdinalIgnoreCase)).Select(x => x.Value).FirstOrDefault();
                        }
                        if (domainInfo == null)
                        {
                            if (!Config.AllowVaultCreation || !Config.RequiresAuthentication || string.IsNullOrEmpty(hs.RequestedModule) || System.IO.Directory.Exists(System.IO.Path.Combine(info.FullName, hs.RequestedModule)))
                            {
                                Network.StartTransaction startSequence = Network.StartTransaction.CreateRejection();
                                Printer.PrintDiagnostics("Rejecting client due to invalid domain: \"{0}\".", hs.RequestedModule);
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                                return;
                            }
                            domainInfo = new DomainInfo()
                            {
                                Bare = true,
                                Directory = null
                            };
                        }
                    }
                    try
                    {
                        ws = Area.Load(domainInfo.Directory, true, true);
                        if (domainInfo.Bare)
                            throw new Exception("Domain is bare, but workspace could be loaded!");
                    }
                    catch
                    {
                        if (!domainInfo.Bare)
                            throw new Exception("Domain not bare, but couldn't load workspace!");
                    }
                    Printer.PrintDiagnostics("Received handshake - protocol: {0}", hs.VersionrProtocol);
                    SharedNetwork.Protocol? clientProtocol = hs.CheckProtocol();
                    bool valid = true;
                    if (clientProtocol == null)
                        valid = false;
                    else
                    {
                        valid = SharedNetwork.AllowedProtocols.Contains(clientProtocol.Value);
                        if (Config.RequiresAuthentication && !SharedNetwork.SupportsAuthentication(clientProtocol.Value))
                            valid = false;
                    }
                    if (valid)
                    {
                        sharedInfo.CommunicationProtocol = clientProtocol.Value;
                        Network.StartTransaction startSequence = null;
                        clientInfo.Access = Rights.Read | Rights.Write;
                        clientInfo.BareAccessRequired = domainInfo.Bare;
                        if (PrivateKey != null)
                        {
                            startSequence = Network.StartTransaction.Create(domainInfo.Bare ? string.Empty : ws.Domain.ToString(), PublicKey, clientProtocol.Value);
                            Printer.PrintDiagnostics("Sending RSA key...");
                            ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                            if (!HandleAuthentication(clientInfo, client, sharedInfo))
                                throw new Exception("Authentication failed.");
                            StartClientTransaction clientKey = ProtoBuf.Serializer.DeserializeWithLengthPrefix<StartClientTransaction>(stream, ProtoBuf.PrefixStyle.Fixed32);
                            System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter exch = new System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter(PrivateKey);
                            byte[] aesKey = exch.DecryptKeyExchange(clientKey.Key);
                            byte[] aesIV = exch.DecryptKeyExchange(clientKey.IV);
                            Printer.PrintDiagnostics("Got client key: {0}", System.Convert.ToBase64String(aesKey));

                            var aesCSP = System.Security.Cryptography.AesManaged.Create();

                            sharedInfo.DecryptorFunction = () => { return aesCSP.CreateDecryptor(aesKey, aesIV); };
                            sharedInfo.EncryptorFunction = () => { return aesCSP.CreateEncryptor(aesKey, aesIV); };
                        }
                        else
                        {
                            startSequence = Network.StartTransaction.Create(domainInfo.Bare ? string.Empty : ws.Domain.ToString(), clientProtocol.Value);
                            ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                            if (!HandleAuthentication(clientInfo, client, sharedInfo))
                                throw new Exception("Authentication failed.");
                            StartClientTransaction clientKey = ProtoBuf.Serializer.DeserializeWithLengthPrefix<StartClientTransaction>(stream, ProtoBuf.PrefixStyle.Fixed32);
                        }
                        sharedInfo.Stream = stream;
                        sharedInfo.Workspace = ws;
                        sharedInfo.ChecksumType = Config.ChecksumType;

                        clientInfo.SharedInfo = sharedInfo;

                        while (true)
                        {
                            NetCommand command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(stream, ProtoBuf.PrefixStyle.Fixed32);
                            if (command.Type == NetCommandType.Close)
                            {
                                Printer.PrintDiagnostics("Client closing connection.");
                                break;
                            }
                            else if (command.Type == NetCommandType.PushInitialVersion)
                            {
                                bool fresh = false;
                                if (domainInfo.Directory == null)
                                {
                                    if (!clientInfo.Access.HasFlag(Rights.Create))
                                        throw new Exception("Access denied.");
                                    fresh = true;
                                    System.IO.DirectoryInfo newDirectory = new System.IO.DirectoryInfo(System.IO.Path.Combine(info.FullName, hs.RequestedModule));
                                    newDirectory.Create();
                                    domainInfo.Directory = newDirectory;
                                    if (!newDirectory.Exists)
                                        throw new Exception("Access denied.");
                                }
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                lock (SyncObject)
                                {
                                    ws = Area.InitRemote(domainInfo.Directory, Utilities.ReceiveEncrypted<ClonePayload>(clientInfo.SharedInfo));
                                    clientInfo.SharedInfo.Workspace = ws;
                                    domainInfo.Bare = false;
                                    if (fresh)
                                        Domains[hs.RequestedModule] = domainInfo;
                                }
                            }
                            else if (command.Type == NetCommandType.PushBranchJournal)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                SharedNetwork.ReceiveBranchJournal(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.QueryBranchID)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting a branch info for {0}", string.IsNullOrEmpty(command.AdditionalPayload) ? "<root>" : "\"" + command.AdditionalPayload + "\"");
                                bool multiple = false;
                                Objects.Branch branch = string.IsNullOrEmpty(command.AdditionalPayload) ? ws.RootBranch : ws.GetBranchByPartialName(command.AdditionalPayload, out multiple);
                                if (branch != null)
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge, AdditionalPayload = branch.ID.ToString() }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                                else if (!multiple)
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = "branch not recognized" }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                                else
                                {
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = "multiple branches with that name!" }, ProtoBuf.PrefixStyle.Fixed32);
                                }
                            }
                            else if (command.Type == NetCommandType.ListBranches)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting a branch list.");
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Identifier == 1) // send extra data
                                {
                                    BranchList bl = new BranchList();
                                    bl.Branches = clientInfo.SharedInfo.Workspace.Branches.ToArray();
                                    Dictionary<Guid, Objects.Version> importantVersions = new Dictionary<Guid, Objects.Version>();
                                    List<KeyValuePair<Guid, Guid>> allHeads = new List<KeyValuePair<Guid, Guid>>();
                                    foreach (var x in bl.Branches)
                                    {
                                        if (x.Terminus.HasValue && !importantVersions.ContainsKey(x.Terminus.Value))
                                        {
                                            importantVersions[x.Terminus.Value] = clientInfo.SharedInfo.Workspace.GetVersion(x.Terminus.Value);
                                            continue;
                                        }
                                        var heads = clientInfo.SharedInfo.Workspace.GetBranchHeads(x);
                                        foreach (var head in heads)
                                        {
                                            if (!importantVersions.ContainsKey(head.Version))
                                                importantVersions[head.Version] = clientInfo.SharedInfo.Workspace.GetVersion(head.Version);
                                        }
                                        allHeads.AddRange(heads.Select(y => new KeyValuePair<Guid, Guid>(y.Branch, y.Version)));
                                    }
                                    bl.Heads = allHeads.ToArray();
                                    bl.ImportantVersions = importantVersions.Values.ToArray();
                                    Utilities.SendEncrypted<BranchList>(clientInfo.SharedInfo, bl);
                                }
                                else
                                {
                                    BranchList bl = new BranchList();
                                    bl.Branches = clientInfo.SharedInfo.Workspace.Branches.ToArray();
                                    List<KeyValuePair<Guid, Guid>> allHeads = new List<KeyValuePair<Guid, Guid>>();
                                    foreach (var x in bl.Branches)
                                    {
                                        if (x.Terminus.HasValue)
                                            continue;
                                        var heads = clientInfo.SharedInfo.Workspace.GetBranchHeads(x);
                                        if (heads.Count == 1)
                                            allHeads.Add(new KeyValuePair<Guid, Guid>(x.ID, heads[0].Version));
                                    }
                                    bl.Heads = allHeads.ToArray();
                                    Utilities.SendEncrypted<BranchList>(clientInfo.SharedInfo, bl);
                                }
                            }
                            else if (command.Type == NetCommandType.RequestRecordUnmapped)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting specific record data blobs.");
                                SharedNetwork.SendRecordDataUnmapped(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.Clone)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client is requesting to clone the vault.");
                                Objects.Version initialRevision = ws.GetVersion(ws.Domain);
                                Objects.Branch initialBranch = ws.GetBranch(initialRevision.Branch);
                                Utilities.SendEncrypted<ClonePayload>(sharedInfo, new ClonePayload() { InitialBranch = initialBranch, RootVersion = initialRevision });
                            }
                            else if (command.Type == NetCommandType.PullVersions)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client asking for remote version information.");
                                Branch branch = ws.GetBranch(new Guid(command.AdditionalPayload));
                                if (branch == null)
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error, AdditionalPayload = string.Format("Unknown branch {0}", command.AdditionalPayload) }, ProtoBuf.PrefixStyle.Fixed32);
                                else
                                    ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                Stack<Objects.Branch> branchesToSend = new Stack<Branch>();
                                Stack<Objects.Version> versionsToSend = new Stack<Objects.Version>();
                                if (!SharedNetwork.SendBranchJournal(sharedInfo))
                                    throw new Exception();
                                if (!SharedNetwork.GetVersionList(sharedInfo, sharedInfo.Workspace.GetBranchHeadVersion(branch), out branchesToSend, out versionsToSend))
                                    throw new Exception();
                                if (!SharedNetwork.SendBranches(sharedInfo, branchesToSend))
                                    throw new Exception();
                                if (!SharedNetwork.SendVersions(sharedInfo, versionsToSend))
                                    throw new Exception();
                            }
                            else if (command.Type == NetCommandType.PushObjectQuery)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client asking about objects on the server...");
                                SharedNetwork.ProcesPushObjectQuery(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushBranch)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client attempting to send branch data...");
                                SharedNetwork.ReceiveBranches(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushVersions)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Client attempting to send version data...");
                                SharedNetwork.ReceiveVersions(sharedInfo);
                            }
                            else if (command.Type == NetCommandType.PushHead)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Write))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Determining head information.");
                                string errorData;
                                lock (ws)
                                {
                                    clientInfo.SharedInfo.Workspace.RunLocked(() =>
                                    {
                                        try
                                        {
                                            clientInfo.SharedInfo.Workspace.BeginDatabaseTransaction();
                                            if (!SharedNetwork.ImportBranchJournal(clientInfo.SharedInfo, false))
                                            {
                                                clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                                return false;
                                            }
                                            if (AcceptHeads(clientInfo, ws, out errorData))
                                            {
                                                ImportVersions(ws, clientInfo);
                                                clientInfo.SharedInfo.Workspace.CommitDatabaseTransaction();
                                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.AcceptPush }, ProtoBuf.PrefixStyle.Fixed32);
                                                return true;
                                            }
                                            else
                                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.RejectPush, AdditionalPayload = errorData }, ProtoBuf.PrefixStyle.Fixed32);
                                            clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                            return false;
                                        }
                                        catch
                                        {
                                            clientInfo.SharedInfo.Workspace.RollbackDatabaseTransaction();
                                            return false;
                                        }
                                    }, false);
                                }
                            }
                            else if (command.Type == NetCommandType.SynchronizeRecords)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                Printer.PrintDiagnostics("Received {0} versions in version pack, but need {1} records to commit data.", sharedInfo.PushedVersions.Count, sharedInfo.UnknownRecords.Count);
                                Printer.PrintDiagnostics("Beginning record synchronization...");
                                if (sharedInfo.UnknownRecords.Count > 0)
                                {
                                    Printer.PrintDiagnostics("Requesting record metadata...");
                                    SharedNetwork.RequestRecordMetadata(clientInfo.SharedInfo);
                                    Printer.PrintDiagnostics("Requesting record data...");
                                    SharedNetwork.RequestRecordData(sharedInfo);
                                    if (!sharedInfo.Workspace.RunLocked(() =>
                                    {
                                        return SharedNetwork.ImportRecords(sharedInfo);
                                    }, false))
                                    {
                                        throw new Exception("Unable to import records!");
                                    }
                                }
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Synchronized }, ProtoBuf.PrefixStyle.Fixed32);
                            }
                            else if (command.Type == NetCommandType.FullClone)
                            {
                                if (!clientInfo.Access.HasFlag(Rights.Read))
                                    throw new Exception("Access denied.");
                                ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge, Identifier = (int)ws.DatabaseVersion }, ProtoBuf.PrefixStyle.Fixed32);
                                command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(stream, ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Type == NetCommandType.Acknowledge)
                                {
                                    bool accept = false;
                                    BackupInfo backupInfo = null;
                                    lock (domainInfo)
                                    {
                                        string backupKey = ws.LastVersion + "-" + ws.LastBranch + "-" + ws.BranchJournalTipID.ToString();
                                        backupInfo = domainInfo.Backup;
                                        if (backupKey != backupInfo.Key)
                                        {
                                            Printer.PrintMessage("Backup key out of date for domain DB[{0}] - {1}", domainInfo.Directory, backupKey);
                                            if (System.Threading.Interlocked.Decrement(ref backupInfo.Refs) == 0)
                                                backupInfo.Backup.Delete();
                                            backupInfo = new BackupInfo();
                                            domainInfo.Backup = backupInfo;
                                            var directory = new System.IO.DirectoryInfo(System.IO.Path.Combine(ws.AdministrationFolder.FullName, "backups"));
                                            directory.Create();
                                            backupInfo.Backup = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, System.IO.Path.GetRandomFileName()));
                                            if (ws.BackupDB(backupInfo.Backup))
                                            {
                                                System.Threading.Interlocked.Increment(ref backupInfo.Refs);
                                                accept = true;
                                                backupInfo.Key = backupKey;
                                            }
                                        }
                                        else
                                        {
                                            accept = true;
                                        }

                                        if (accept)
                                            System.Threading.Interlocked.Increment(ref backupInfo.Refs);
                                    }
                                    if (accept)
                                    {
                                        Printer.PrintDiagnostics("Backup complete. Sending data.");
                                        byte[] blob = new byte[256 * 1024];
                                        long filesize = backupInfo.Backup.Length;
                                        long position = 0;
                                        using (System.IO.FileStream reader = backupInfo.Backup.OpenRead())
                                        {
                                            while (true)
                                            {
                                                long remainder = filesize - position;
                                                int count = blob.Length;
                                                if (count > remainder)
                                                    count = (int)remainder;
                                                reader.Read(blob, 0, count);
                                                position += count;
                                                Printer.PrintDiagnostics("Sent {0}/{1} bytes.", position, filesize);
                                                if (count == remainder)
                                                {
                                                    Utilities.SendEncrypted(sharedInfo, new DataPayload()
                                                    {
                                                        Data = blob.Take(count).ToArray(),
                                                        EndOfStream = true
                                                    });
                                                    break;
                                                }
                                                else
                                                {
                                                    Utilities.SendEncrypted(sharedInfo, new DataPayload()
                                                    {
                                                        Data = blob,
                                                        EndOfStream = false
                                                    });
                                                }
                                            }
                                        }
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Acknowledge }, ProtoBuf.PrefixStyle.Fixed32);
                                        lock (domainInfo)
                                        {
                                            if (System.Threading.Interlocked.Decrement(ref backupInfo.Refs) == 0)
                                                backupInfo.Backup.Delete();
                                        }
                                    }
                                    else
                                    {
                                        Utilities.SendEncrypted<DataPayload>(sharedInfo, new DataPayload() { Data = new byte[0], EndOfStream = true });
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix<NetCommand>(stream, new NetCommand() { Type = NetCommandType.Error }, ProtoBuf.PrefixStyle.Fixed32);
                                    }
                                }
                            }
                            else
                            {
                                Printer.PrintDiagnostics("Client sent invalid command: {0}", command.Type);
                                throw new Exception();
                            }
                        }
                    }
                    else
                    {
                        Network.StartTransaction startSequence = Network.StartTransaction.CreateRejection();
                        Printer.PrintDiagnostics("Rejecting client due to protocol mismatch.");
                        ProtoBuf.Serializer.SerializeWithLengthPrefix<Network.StartTransaction>(stream, startSequence, ProtoBuf.PrefixStyle.Fixed32);
                        return;
                    }
                }
                catch (Exception e)
                {
                    Printer.PrintDiagnostics("Client was a terrible person, because: {0}", e);
                }
                finally
                {
                    if (ws != null)
                        ws.Dispose();
                }
            }

            Printer.PrintDiagnostics("Ended client processor task!");
        }
Пример #21
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 (Locale.GetText ("Invalid data."));
			}
			return decdata;
		}
		public void Parameters () 
		{
			RSAOAEPKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter (key);
			keyex.Parameters = "Mono";
			AssertNull ("Parameters", keyex.Parameters);
		}
		public void ExchangeNoKey () 
		{
			AsymmetricKeyExchangeDeformatter keyex = new RSAOAEPKeyExchangeDeformatter ();
			byte[] M = keyex.DecryptKeyExchange (new byte [(key.KeySize >> 3) - 2 * 20 - 2]);
		}
		public void CapiExchangeMax () 
		{
			byte[] M = new byte [(key.KeySize >> 3) - 2 * 20 - 2];
			byte[] EM = { 0x45, 0x31, 0xA7, 0x4A, 0xE5, 0x8B, 0xC7, 0x0C, 0x5C, 0x8B, 0xE6, 0xAB, 0xC5, 0x99, 0xF3, 0x31, 0xB9, 0x64, 0xFA, 0x19, 0x4A, 0x41, 0xF3, 0x49, 0x05, 0x0B, 0x28, 0xD5, 0x96, 0x43, 0x0E, 0xEB, 0x62, 0x0B, 0x22, 0xFE, 0x5F, 0x92, 0x4F, 0x60, 0xB9, 0xAE, 0x7F, 0xAA, 0xC8, 0x82, 0x66, 0xD7, 0x19, 0xCF, 0xC0, 0x69, 0x1C, 0xAA, 0x7E, 0x95, 0x5D, 0x70, 0x3D, 0x4A, 0x1D, 0x3B, 0x55, 0xBC, 0x7D, 0x36, 0xCF, 0x98, 0x09, 0xF8, 0x20, 0x92, 0x34, 0x79, 0x0B, 0x1A, 0x91, 0xE5, 0xFB, 0x94, 0xAD, 0x2A, 0x15, 0x6E, 0x3D, 0xF4, 0xA5, 0x6F, 0x6B, 0xAE, 0x77, 0x80, 0x3C, 0xF5, 0xCC, 0x84, 0x3A, 0xF9, 0xCE, 0x9F, 0x06, 0xF6, 0xCC, 0xA8, 0x75, 0xE1, 0x55, 0x56, 0xA5, 0x76, 0x50, 0x28, 0xA7, 0x3E, 0x91, 0x11, 0x5C, 0x82, 0x7C, 0x1A, 0x92, 0x02, 0x74, 0xCC, 0xA9, 0x6C, 0xFC, 0xA4 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
		public void Bug79320 ()
		{
			string s = "hdphq/mn8goBi43YGPkmOfPj5vXjHrKPJkT4mLT3l+XzLttHMLC4/yBYkuzlXtbrl2jtAJRb6oA8UcQFalUMnCa09LDZrgNU2yySn7YbiG8raSq7u2nfDCbPu+c8T9fyHxrCHrX0zeqqImX33csIn6rIrQZ8HKcMsoQso4qtS2A=";
			byte [] bytes = Convert.FromBase64String (s);
			RSACryptoServiceProvider r = new RSACryptoServiceProvider ();
			r.FromXmlString ("<RSAKeyValue><Modulus>iSObDmmhDgrl4NiLaviFcpv4NdysBWJcqiVz3AQbPdajtXaQQ8VJdfRkixah132yKOFGCWZhHS3EuPMh8dcNwGwta2nh+m2IV6ktzI4+mZ7CSNAsmlDY0JI+H8At1vKvNArlC5jkVGuliYroJeSU/NLPLNYgspi7TtXGy9Rfug8=</Modulus><Exponent>EQ==</Exponent><P>pd4svtxrnTWXVSb151/JFgT9szI6dxQ5pAFPd4A4yuxLLEay2W2z7d9LVk5siMFhZ10uTJGWzNP5pSgLT8wdww==</P><Q>06j6m4cGRc3uoKVuFFGA19JG3Bi4tDBEQHebEc/Y3+eThrOasYIRrQmGUfqWnd9eFitO9GOaVJ0muNDV7NOxxQ==</Q><DP>OoqmYXr4zhLqHg3AM4s36adomZlBz6zJDLUrGx4yKYCTAJFsTL1OkDCxLYUXP1NPjeSm7dkIDA6UWGh8doRGvQ==</DP><DQ>PkDCLb5NI5br1OVcnJBxMGsFyEOBnmiMi2545x8DjSX+Nq1LnZ6555ljvcIsTIz9jgy83nel3KaxCS5dCWtwhQ==</DQ><InverseQ>OrFYaG7wTqim/bub4qY0CvIfhsjG4/4MEabg0UFTf/+tekKas7DDKg2TD5BS2q0O3XEt7xIfp0S6dpOAnrlyGQ==</InverseQ><D>IESc9FUW1iCuj0ICr8IBSCSy3383iMvZkXI5YPHoSskXdf3Hl3m27pPbbAVTQcM4+o9bxfn4u5JMZ8C8sV/G/8Cfl4ss1NVMbZOecvVObRqRpqXaveq5fN2X0EklH1wzm5w3O8cMXdbC/hc0gKUqaMjFVn1zpf3zVjpOkY0eGRE=</D></RSAKeyValue>");
			RSAOAEPKeyExchangeDeformatter def = new RSAOAEPKeyExchangeDeformatter (r);
			AssertNotNull (def.DecryptKeyExchange (bytes));
		}
		public void MonoExchangeMin() 
		{
			byte[] M = { 0x01 };
			byte[] EM = { 0x75, 0x06, 0x33, 0xB4, 0x47, 0xDB, 0x9C, 0x72, 0x1A, 0x09, 0x48, 0xEA, 0xF3, 0xED, 0xCF, 0xA7, 0x6D, 0x09, 0x8E, 0xF5, 0xC9, 0x70, 0x18, 0xF7, 0x22, 0xCC, 0xEC, 0xCB, 0xD3, 0x2B, 0xE7, 0xE3, 0x0A, 0x47, 0xF4, 0xE1, 0x66, 0x73, 0xEA, 0x7F, 0x5B, 0x27, 0x32, 0x62, 0x9D, 0x0C, 0x2F, 0x88, 0x2E, 0x3A, 0x37, 0x6C, 0x0C, 0x09, 0x1D, 0xF3, 0xE1, 0x80, 0x66, 0x26, 0x29, 0x97, 0x3D, 0xB7, 0xE6, 0x01, 0xD0, 0x88, 0x9C, 0x68, 0x3F, 0x62, 0x7C, 0x71, 0x36, 0xDA, 0xC3, 0xE2, 0x93, 0x20, 0x95, 0xF8, 0x15, 0x89, 0x73, 0x24, 0xDF, 0xFB, 0x72, 0xD9, 0x63, 0x19, 0x84, 0x41, 0x92, 0x3C, 0x71, 0x36, 0xB9, 0x09, 0x24, 0xD6, 0x8E, 0x2D, 0x5A, 0xF2, 0x4B, 0xF4, 0xCD, 0x58, 0xEB, 0x4E, 0xE4, 0x97, 0xB3, 0x09, 0xED, 0xCF, 0x6A, 0x6D, 0xBC, 0xE4, 0xD4, 0x8D, 0xEC, 0xA6, 0x35, 0x53 };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeDeformatter Min", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}
Пример #27
0
        /// <inheritdoc />
        protected internal override byte[] Decrypt(byte[] data, byte[] iv)
        {
            AsymmetricKeyExchangeDeformatter keyExchange;
            switch (this.Algorithm)
            {
                case AsymmetricAlgorithm.RsaOaepSha1:
                case AsymmetricAlgorithm.RsaOaepSha256:
                case AsymmetricAlgorithm.RsaOaepSha384:
                case AsymmetricAlgorithm.RsaOaepSha512:
                    keyExchange = new RSAOAEPKeyExchangeDeformatter(this.Rsa);
                    break;
                case AsymmetricAlgorithm.RsaPkcs1:
                    keyExchange = new RSAPKCS1KeyExchangeDeformatter(this.Rsa);
                    break;
                default:
                    throw new NotSupportedException();
            }

            return keyExchange.DecryptKeyExchange(data);
        }
Пример #28
0
		public byte[] Decrypt (byte[] rgb, bool fOAEP) 
		{
#if NET_1_1
			if (m_disposed)
				throw new ObjectDisposedException ("rsa");
#endif
			// choose between OAEP or PKCS#1 v.1.5 padding
			AsymmetricKeyExchangeDeformatter def = null;
			if (fOAEP)
				def = new RSAOAEPKeyExchangeDeformatter (rsa);
			else
				def = new RSAPKCS1KeyExchangeDeformatter (rsa);

			return def.DecryptKeyExchange (rgb);
		}
Пример #29
0
 /// <inheritdoc />
 protected internal override byte[] Decrypt(byte[] data, byte[] iv)
 {
     var keyExchange = new RSAOAEPKeyExchangeDeformatter(this.Rsa);
     return keyExchange.DecryptKeyExchange(data);
 }
		public void CapiExchange192 () 
		{
			byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49, 0x00, 0x00, 0x00, 0x00 };
			byte[] EM = { 0x72, 0x0A, 0x0E, 0xA0, 0x8C, 0x40, 0x69, 0x9D, 0x78, 0xBC, 0x94, 0x4B, 0x2C, 0x14, 0xC0, 0xC8, 0x13, 0x8B, 0x6D, 0x2F, 0x01, 0xE3, 0x45, 0x33, 0xE7, 0x9B, 0x87, 0xDB, 0x37, 0xBD, 0xA9, 0x63, 0xCC, 0x94, 0x8F, 0xBB, 0x1D, 0x61, 0xA1, 0x5E, 0x6A, 0x33, 0xBD, 0xD5, 0xC8, 0x22, 0x40, 0xB1, 0x32, 0xFB, 0x6F, 0x2A, 0x3B, 0x8A, 0x15, 0x4E, 0xC1, 0x25, 0xF0, 0x34, 0x17, 0x9A, 0x68, 0x34, 0x27, 0x5B, 0x49, 0xC5, 0xEA, 0x4D, 0x7F, 0x07, 0x4C, 0xAC, 0xF8, 0xE3, 0xD7, 0x9E, 0x72, 0xB0, 0xD1, 0xAD, 0x9E, 0x9C, 0xBB, 0xC6, 0x79, 0x14, 0x63, 0x5E, 0x13, 0xD1, 0x02, 0xDE, 0x57, 0xB5, 0xBC, 0x57, 0x68, 0xAC, 0xE3, 0xEF, 0x79, 0xED, 0xAF, 0xC0, 0xBB, 0xFE, 0xB3, 0xA6, 0x4C, 0xE8, 0x79, 0xE2, 0x3A, 0xB3, 0x37, 0x97, 0x90, 0x05, 0xCF, 0xB9, 0x1A, 0x92, 0xEC, 0x73, 0xC5, 0x8D };

			AsymmetricKeyExchangeDeformatter keyback = new RSAOAEPKeyExchangeDeformatter (key);
			try {
				byte[] Mback = keyback.DecryptKeyExchange (EM);
				AssertEquals ("RSAOAEPKeyExchangeFormatter 1", M, Mback);
			}
			catch (CryptographicException ce) {
				// not supported by every version of Windows - Minimum: Windows XP
				Console.WriteLine (ce.Message + " (" + Environment.OSVersion.ToString () + ")");
			}
		}