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


C# RSACryptoServiceProvider.ToXmlString方法代码示例

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


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

示例1: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        var rsa = new RSACryptoServiceProvider();
        _privateKey = rsa.ToXmlString(true);
        _publicKey = rsa.ToXmlString(false);

        EncriptadorTripleDES des = new EncriptadorTripleDES();

        //string text = "1-/Ola/DIego/Dub/aca";

        //var resultadoEncryp = des.Encrypt(text, true);
        //var resultadoDEncryp = des.Decrypt(resultadoEncryp, true);

        //var md5 = MD5Hash(text);
        //var reverMd5 = retornoNormal(md5);

        //var enc = Encrypt(text);
        //Console.WriteLine("RSA // Encrypted Text: " + enc);
        //var dec = Decrypt(enc);
        //Console.WriteLine("RSA // Decrypted Text: " + dec);
    }
开发者ID:di3goandres,项目名称:Proyecto3,代码行数:21,代码来源:login.master.cs

示例2: Main

    public static void Main(String[] args) {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 128; //  192;
        aes.Key = new byte[] {0xC7, 0x42, 0xD1, 0x37, 0x4B, 0xAC, 0xFE, 0x94,
                              0x9D, 0x59, 0x79, 0x92, 0x71, 0x48, 0xD6, 0x8E};
//                              ,1,2,3,4,5,6,7,8};

        byte[] aesKey = aes.Key;
        if (args.Length > 0) {
            FileStream fs = new FileStream(args[0], FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            String xmlString = sr.ReadToEnd();
            rsa.FromXmlString(xmlString);
        } else {
            FileStream fs = new FileStream("rsa.xml", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(rsa.ToXmlString(true));
            sw.Close();
        }
        Console.WriteLine("RSA Key is:\n"+rsa.ToXmlString(true));

        Console.WriteLine("AES Key is:");
        PrintByteArray(aesKey);
        byte[] encryptedKey1 = rsa.Encrypt(aesKey, true);
        Console.WriteLine("Encrypted AES Key is:");
        PrintByteArray(encryptedKey1);
        byte[] decryptedKey1 = rsa.Decrypt(encryptedKey1, true);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey1);

        byte[] encryptedKey2 = rsa.Encrypt(aesKey, false);
        Console.WriteLine("Encrypted2 AES Key is:");
        PrintByteArray(encryptedKey2);
        byte[] decryptedKey2 = rsa.Decrypt(encryptedKey2, false);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey2);

    }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:39,代码来源:RSAOAEP.cs

示例3: GetRASKey

    /// <summary>
    /// 得到RSA的解谜的密匙对
    /// </summary>
    /// <returns></returns>
    public static RSAKey GetRASKey()
    {
        RSACryptoServiceProvider.UseMachineKeyStore = true;
        //声明一个指定大小的RSA容器
        RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(DWKEYSIZE);
        //取得RSA容易里的各种参数
        RSAParameters p = rsaProvider.ExportParameters(true);

        return new RSAKey()
        {
            PrivateKey = ToBase64Key(rsaProvider.ToXmlString(true)),
            PublicKey = ToBase64Key(rsaProvider.ToXmlString(false)),
            PublicKeyExponent = BytesToHexString(p.Exponent),
            PublicKeyModulus = BytesToHexString(p.Modulus)
        };
    }
开发者ID:hj-nicholas,项目名称:BaseFrame,代码行数:20,代码来源:RSAHelper.cs

示例4: RSATest

    private static void RSATest()
    {
        var publicPrivateRsa = new RSACryptoServiceProvider
            (
                new CspParameters()
                {
                    KeyContainerName = "PublicPrivateKeys",
                    Flags = CspProviderFlags.UseMachineKeyStore
                    //Flags = CspProviderFlags.UseDefaultKeyContainer
                }
            )
        {
            PersistKeyInCsp = true,
        };

        var publicRsa = new RSACryptoServiceProvider(
                new CspParameters()
                {
                    KeyContainerName = "PublicKey",
                    Flags = CspProviderFlags.UseMachineKeyStore
                    //Flags = CspProviderFlags.UseDefaultKeyContainer
                }
            )
        {
            PersistKeyInCsp = true
        };

        //Export the key.
        publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false));
        Console.WriteLine(publicRsa.ToXmlString(false));
        Console.WriteLine(publicPrivateRsa.ToXmlString(false));
        //Dispose those two CSPs.
        using (publicRsa)
        {
            publicRsa.Clear();
        }
        using (publicPrivateRsa)
        {
            publicRsa.Clear();
        }

        //Retrieve keys
        publicPrivateRsa = new RSACryptoServiceProvider(
                new CspParameters()
                {
                    KeyContainerName = "PublicPrivateKeys",
                    Flags = CspProviderFlags.UseMachineKeyStore
                    //Flags = CspProviderFlags.UseDefaultKeyContainer
                }
            );

        publicRsa = new RSACryptoServiceProvider(
                new CspParameters()
                {
                    KeyContainerName = "PublicKey",
                    Flags = CspProviderFlags.UseMachineKeyStore
                    //Flags = CspProviderFlags.UseDefaultKeyContainer
                }
            );
        Console.WriteLine(publicRsa.ToXmlString(false));
        Console.WriteLine(publicPrivateRsa.ToXmlString(false));
        using (publicRsa)
        {
            publicRsa.Clear();
        }
        using (publicPrivateRsa)
        {
            publicRsa.Clear();
        }
    }
开发者ID:ATouhou,项目名称:QuranCode,代码行数:70,代码来源:Numbers.cs

示例5: GenerateRSAKeys

    public static void GenerateRSAKeys(string username)
    {
        try
        {
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH.mm.ss");
            if (!String.IsNullOrEmpty(username))
            {
                username = username.Replace(" ", "");
                username = username.Replace(".", "");
                username = username.Replace("\b", "");
                username = username.Replace("\t", "");
                username = username.Replace("\r", "");
                username = username.Replace("\n", "");
            }
            else
            {
                username = "";
            }

            int key_length = 16 * 1024; // in bits
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(key_length);

            string private_key_filename = NUMBERS_FOLDER + "/" + timestamp + "_" + username + ((username.Length == 0) ? "" : "_") + "PrivateKey.xml";
            using (StreamWriter writer = new StreamWriter(private_key_filename, false, Encoding.Unicode))
            {
                writer.WriteLine(provider.ToXmlString(true));
            }

            string public_key_filename = NUMBERS_FOLDER + "/" + timestamp + "_" + username + ((username.Length == 0) ? "" : "_") + "PublicKey.xml";
            using (StreamWriter writer = new StreamWriter(public_key_filename, false, Encoding.Unicode))
            {
                writer.WriteLine(provider.ToXmlString(false));
            }
        }
        catch
        {
            // silence IO error in case running from read-only media (CD/DVD)
        }
    }
开发者ID:ATouhou,项目名称:QuranCode,代码行数:39,代码来源:Numbers.cs

示例6: Entry


//.........这里部分代码省略.........
        //            stream.Read(x509key, 0, datalen);
        //            stream.Close();
            return;

        }
        x509size = x509key.Length;

        //Console.WriteLine(sb.ToString()) ;
        //PutFileBytes("x509key", x509key, x509key.Length) ;

        // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
        MemoryStream mem = new MemoryStream(x509key);
        BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
        byte bt = 0;
        ushort twobytes = 0;

        try
        {

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130)	//data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();	//advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();	//advance 2 bytes
            else
                return;

            seq = binr.ReadBytes(15);		//read the Sequence OID
            if (!CompareBytearrays(seq, SeqOID))	//make sure Sequence for OID is correct
                return;

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8103)	//data read as little endian order (actual data order for Bit String is 03 81)
                binr.ReadByte();	//advance 1 byte
            else if (twobytes == 0x8203)
                binr.ReadInt16();	//advance 2 bytes
            else
                return;

            bt = binr.ReadByte();
            if (bt != 0x00)		//expect null byte next
                return;

            twobytes = binr.ReadUInt16();
            if (twobytes == 0x8130)	//data read as little endian order (actual data order for Sequence is 30 81)
                binr.ReadByte();	//advance 1 byte
            else if (twobytes == 0x8230)
                binr.ReadInt16();	//advance 2 bytes
            else
                return;

            twobytes = binr.ReadUInt16();
            byte lowbyte = 0x00;
            byte highbyte = 0x00;

            if (twobytes == 0x8102)	//data read as little endian order (actual data order for Integer is 02 81)
                lowbyte = binr.ReadByte();	// read next bytes which is bytes in modulus
            else if (twobytes == 0x8202)
            {
                highbyte = binr.ReadByte();	//advance 2 bytes
                lowbyte = binr.ReadByte();
            }
            else
                return;
            byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
            int modsize = BitConverter.ToInt32(modint, 0);

            int firstbyte = binr.PeekChar();
            if (firstbyte == 0x00)
            {	//if first byte (highest order) of modulus is zero, don't include it
                binr.ReadByte();	//skip this null byte
                modsize -= 1;	//reduce modulus buffer size by 1
            }

            byte[] modulus = binr.ReadBytes(modsize);	//read the modulus bytes

            if (binr.ReadByte() != 0x02)			//expect an Integer for the exponent data
                return;
            int expbytes = (int)binr.ReadByte();		// should only need one byte for actual exponent data (for all useful values)
            byte[] exponent = binr.ReadBytes(expbytes);

            showBytes("\nExponent", exponent);
            showBytes("\nModulus", modulus);

            // ------- create RSACryptoServiceProvider instance and initialize with public key -----
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAKeyInfo = new RSAParameters();
            RSAKeyInfo.Modulus = modulus;
            RSAKeyInfo.Exponent = exponent;
            RSA.ImportParameters(RSAKeyInfo);

            xmlpublickey = RSA.ToXmlString(false);
            // Console.WriteLine("XML encoded RSA public key:\n{0}", xmlpublickey);
        }

        finally
        {
            binr.Close();
        }
    }
开发者ID:hajimen,项目名称:flowerflower,代码行数:101,代码来源:pempublic.cs

示例7: StartListening

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[16000];

        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
           // Console.ReadLine();
        string answer = null;
        byte[] aesKey = null;
        answer = Console.ReadLine();
        if (answer == "gen")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
            string rsaKey = rsa.ToXmlString(true);
            File.WriteAllText("c:\\private.txt", rsaKey);
            Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
        }
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        answer = Console.ReadLine();
        if (answer == "enc")
        {
            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Ожидание соединения...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
                    Console.Read();
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.AddExtension = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                        {
                            myAes.KeySize = 256;
                            myAes.GenerateKey();
                           // myAes.Padding = PaddingMode.None;
                            aesKey = myAes.Key;
                            Console.WriteLine(dlg.FileName);
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                            byte[] df = rsa.Encrypt(myAes.Key, false);
                            byte[] mes = Encoding.ASCII.GetBytes("{Key}");

                            byte[] newArray = new byte[df.Length + mes.Length];
                            Array.Copy(mes, 0, newArray, 0, mes.Length);
                            Array.Copy(df, 0, newArray, mes.Length, df.Length);
                            handler.Send(newArray);
                        }
                    }
                    Thread.Sleep(1000);
                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);

                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("Ключ") > -1)
                        {
                            Console.Write("\nКлюч был успешно отправлен!\n");
                            byte[] encMes = EncryptFile(dlg.FileName, aesKey);
                            handler.Send(encMes);
                            Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            break;
                        }
                    }
                    //Thread.Sleep(1000);

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        Console.WriteLine("\nНажмите Enter для продолжения\n");
        Console.Read();
    }
开发者ID:Zlover,项目名称:CipherFile,代码行数:99,代码来源:Program.cs


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