GenerateKey() public méthode

public GenerateKey ( ) : void
Résultat void
        /// <summary>
        /// 测试 生成对称密钥.
        /// </summary>
        public static void DoTest()
        {
            Console.WriteLine("##### 生成对称密钥的例子 !");

            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);

            Console.WriteLine("再多生成一组密钥 !");

            TDES.GenerateIV();
            TDES.GenerateKey();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);

            Console.WriteLine("再多生成一组密钥 !");

            TDES.GenerateIV();
            TDES.GenerateKey();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);
        }
        public static String EncryptString(String in_string)
        {
            String return_value;

            using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
            {
                tdsAlg.GenerateKey();
                tdsAlg.GenerateIV();

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(in_string);
                        }
                        return_value = msEncrypt.ToString();
                    }
                }
            }
            return return_value;
        }
        public static String DecryptString(String in_string)
        {
            String return_value;
            using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
            {
                tdsAlg.GenerateKey();
                tdsAlg.GenerateIV();

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

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(in_string)))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            return_value = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return return_value;

        }
 /// <exception cref="CryptographicException">The <see cref="T:System.Security.Cryptography.TripleDES" /> cryptographic service provider is not available. </exception>
 public static string CreateKey()
 {
     using (var provider = new TripleDESCryptoServiceProvider())
     {
         provider.GenerateKey();
         return BytesToHexString(provider.Key);
     }
 }
Exemple #5
0
 // Generate a new symmetric key
 public static string generateKey()
 {
     using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
     {
         tdes.GenerateKey();
         return ASCIIEncoding.ASCII.GetString(tdes.Key);
     }
 }
 public static string CreateNewKey()
 {
     using (var des = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
     {
         des.GenerateKey();
         return(Convert.ToBase64String(des.Key));
     }
 }
Exemple #7
0
        internal static string GENERATEUR_DE_CLES()
        {
            trip = new TripleDESCryptoServiceProvider();
            trip.GenerateKey();

            return Convert.ToBase64String(trip.Key);

        }
        public void DoEncryption()
        {
            // create a symmetric encryptor
            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider ();
            // create IV and Key need for symmetric encryption
            TDES.GenerateIV();
            TDES.GenerateKey();

            // create an asymmetric encryptor
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
            string AsymKeys = RSA.ToXmlString (true);

            // export the public and private keys to a file
            WriteKeyToFile(AsymKeys);

            // asymmetric encryption is good for
            // small data, hence, we use it to encrypted
            // IV and Key for symmetric encryption
            byte[] encryptedIV = RSA.Encrypt(TDES.IV, false);
            byte[] encryptedKey = RSA.Encrypt(TDES.Key, false);

            // convert the length of IV and Key (e.g. number of bytes used)
            // into a byte, e.g. 4 to 0000 0100
            // as default length of a Integer in .NET is 32,
            // the result byte length should be 4 bytes, i.e. 32/8
            byte[] IVSize = BitConverter.GetBytes(encryptedIV.Length);
            byte[] keySize = BitConverter.GetBytes(encryptedKey.Length);

            // write out the IV length, the key length,
            // the encrypted iv, the encrypted key and the actual
            // date to a file using the symmetric encryptor.
            using(FileStream ostream = new FileStream("encrypted.enc", FileMode.Create)){
                ostream.Write(IVSize, 0, IVSize.Length);
                ostream.Write(keySize, 0, keySize.Length);
                ostream.Write(encryptedIV, 0, encryptedIV.Length);
                ostream.Write(encryptedKey, 0, encryptedKey.Length);

                CryptoStream cstream = new CryptoStream(ostream,
                                                       TDES.CreateEncryptor(),
                                                        CryptoStreamMode.Write);

                // encrypt the data using the crypto stream
                EncryptFile(cstream);

                // close streams
                cstream.Close();
                ostream.Close();
            }
        }
        public static void GenerateNewIVAndKey(string path)
        {
            try
            {
                var encrypt = new TripleDESCryptoServiceProvider();

                encrypt.GenerateIV();
                encrypt.GenerateKey();

                var sb = new StringBuilder();
                sb.Append("private static byte[] _iv = new byte[] {");
                foreach (var b in encrypt.IV)
                {
                    sb.Append(b);
                    sb.Append(',');
                }

                var ivFront = sb.ToString().TrimEnd(',');
                sb = new StringBuilder();

                sb.Append(ivFront);
                sb.Append("};");

                var ivStr = sb.ToString();

                sb = new StringBuilder();
                sb.Append("private static byte[] _key = new byte[] {");
                foreach (var b in encrypt.Key)
                {
                    sb.Append(b);
                    sb.Append(',');
                }

                var keyFront = sb.ToString().TrimEnd(',');
                sb = new StringBuilder();

                sb.Append(keyFront);
                sb.Append("};");

                var keyStr = sb.ToString();

                var lines = new string[] { ivStr, "\n", keyStr };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
            }
        }
        public SingleKeyEncryptionService(ISingleKeyStore keystore)
        {
            //_passwordHashProvider = passwordHashProvider;
            var hash = keystore.GetKey();

            if (string.IsNullOrWhiteSpace(hash))
            {
                var tDes = new TripleDESCryptoServiceProvider();
                tDes.GenerateKey();
                keystore.SetKey(Convert.ToBase64String(tDes.Key));
                hash=keystore.GetKey();
            }

            _hashmd5 = new MD5CryptoServiceProvider();
            _hashEnc = Encoding.UTF8.GetBytes(hash);
            //_hash = key
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

            //Set key size
            TDES.KeySize = 10;

            //Generate keys
            TDES.GenerateIV();
            TDES.GenerateKey();

            string data = "p@ssword";

            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(@"C:\passwords.txt", FileMode.OpenOrCreate);

                // Create a CryptoStream using the FileStream  
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(TDES.Key, TDES.IV),
                    CryptoStreamMode.Write);

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

                // Write the data to the stream  
                // to encrypt it.
                sWriter.WriteLine(data);

                // Close the streams and 
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
            catch
            {
                Console.WriteLine("A Cryptographic error occurred");
            }

        }
        public void Encrypt_Decrypt_RoundTrips()
        {
            // Arrange
            var symmetricAlgorithm = new TripleDESCryptoServiceProvider();
            symmetricAlgorithm.GenerateKey();

            var serviceCollection = new ServiceCollection();
            var mockInternalEncryptor = new Mock<IInternalCertificateXmlEncryptor>();
            mockInternalEncryptor.Setup(o => o.PerformEncryption(It.IsAny<EncryptedXml>(), It.IsAny<XmlElement>()))
                .Returns<EncryptedXml, XmlElement>((encryptedXml, element) =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", symmetricAlgorithm); // use symmetric encryption
                    return encryptedXml.Encrypt(element, "theKey");
                });
            serviceCollection.AddInstance<IInternalCertificateXmlEncryptor>(mockInternalEncryptor.Object);

            var mockInternalDecryptor = new Mock<IInternalEncryptedXmlDecryptor>();
            mockInternalDecryptor.Setup(o => o.PerformPreDecryptionSetup(It.IsAny<EncryptedXml>()))
                .Callback<EncryptedXml>(encryptedXml =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", symmetricAlgorithm); // use symmetric encryption
                });
            serviceCollection.AddInstance<IInternalEncryptedXmlDecryptor>(mockInternalDecryptor.Object);

            var services = serviceCollection.BuildServiceProvider();
            var encryptor = new CertificateXmlEncryptor(services);
            var decryptor = new EncryptedXmlDecryptor(services);

            var originalXml = XElement.Parse(@"<mySecret value='265ee4ea-ade2-43b1-b706-09b259e58b6b' />");

            // Act & assert - run through encryptor and make sure we get back <EncryptedData> element
            var encryptedXmlInfo = encryptor.Encrypt(originalXml);
            Assert.Equal(typeof(EncryptedXmlDecryptor), encryptedXmlInfo.DecryptorType);
            Assert.Equal(XName.Get("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"), encryptedXmlInfo.EncryptedElement.Name);
            Assert.Equal("http://www.w3.org/2001/04/xmlenc#Element", (string)encryptedXmlInfo.EncryptedElement.Attribute("Type"));
            Assert.DoesNotContain("265ee4ea-ade2-43b1-b706-09b259e58b6b", encryptedXmlInfo.EncryptedElement.ToString(), StringComparison.OrdinalIgnoreCase);

            // Act & assert - run through decryptor and make sure we get back the original value
            var roundTrippedElement = decryptor.Decrypt(encryptedXmlInfo.EncryptedElement);
            XmlAssert.Equal(originalXml, roundTrippedElement);
        }
Exemple #13
0
        /// <summary>
        /// Create a new SymmCipher object with a random key based on the alg and mode supplied.
        /// </summary>
        /// <param name="algId"></param>
        /// <param name="numBits"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static SymmCipher Create(SymDefObject symDef = null, byte[] keyData = null, byte[] iv = null)
        {
            if (symDef == null)
            {
                symDef = new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb);
            }

#if TSS_USE_BCRYPT
            BCryptAlgorithm alg = null;

            switch (symDef.Algorithm)
            {
                case TpmAlgId.Aes:
                    alg = new BCryptAlgorithm(Native.BCRYPT_AES_ALGORITHM);
                    break;
                case TpmAlgId.Tdes:
                    alg = new BCryptAlgorithm(Native.BCRYPT_3DES_ALGORITHM);
                    break;
                default:
                    Globs.Throw<ArgumentException>("Unsupported symmetric algorithm " + symDef.Algorithm);
                    break;
            }

            if (keyData == null)
            {
                keyData = Globs.GetRandomBytes(symDef.KeyBits / 8);
            }
            var key = alg.GenerateSymKey(symDef, keyData, GetBlockSize(symDef));
            //key = BCryptInterface.ExportSymKey(keyHandle);
            //keyHandle = alg.LoadSymKey(key, symDef, GetBlockSize(symDef));
            alg.Close();
            return key == null ? null : new SymmCipher(key, keyData, iv);
#else
            SymmetricAlgorithm alg = null; // = new RijndaelManaged();
            bool limitedSupport = false;
            // DES and __3DES are not supported in TPM 2.0 rev. 0.96 to 1.30
            switch (symDef.Algorithm) {
                case TpmAlgId.Aes:
                    alg = new RijndaelManaged();
                    break;
                case TpmAlgId.Tdes:
                    alg = new TripleDESCryptoServiceProvider();
                    limitedSupport = true;
                    break;
                default:
                    Globs.Throw<ArgumentException>("Unsupported symmetric algorithm " + symDef.Algorithm);
                    break;
            }

            int blockSize = GetBlockSize(symDef);
            alg.KeySize = symDef.KeyBits;
            alg.BlockSize = blockSize * 8;
            alg.Padding = PaddingMode.None;
            alg.Mode = GetCipherMode(symDef.Mode);

            // REVISIT: Get this right for other modes
            if (symDef.Algorithm == TpmAlgId.Tdes && symDef.Mode == TpmAlgId.Cfb)
            {
                alg.FeedbackSize = 8;
            }
            else
            {
                alg.FeedbackSize = alg.BlockSize;
            }

            if (keyData == null)
            {
                // Generate random key
                alg.IV = Globs.GetZeroBytes(blockSize);
                try
                {
                    alg.GenerateKey();
                }
                catch (Exception)
                {
                    alg.Dispose();
                    throw;
                }
            }
            else
            {
                // Use supplied key bits
                alg.Key = keyData;
                if (iv == null)
                {
                    iv = Globs.GetZeroBytes(blockSize);
                }
                else if (iv.Length != blockSize)
                {
                    Array.Resize(ref iv, blockSize);
                }
                alg.IV = iv;
            }

            var symCipher = new SymmCipher(alg);
            symCipher.LimitedSupport = limitedSupport;
            return symCipher;
#endif
        }
        private static void CreateKey(out byte[] key, out byte[] iv)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            KeySizes[] ks = des.LegalKeySizes;
            foreach (var k in ks)
            {
                des.KeySize = k.MaxSize;
            }
            ks = des.LegalBlockSizes;
            foreach (var k in ks)
            {
                des.BlockSize = k.MaxSize;
            }
            des.GenerateKey();
            des.GenerateIV();

            key = des.Key;
            iv = des.IV;
        }
Exemple #15
0
        static void Main(string[] args)
        {
            //criptografia
            //algoritmo de criptografia
            //mensagem
            //mensagem cifrada
            //chave de criptografia

            //ponta solta

            //abcdefghijklmnopqrstuvwxyz
            //paranoia e bom para senhas, entendeu?
            //parnoiebmshtd ucfgjklqvwxyz
            //puacrfngojikelbqmvswhxtydz -> chave

            //mensagem = opabeleza
            //cifrada =  bqpurkrzp
            //           opabeleza

            //abcdefghijklmnopqrstuvwxyz
            //opabeleza - original
            //bberqssgk - cifrada com rotação da chave
            //puacrfngojikelbqmvswhxtydz 1
            //zpuacrfngojikelbqmvswhxtyd 2
            //dzpuacrfngojikelbqmvswhxty 3
            //ydzpuacrfngojikelbqmvswhxt 4
            //tydzpuacrfngojikelbqmvswhx 5
            //xtydzpuacrfngojikelbqmvswh 6
            //hxtydzpuacrfngojikelbqmvsw 7
            //whxtydzpuacrfngojikelbqmvs 8
            //swhxtydzpuacrfngojikelbqmv 9

            /*
                XOR - eXclusive OR (algoritmo)

                6   - 0000 0110 (msg)
                2   - 0000 0010 (chave)
                6^2 - 0000 0100 -> 4 (msg cifrada)
                4^2 - 0000 0110 -> 6 (msg)
            */

            /*
               Algoritmos
               ----------
               DES: DESCryptoServiceProvider
               RC2: RC2CryptoServiceProvider
               Rijndael: RijndaelManaged
               TripleDES: TripleDESCryptoServiceProvider
            */

            //criação de chaves simétricas
            var tdes = new TripleDESCryptoServiceProvider();

            Console.WriteLine(tdes.IV); //64 bits
            Console.WriteLine(tdes.Key); //192 bits

            Console.WriteLine();

            Console.WriteLine(tdes.IV.GetString());

            Console.WriteLine();

            Console.WriteLine(tdes.Key.GetString());

            tdes.GenerateIV();
            tdes.GenerateKey();

            Console.WriteLine();
            Console.WriteLine();

            byte[] meuIV = { 12, 23, 54, 65, 23, 76, 87, 89 };
            byte[] minhaChave = { 12, 23, 54, 65, 23, 76, 87, 189, 112, 123, 154, 165, 123, 176, 187, 189, 102, 230, 254, 5, 213, 167, 178, 9 };

            tdes.IV = meuIV;
            tdes.Key = minhaChave;

            Console.WriteLine(tdes.IV.GetString());

            Console.WriteLine();

            Console.WriteLine(tdes.Key.GetString());

            Console.ReadKey();
        }
Exemple #16
0
        public static void main(string[] args)
        {
            AesManaged aes = new AesManaged();
            Console.WriteLine("AesManaged ");
            KeySizes[] ks = aes.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = aes.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }

            RijndaelManaged rij = new RijndaelManaged();
            Console.WriteLine("RijndaelManaged ");
            ks = rij.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = rij.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }
            TripleDESCryptoServiceProvider tsp = new TripleDESCryptoServiceProvider();
            Console.WriteLine("TripleDESCryptoServiceProvider ");
            ks = tsp.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = tsp.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.BlockSize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();
                Console.Out.WriteLine(rijAlg.KeySize + " " + rijAlg.BlockSize + " " + Convert.ToBase64String(rijAlg.IV, Base64FormattingOptions.None) + " " +
                    Convert.ToBase64String(rijAlg.Key, Base64FormattingOptions.None));
            }

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.KeySize = 192;
            des.BlockSize = 64;
            des.GenerateKey();
            des.GenerateIV();
            Console.Out.WriteLine(des.KeySize + " " + des.BlockSize + " " + Convert.ToBase64String(des.IV, Base64FormattingOptions.None) + " " +
                Convert.ToBase64String(des.Key, Base64FormattingOptions.None));
        }
 public static string GenerateTripleDESHexStringKey()
 {
     TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
     des.GenerateKey();
     return BytesArrayToHexString(des.Key);
 }
        internal static bool EncryptFile(string fileNameToEncrypt)
        {
            string encryptedFileName = fileNameToEncrypt + ".enc";

            //instantiate our RSA crypto service provider with parameters
            const int PROVIDER_RSA_FULL = 1;
            const string CONTAINER_NAME = "CodewordCryptoContainer";
            CspParameters cspParams;
            cspParams = new CspParameters(PROVIDER_RSA_FULL);
            cspParams.KeyContainerName = CONTAINER_NAME;
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            RSACryptoServiceProvider aSymmetricEncProvider = new RSACryptoServiceProvider(cspParams);
            TripleDESCryptoServiceProvider SymmetricEncProvider = new TripleDESCryptoServiceProvider();

            //open read-only file stream for our unencrypted file
            FileStream PlaintextFileDataStream = new FileStream(fileNameToEncrypt, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            //create a writable filestream to write encrypted file out
            FileStream EncryptedFileDataStream = new FileStream(encryptedFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //init a binaryWriter class to dump data to file
            BinaryWriter bw = new BinaryWriter(EncryptedFileDataStream);

            int fileLength = (int)PlaintextFileDataStream.Length;

            //if no data to encrypt, fail now
            if (fileLength == 0)
            {
                PlaintextFileDataStream.Close();
                EncryptedFileDataStream.Close();
                return false;
            }

            //read all data from file as binary data
            byte[] UnencryptedBinaryData = ReadByteArray(PlaintextFileDataStream);
            PlaintextFileDataStream.Close();

            //generate a new IV and sym key for encryption
            SymmetricEncProvider.GenerateIV();
            SymmetricEncProvider.GenerateKey();

            //use asymmetric encryption to encrpyt initialization vector (IV)
            byte[] EncryptedBinaryData = aSymmetricEncProvider.Encrypt(SymmetricEncProvider.IV, false);
            //then write it to the output stream (encrypted file)
            bw.Write(EncryptedBinaryData);
            //do the same for symmetric key
            EncryptedBinaryData = aSymmetricEncProvider.Encrypt(SymmetricEncProvider.Key, false);
            bw.Write(EncryptedBinaryData);

            //create our symmetric encryptor
            ICryptoTransform DES3Encrypt = SymmetricEncProvider.CreateEncryptor();

            //create a crypto stream to write our encrypted data by using:
            //      -target data stream (EncryptedFileDataStream), ie output file encrypted
            //      -transformation to user (3-DES)
            //      -mode (Write)
            //this will essentially pipe all our unencrypted data we read in from the file-to-encrypt
            //through our encrypted data stream using the 3-DES transformation
            CryptoStream cryptoStream = new CryptoStream(EncryptedFileDataStream, DES3Encrypt, CryptoStreamMode.Write);
            cryptoStream.Write(UnencryptedBinaryData, 0, UnencryptedBinaryData.Length);
            cryptoStream.Close();
            EncryptedFileDataStream.Close();
            PlaintextFileDataStream.Close();
            bw.Close();

            return true;
        }
Exemple #19
0
 public static string GenerateKey()
 {
     var crypto = new TripleDESCryptoServiceProvider();
     crypto.GenerateKey();
     return Convert.ToBase64String(crypto.Key);
 }
 public static Secret HybridEncrypt
                             (
                                 RSACryptoServiceProvider encryptorPrivateKeyPfxProvider
                                 , X509Certificate2 encryptorPublicKeyCer
                                 , RSACryptoServiceProvider decryptorPublicKeyCerProvider
                                 , HashSignatureMode signHashMode
                                 , bool DoOAEPadding
                                 , byte[] data
                             )
 {
     Secret secret = new Secret();
     using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
     {
         provider.GenerateIV();
         secret.EncryptorSharedEncryptedOnceIV = provider.IV;
         provider.GenerateKey();
         secret.EncryptorSharedEncryptedOnceKey = provider.Key;
         secret.EncryptedData = provider.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
     }
     secret.EncryptorSharedEncryptedOnceIV = decryptorPublicKeyCerProvider.Encrypt(secret.EncryptorSharedEncryptedOnceIV, DoOAEPadding);
     secret.EncryptorSharedEncryptedOnceKey = decryptorPublicKeyCerProvider.Encrypt(secret.EncryptorSharedEncryptedOnceKey, DoOAEPadding);
     HashAlgorithm hashAlgorithm;
     if (signHashMode == HashSignatureMode.SHA1)
     {
         hashAlgorithm = new SHA1CryptoServiceProvider();
     }
     else //(hashSignatureMode == HashSignatureMode.MD5)
     {
         hashAlgorithm = new MD5CryptoServiceProvider();
     }
     MemoryStream stream = new MemoryStream();
     byte[] buffer = secret.EncryptorSharedEncryptedOnceIV;
     stream.Write(buffer, 0, buffer.Length);
     buffer = secret.EncryptorSharedEncryptedOnceKey;
     stream.Write(buffer, 0, buffer.Length);
     buffer = secret.EncryptedData;
     stream.Position = 0;
     buffer = hashAlgorithm.ComputeHash(stream);
     stream.Close();
     stream.Dispose();
     secret.EncryptorHashSignature = encryptorPrivateKeyPfxProvider.SignHash
                                                                         (
                                                                             buffer
                                                                             , Enum.GetName
                                                                                         (
                                                                                             signHashMode.GetType()
                                                                                             , signHashMode
                                                                                         )
                                                                         );
     secret.EncryptorPublicKeyCerRawData = encryptorPublicKeyCer.RawData;
     secret.SignHashMode = signHashMode;
     secret.DoOAEPadding = DoOAEPadding;
     return secret;
 }