当前位置: 首页>>代码示例>>C#>>正文


C# TripleDESCryptoServiceProvider.GenerateKey方法代码示例

本文整理汇总了C#中System.Security.Cryptography.TripleDESCryptoServiceProvider.GenerateKey方法的典型用法代码示例。如果您正苦于以下问题:C# TripleDESCryptoServiceProvider.GenerateKey方法的具体用法?C# TripleDESCryptoServiceProvider.GenerateKey怎么用?C# TripleDESCryptoServiceProvider.GenerateKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Security.Cryptography.TripleDESCryptoServiceProvider的用法示例。


在下文中一共展示了TripleDESCryptoServiceProvider.GenerateKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DoTest

        /// <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);
        }
开发者ID:mahuidong,项目名称:my-csharp-sample,代码行数:37,代码来源:SymmetricKeysTest.cs

示例2: EncryptString

        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;
        }
开发者ID:expertlight,项目名称:CalandrePresentation,代码行数:29,代码来源:Crypto.cs

示例3: DecryptString

        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;

        }
开发者ID:expertlight,项目名称:CalandrePresentation,代码行数:30,代码来源:Crypto.cs

示例4: CreateKey

 /// <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);
     }
 }
开发者ID:CaptiveAire,项目名称:Dynamic-Image-Handler,代码行数:9,代码来源:SymCrypt.cs

示例5: generateKey

 // Generate a new symmetric key
 public static string generateKey()
 {
     using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
     {
         tdes.GenerateKey();
         return ASCIIEncoding.ASCII.GetString(tdes.Key);
     }
 }
开发者ID:and3k5,项目名称:mermail,代码行数:9,代码来源:symmetric.cs

示例6: GENERATEUR_DE_CLES

        internal static string GENERATEUR_DE_CLES()
        {
            trip = new TripleDESCryptoServiceProvider();
            trip.GenerateKey();

            return Convert.ToBase64String(trip.Key);

        }
开发者ID:abdojobs,项目名称:memoireboy,代码行数:8,代码来源:Encrypt.cs

示例7: DoEncryption

        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();
            }
        }
开发者ID:BigBearGCU,项目名称:FNDEV-Week10-Cryptography,代码行数:49,代码来源:Encryption.cs

示例8: GenerateNewIVAndKey

        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);
            }
        }
开发者ID:Supermortal,项目名称:MusicianHelper,代码行数:49,代码来源:Security.cs

示例9: SingleKeyEncryptionService

        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
        }
开发者ID:maxfridbe,项目名称:Infrastructure,代码行数:17,代码来源:SingleKeyEncryptionService.cs

示例10: Page_Load

        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 = "[email protected]";

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

        }
开发者ID:sdldemo,项目名称:MOPAS_charp,代码行数:43,代码来源:InsufficientKey.aspx.cs

示例11: Encrypt_Decrypt_RoundTrips

        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);
        }
开发者ID:supermason,项目名称:DataProtection,代码行数:41,代码来源:CertificateXmlEncryptionTests.cs

示例12: GenerateKey

 public static string GenerateKey()
 {
     var crypto = new TripleDESCryptoServiceProvider();
     crypto.GenerateKey();
     return Convert.ToBase64String(crypto.Key);
 }
开发者ID:aduggleby,项目名称:dragon,代码行数:6,代码来源:CryptUtil.cs

示例13: Create

        /// <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;
            }
//.........这里部分代码省略.........
开发者ID:Microsoft,项目名称:TSS.MSR,代码行数:101,代码来源:CryptoSymm.cs

示例14: CreateKey

        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;
        }
开发者ID:i-love-falcom,项目名称:WW,代码行数:20,代码来源:CryptographyHelper.cs

示例15: Main

        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();
        }
开发者ID:50minutos,项目名称:MOC-10265,代码行数:84,代码来源:Program.cs


注:本文中的System.Security.Cryptography.TripleDESCryptoServiceProvider.GenerateKey方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。