CreateKeyExchange() 공개 메소드

public CreateKeyExchange ( byte rgbData ) : byte[]
rgbData byte
리턴 byte[]
예제 #1
0
		public override void GenerateClient (TlsContext ctx)
		{
			// Compute pre master secret
			using (var preMasterSecret = ctx.Session.GetSecureRandomBytes (48)) {
				preMasterSecret.Buffer [0] = (byte)((short)ctx.Configuration.RequestedProtocol >> 8);
				preMasterSecret.Buffer [1] = (byte)ctx.Configuration.RequestedProtocol;

				RSA rsa = null;
				// Create a new RSA key
				var serverCertificates = ctx.Session.PendingCrypto.ServerCertificates;
				if (serverCertificates == null || serverCertificates.Count == 0) {
					// FIXME: Should have received ServerKeyExchange message.
					throw new TlsException (AlertDescription.IlegalParameter);
				} else {
					rsa = new RSAManaged (serverCertificates [0].RSA.KeySize);
					rsa.ImportParameters (serverCertificates [0].RSA.ExportParameters (false));
				}

				ComputeMasterSecret (ctx, preMasterSecret);

				// Encrypt premaster_sercret
				var formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
				encryptedPreMasterSecret = formatter.CreateKeyExchange (preMasterSecret.Buffer);
				rsa.Clear ();
			}
		}
		protected override void ProcessAsSsl3()
		{
			// Compute pre master secret
			byte[] preMasterSecret = this.Context.Cipher.CreatePremasterSecret();

			// Create a new RSA key
			RSA rsa = null;
			if (this.Context.ServerSettings.ServerKeyExchange) 
			{
				// this is the case for "exportable" ciphers
				rsa = new RSAManaged ();
				rsa.ImportParameters (this.Context.ServerSettings.RsaParameters);
			}
			else 
			{
				rsa = this.Context.ServerSettings.CertificateRSA;
			}
			
			// Encrypt premaster_sercret
			RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter(rsa);

			// Write the preMasterSecret encrypted
			byte[] buffer = formatter.CreateKeyExchange(preMasterSecret);
			this.Write(buffer);

			// Create master secret
			this.Context.Cipher.ComputeMasterSecret(preMasterSecret);

			// Create keys
			this.Context.Cipher.ComputeKeys();

			// Clear resources
			rsa.Clear();
		}
	public void KeyExchangeMin ()
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter (key);
		byte[] M = { 0x01 };
		byte[] EM = keyex.CreateKeyExchange (M);

		AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter (key);
		byte[] Mback = keyback.DecryptKeyExchange (EM);
		AssertEquals ("RSAPKCS1KeyExchangeFormatter 1", M, Mback);
	}
예제 #4
0
        private static bool DetectRsaCngSupport()
        {
            Type rsaCng = GetSystemCoreType(RSACngTypeName, throwOnError: false);

            // If the type doesn't exist, there can't be good support for it.
            // (System.Core < 4.6)
            if (rsaCng == null)
            {
                return(false);
            }

            Type dsaCng = GetSystemCoreType(DSACngTypeName, throwOnError: false);

            // The original implementation of RSACng returned shared objects in the CAPI fallback
            // pathway. That behavior is hard to test for, since CNG can load all CAPI software keys.
            // But, since DSACng was added in 4.6.2, and RSACng better guarantees uniqueness in 4.6.2
            // use that coincidence as a compatibility test.
            //
            // If DSACng is missing, RSACng usage might lead to attempting to use Disposed objects
            // (System.Core < 4.6.2)
            if (dsaCng == null)
            {
                return(false);
            }

            // Create an RSACng instance and send it to RSAPKCS1KeyExchangeFormatter. It was adjusted to
            // be CNG-capable for 4.6.2; and other types in that library also are up-to-date.
            //
            // If mscorlib can't handle it properly, then other libraries probably can't, so we'll keep
            // preferring RSACryptoServiceProvider.
            RSA rsa = (RSA)Activator.CreateInstance(rsaCng);

            try
            {
                RSAPKCS1KeyExchangeFormatter formatter = new RSAPKCS1KeyExchangeFormatter(rsa);
                formatter.CreateKeyExchange(new byte[1]);
            }
            catch (NotSupportedException)
            {
                // (mscorlib < 4.6.2)
                return(false);
            }

            return(true);
        }
예제 #5
0
        /// <inheritdoc />
        protected internal override byte[] Encrypt(byte[] data, byte[] iv)
        {
            AsymmetricKeyExchangeFormatter keyExchange;
            switch (this.Algorithm)
            {
                case AsymmetricAlgorithm.RsaOaepSha1:
                case AsymmetricAlgorithm.RsaOaepSha256:
                case AsymmetricAlgorithm.RsaOaepSha384:
                case AsymmetricAlgorithm.RsaOaepSha512:
                    keyExchange = new RSAOAEPKeyExchangeFormatter(this.Rsa);
                    break;
                case AsymmetricAlgorithm.RsaPkcs1:
                    keyExchange = new RSAPKCS1KeyExchangeFormatter(this.Rsa);
                    break;
                default:
                    throw new NotSupportedException();
            }

            return keyExchange.CreateKeyExchange(data);
        }
예제 #6
0
파일: encryptedxml.cs 프로젝트: mind0n/hive
        // encrypts the supplied input key 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[] EncryptKey (byte[] keyData, RSA rsa, bool useOAEP) {
            if (keyData == null)
                throw new ArgumentNullException("keyData");
            if (rsa == null)
                throw new ArgumentNullException("rsa");

            if (useOAEP) {
                RSAOAEPKeyExchangeFormatter rsaFormatter = new RSAOAEPKeyExchangeFormatter(rsa);
                return rsaFormatter.CreateKeyExchange(keyData);
            } else {
                RSAPKCS1KeyExchangeFormatter rsaFormatter = new RSAPKCS1KeyExchangeFormatter(rsa);
                return rsaFormatter.CreateKeyExchange(keyData);
            }
        }
	public void KeyExchange128bits ()
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter (key);
		byte[] M = { 0xd4, 0x36, 0xe9, 0x95, 0x69, 0xfd, 0x32, 0xa7, 0xc8, 0xa0, 0x5b, 0xbc, 0x90, 0xd3, 0x2c, 0x49 };
		byte[] EM = keyex.CreateKeyExchange (M, typeof (Rijndael));

		AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter (key);
		byte[] Mback = keyback.DecryptKeyExchange (EM);
		AssertEquals ("RSAPKCS1KeyExchangeFormatter 1", M, Mback);
	}
	[Category ("NotDotNet")] // Sometime causes System.ExecutionEngineException on MS implementation
#endif
	public void KeyExchangeNull ()
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter (key);
		byte[] EM = keyex.CreateKeyExchange (null);
	}
	public void ExchangeNoKey () 
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter ();
		byte[] M = keyex.CreateKeyExchange (new byte [16]);
	}
	public void KeyExchangeTooBig()
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter (key);
		byte[] M = new byte [(key.KeySize >> 3)- 10];
		byte[] EM = keyex.CreateKeyExchange (M);
	}
	public void KeyExchangeMax()
	{
		AsymmetricKeyExchangeFormatter keyex = new RSAPKCS1KeyExchangeFormatter (key);
		byte[] M = new byte [(key.KeySize >> 3)- 11];
		byte[] EM = keyex.CreateKeyExchange (M);

		AsymmetricKeyExchangeDeformatter keyback = new RSAPKCS1KeyExchangeDeformatter (key);
		byte[] Mback = keyback.DecryptKeyExchange (EM);
		AssertEquals ("RSAPKCS1KeyExchangeFormatter 1", M, Mback);
	}
예제 #12
0
        public static void TestRSACertificate()
        {
            byte [] bPublicKeyModulus = new byte []
            {
                0xB3, 0x93, 0x18, 0x8B, 0x70, 0xC8, 0x57, 0xFC, 0x0F, 0x75, 0x11, 0xF7, 0x32, 0x2E, 0x6F, 0x91,
                0xD2, 0x76, 0x1F, 0x33, 0x5D, 0xE2, 0x9C, 0x48, 0x84, 0x16, 0xD8, 0x2A, 0x09, 0x1B, 0x42, 0x8D,
                0x31, 0x53, 0x21, 0xCB, 0x44, 0xC7, 0x97, 0x0A, 0x76, 0x18, 0xF5, 0xD6, 0xE8, 0x4B, 0x0C, 0xDD,
                0x5D, 0xBD, 0xA8, 0x47, 0xCD, 0x81, 0x9E, 0xD9, 0x8D, 0xAE, 0x5C, 0x5D, 0xEC, 0x79, 0x99, 0x4B,
                0x1A, 0xD7, 0x69, 0x89, 0x15, 0x0C, 0xA5, 0x51, 0xDC, 0xBF, 0x6A, 0x98, 0x76, 0xE4, 0x17, 0x55,
                0x8E, 0xCE, 0xB7, 0x8A, 0xA0, 0x94, 0xF8, 0xC6, 0x45, 0xA6, 0x89, 0x82, 0x70, 0xA6, 0x40, 0x2A,
                0x03, 0x8A, 0xD5, 0xE7, 0xE9, 0x03, 0x03, 0x63, 0x24, 0x55, 0xB7, 0xA1, 0xAD, 0xF0, 0x7D, 0x02,
                0x63, 0x3C, 0xB5, 0x6B, 0xAD, 0xA5, 0xA1, 0xA2, 0x2A, 0x0A, 0x8F, 0x3D, 0x84, 0x2F, 0x40, 0xF3
            };

            // Taken from openssl on our test certificate
            byte[] bPrivateExponent = new byte[]
            {
                0x42, 0x7e, 0x26, 0x29, 0x83, 0xd2, 0x7b, 0x59, 0xd7, 0x33, 0x67, 0x3a, 0x9c, 0x37, 0x3b,
                0x92, 0xc8, 0x56, 0x7a, 0xc9, 0x1f, 0x6b, 0x88, 0xa9, 0x05, 0x58, 0x1c, 0x24, 0xbc, 0x88,
                0x7e, 0x85, 0x1f, 0x8d, 0x83, 0xc6, 0xeb, 0xa9, 0xe8, 0x10, 0xb4, 0x98, 0x1b, 0x77, 0xbf,
                0x3e, 0x02, 0xfe, 0x78, 0xf6, 0x80, 0x38, 0x4e, 0x2d, 0x3f, 0xef, 0x98, 0x99, 0xc6, 0x93,
                0xf4, 0xbb, 0x35, 0xfa, 0x4d, 0x25, 0x93, 0x3b, 0xfa, 0xf0, 0x35, 0x21, 0x18, 0xe7, 0x16,
                0x5a, 0x21, 0x2a, 0xd1, 0x8e, 0xe4, 0x27, 0xcc, 0xca, 0x84, 0xe5, 0xc6, 0x31, 0x1d, 0x6f,
                0x2f, 0x3c, 0xc6, 0x17, 0x6d, 0x55, 0x2c, 0x1a, 0x95, 0xbe, 0x90, 0x18, 0xf8, 0x44, 0xc0,
                0x8a, 0xdd, 0x1e, 0x11, 0x68, 0x67, 0x42, 0xad, 0x6e, 0xb0, 0x41, 0x68, 0x9d, 0xa8, 0xe6,
                0xf0, 0x81, 0x36, 0xd3, 0x7f, 0x34, 0x16, 0x41
            };

            byte[] bPublicKeyExponent = new byte[] { 0x01, 0x00, 0x01 };

            string strTextToBeEncrypted = "12345";
            string strEncryptedWithPublicKey = "5A D9 BF B9 44 4C C5 F2 0E 9C F5 61 D7 D2 BA B0 54 7A 46 74 BF 3A A3 5E 1D 45 23 9A A0 C8 A0 AF F5 11 16 25 03 3D 77 04 C4 85 80 05 52 FB 83 22 06 63 6C 65 82 A9 75 12 72 E2 82 07 B8 72 EA 30 66 0E 75 6E D2 D4 B6 2F DD B2 61 15 4C D3 53 465B 68 36 F6 C1 3E 90 74 52 07 4E 32 EC 8D 7F A2 F1 71 64 33 F3 2D 99 9A 12 D1 ED ED AB 9D B0 D3 18 A9 B2 E2 99 C0 C7 C3 BA AF EF 51 5C 05 0F 4D";
            string strEncryptedWithPrivateKey= "62 D9 64 6E C2 57 BA 58 92 E0 13 2D EA 36 71 49 83 B6 7D 32 32 EE A6 89 FF 71 8F 60 94 43 6E 85 5D AB FF 52 61 92 A5 EE 8A 9E AE 27 51 3B A3 65 22 C3 EC AB 29 E2 2D EB 29 04 51 D9 6B D4 5F 6C 36 8C 62 80 F7 D3 69 8B A2 51 43 CF B3 9D 03 50A4 FB 93 BB CC 42 5F 20 FF 9B 51 9B 4D 56 30 10 35 14 CE EF E6 52 5F 07 52 AC 98 BB 54 2A 79 0F 08 E8 20 45 6A 77 78 85 0D BF 7B E2 6F F9 43 F8";

            byte[] bTextToBeEncrypted = System.Text.UTF8Encoding.UTF8.GetBytes(strTextToBeEncrypted);
            byte[] bEncryptedWithPublicKey = ByteHelper.ByteFromHexString(strEncryptedWithPublicKey);
            byte[] bEncryptedWithPrivateKey = ByteHelper.ByteFromHexString(strEncryptedWithPrivateKey);

                /// This RSA certificate was generated with OpenSSL.  A file is encrypted with OpenSSL using the private key to make sure we
            /// can decrypt it with the public key
            ///

            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();

            RSAParameters rsaparams = new RSAParameters();
            rsaparams.Modulus = bPublicKeyModulus;
            rsaparams.Exponent = bPublicKeyExponent;
            provider.ImportParameters(rsaparams);

            /// Verified that both of these methods work, they encrypt the string to a form that can be unencrypted (to reproduce "12345")
            /// by using the private key with openssl
            /// Steps taken
            /// Save the debug output hex string produced below as a ascii hex file (384 bytes long)
            /// convert the ascii hex file to a binary file (128 bytes long)
            ///     (I wrote a program called ba.exe to do this)
            /// run openssl against the binary file:
            /// C:\openssl\bin>openssl rsautl -decrypt -in hex2.bin -inkey test_key.pem -out hex2.decrypt
            /// verify that file hex2.decrypt has the ascii contents "12345"  (it did with both outputs below)
            ///
            /// (Note the output is different every time because of PKCS padding applied to make it different every time, this is stripped once it's decrypted)
            ///

            byte[] bEncryptedText1 = provider.Encrypt(bTextToBeEncrypted, false);
            System.Diagnostics.Debug.WriteLine(ByteHelper.HexStringFromByte(bEncryptedText1, true, 16));
            System.Diagnostics.Debug.WriteLine("");

            RSAPKCS1KeyExchangeFormatter formm = new RSAPKCS1KeyExchangeFormatter(provider);
            byte[] bEncryptedText = formm.CreateKeyExchange(bTextToBeEncrypted);
            System.Diagnostics.Debug.WriteLine(ByteHelper.HexStringFromByte(bEncryptedText, true, 16));
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");

            provider.Dispose();
        }
예제 #13
0
		// create a symetrical key, encrypt that with RSA, and encrypt the data with the symertrical key
		// see http://pages.infinit.net/ctech/20031101-0151.html
		static byte[] Encrypt (RSA rsa, byte[] input) 
		{
		     // by default this will create a 128 bits AES (Rijndael) object
		     SymmetricAlgorithm sa = SymmetricAlgorithm.Create ();
		     ICryptoTransform ct = sa.CreateEncryptor ();
		     byte[] encrypt = ct.TransformFinalBlock (input, 0, input.Length);
		
		     RSAPKCS1KeyExchangeFormatter fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
		     byte[] keyex = fmt.CreateKeyExchange (sa.Key);
		
		     // return the key exchange, the IV (public) and encrypted data
		     byte[] result = new byte [keyex.Length + sa.IV.Length + encrypt.Length];
		     Buffer.BlockCopy (keyex, 0, result, 0, keyex.Length);
		     Buffer.BlockCopy (sa.IV, 0, result, keyex.Length, sa.IV.Length);
		     Buffer.BlockCopy (encrypt, 0, result, keyex.Length + sa.IV.Length, encrypt.Length);
		     return result;
		}
예제 #14
0
        private async static Task File(string inFile, string outFile, RSACryptoServiceProvider key)
        {
            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(key);
                    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
                    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                    {

                        await outFs.WriteAsync(LenK, 0, 4);
                        await outFs.WriteAsync(LenIV, 0, 4);
                        await outFs.WriteAsync(keyEncrypted, 0, lKey);
                        await outFs.WriteAsync(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 = await inFs.ReadAsync(data, 0, blockSizeBytes);
                                    offset += count;
                                    await outStreamEncrypted.WriteAsync(data, 0, count);
                                    bytesRead += blockSizeBytes;
                                }
                                while (count > 0);
                            }
                        }
                    }
                }
            }
        }