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


C# TripleDESCryptoServiceProvider.GenerateIV方法代码示例

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


在下文中一共展示了TripleDESCryptoServiceProvider.GenerateIV方法的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: 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

示例3: 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

示例4: 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

示例5: 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

示例6: EncryptString

        public string EncryptString(string data)
        {
            byte[] toEncrypt = Encoding.UTF8.GetBytes(data);
            var tDes = new TripleDESCryptoServiceProvider();

            tDes.GenerateIV();

            var key = _hashmd5.ComputeHash(_hashEnc);
            var bytes = TripleDes.Encrypt(toEncrypt, key, tDes.IV);

            var str = Convert.ToBase64String(bytes, 0, bytes.Length);
            var iv = Convert.ToBase64String(tDes.IV, 0, tDes.IV.Length);
            var res = string.Format("{0}|{1}", str, iv);
            return res;
        }
开发者ID:maxfridbe,项目名称:Infrastructure,代码行数:15,代码来源:SingleKeyEncryptionService.cs

示例7: 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

示例8: 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

示例9: main

        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));
        }
开发者ID:lazycrazyowl,项目名称:juddi,代码行数:64,代码来源:Encryption.cs

示例10: GetInitializationVector

 /// <summary>
 /// Gets the initialization vector.
 /// </summary>
 /// <returns>
 /// The initialization vector.
 /// </returns>
 public byte[] GetInitializationVector()
 {
     var tripleDes = new TripleDESCryptoServiceProvider();
     tripleDes.GenerateIV();
     return tripleDes.IV;
 }
开发者ID:famstutz,项目名称:YAEM,代码行数:12,代码来源:TripleDESCryptoProvider.cs

示例11: GenerateTripleDESHexStringIV

 public static string GenerateTripleDESHexStringIV()
 {
     TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
     des.GenerateIV();
     return BytesArrayToHexString(des.IV);
 }
开发者ID:Microshaoft,项目名称:Microshaoft.Common.Utilities.Net.4x,代码行数:6,代码来源:CryptographyHelper.cs

示例12: GenerateIV

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

示例13: Decrypt

        /// <summary>
        /// Desifrovani dat (3DES alg.)
        /// - v pripade, ze vstupni data nemaji validni format vyhazuje GopayException
        /// </summary>
        /// 
        /// <param name="data">data</param>
        /// <param name="secureKey">secureKey</param>
        /// 
        /// <returns>desifrovany retezec</returns>
        public static string Decrypt(string data, string secureKey) {
            byte[] cData = Hex2Byte(data);

            // Vytvorime instanci 3DES algoritmu, nastavime parametry
            TripleDESCryptoServiceProvider alg = new TripleDESCryptoServiceProvider();
            alg.Mode = CipherMode.ECB;
            alg.GenerateIV();
            alg.Key = Encoding.Default.GetBytes(secureKey);
            alg.Padding = PaddingMode.None;

            // Vytvorime decryptor
            ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);

            MemoryStream ms;
            CryptoStream cs;
            String decryptedData = "";

            try {
                ms = new MemoryStream(cData.Length);
                cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
                cs.Write(cData, 0, cData.Length);
                decryptedData = Encoding.UTF8.GetString(ms.ToArray());

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());
            }

            return decryptedData.TrimEnd('\0');
        }
开发者ID:avaxxx,项目名称:ItronPayment,代码行数:38,代码来源:GopayHelper.cs

示例14: Encrypt

        /// <summary>
        /// Sifrovani dat 3DES
        /// - v pripade, ze vstupni data nemaji validni format vyhazuje GopayException
        /// </summary>
        /// 
        /// <param name="data">data</param>
        /// <param name="secureKey">secureKey</param>
        /// 
        /// <returns>zasifrovana data</returns>
        public static string Encrypt(string data, string secureKey) {
            // Vytvorime instanci 3DES algoritmu, nastavime parametry
            TripleDESCryptoServiceProvider alg = new TripleDESCryptoServiceProvider();
            alg.Padding = PaddingMode.Zeros;
            alg.Mode = CipherMode.ECB;
            alg.GenerateIV();
            try {
                alg.Key = new ASCIIEncoding().GetBytes(secureKey);

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());
            }

            // Vytvorime encryptor
            ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);
            byte[] encryptedByte;

            try {
                sw.Write(data);
                sw.Flush();
                cs.FlushFinalBlock();

                encryptedByte = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(encryptedByte, 0, (int)ms.Length);

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());

            } finally {
                ms.Close();
                ms.Dispose();

                cs.Close();
                cs.Dispose();

                sw.Close();
                sw.Dispose();
            }

            StringBuilder encryptedData = new StringBuilder();
            foreach (byte b in encryptedByte) {
                try {
                    encryptedData.Append(String.Format("{0:x2}", b));

                } catch (Exception ex) {
                    throw new GopayException(ex.ToString());
                }
            }

            return encryptedData.ToString();
        }
开发者ID:avaxxx,项目名称:ItronPayment,代码行数:65,代码来源:GopayHelper.cs

示例15: EncryptFile

        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;
        }
开发者ID:kumaraguruv,项目名称:codeword,代码行数:66,代码来源:CwCryptoHelper.cs


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