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


C# RSACryptoServiceProvider.FromXmlString方法代码示例

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


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

示例1: signSamlElement

    /// <summary>
    /// Sign the XML String of SamlResponse
    /// </summary>
    /// <param name="xmlString"></param>
    /// <returns>Digital signed SamlReponse string</returns>
    public static String signSamlElement(String xmlString)
    {
        // Create a new CspParameters object to specify a key container.
         CspParameters cspParams = new CspParameters();

         cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
         //    cspParams.KeyContainerName = "GOOGLE";
        //     cspParams.ProviderName = "HF";

         string pb = "<RSAKeyValue><Modulus>wTI341fDKEG9mV9VDFRj/XKf5nZxfadISavENRbwPlKZBipYAi6zgVNPJ7nhSH4qdXqphOreXFFmwsg8JzxHLJRJ8yjIfiG3ORuRaHO0dpTslSQ4wz5qVroj4avI3m5pL6jFgtaWJkWlr7uzq4xrdKwu+wZiOaNNCFjqUo18ycE=</Modulus><Exponent>AQAB</Exponent><P>86FAPMQJey3PrI+PBPnMgn8xzR3qy/WBjUihKn+Fb9tP7GipWD9oi3tkdR/KZfBcvSoacDQqxMg8Y+aY90glGQ==</P><Q>ywFrg+GccDYsFwOZJsgzC8FXBQf9jalFbfuRdjrrH0Cd2JqHXC/nrpc7YB3qOORaWSuxWorGdN3+o42qszX26Q==</Q><DP>L3udDnrSsjxCfopYQIsDDegGZ8jN60SFJGkkaCkEc8GVuSjI4JczJAQ/lwhEJUwMdx3Om1G/iCzSgFIAPCnGeQ==</DP><DQ>HX0nUREE2IgF/5HWPXv3bk23hlOS0XE1VLSmfLYyUWfhhgVshEexL/tn9J5j17/UH//o0241ReS5iKibk0zTgQ==</DQ><InverseQ>IC++K/C2NT5w01BYp5dcB1sXmWH32oFB1bmgcAkwK2VbQm9a9Xt1YdXtMVUEkxln7Inciny8oEfwdDiUjc82KQ==</InverseQ><D>byvGnTvTQUcTIz6IYh/tqdpbyPI/PF8Wac49iY85j6NYCwQywI6/HJwj4GhGCsEPDasYATRl4Bm3WD6A3tMA4NUw/RYfdutL2vDXjYXZMETWnABeeTdPK9haPw/NrcvhWRkGqNyeHG1soqmrF/x/0Xh5EYTv4KtrIJrPpKFajAE=</D></RSAKeyValue>";
        // Create a new RSA signing key and save it in the container.
         RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();

            /*  RSACryptoServiceProvider rsaKey;
         if (System.Web.HttpContext.Current == null) // WinForm
             rsaKey = new RSACryptoServiceProvider();
         else // WebForm - Uses Machine store for keys
             rsaKey = new RSACryptoServiceProvider(cspParams);
        */

         rsaKey.FromXmlString(pb);

          /*  X509Certificate2 cert = new X509Certificate2(@"C:\certificate.pfx", "");
        RSACryptoServiceProvider rsaKey = cert.PrivateKey as RSACryptoServiceProvider;*/

           // Create a new XML document
        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML String into the XmlDocument object
        xmlDoc = Util.createXmlDom(xmlString);

        // Sign the XML document
        SignXml(xmlDoc, rsaKey);

        // convert XmlDocument to String
           /*     MemoryStream stream = new MemoryStream();

        XmlTextWriter writer = new XmlTextWriter(stream, null);

        writer.Formatting = Formatting.Indented;

        xmlDoc.Save(writer);

        StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);

        stream.Position = 0;

        string res = sr.ReadToEnd();

        sr.Close();

        stream.Close();

        return res;
        * */

        return xmlDoc.OuterXml;
    }
开发者ID:brooklynb7,项目名称:CGA,代码行数:63,代码来源:XmlDigitalSigner.cs

示例2: DecryptString

 /// <summary>
 /// 字符串解密
 /// </summary>
 /// <param name="encryptString">密文</param>
 /// <param name="privateKey">私钥</param>
 /// <returns>遇到解密失败将会返回原字符串</returns>
 public static string DecryptString(string encryptString, string privateKey)
 {
     string source = string.Empty;
     try
     {
         RSACryptoServiceProvider.UseMachineKeyStore = true;
         RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
         rsaProvider.FromXmlString(FromBase64Key(privateKey));
         byte[] data = rsaProvider.Decrypt(HexStringToBytes(encryptString), false);
         source = System.Text.Encoding.ASCII.GetString(data);
     }
     catch { }
     return source;
 }
开发者ID:hj-nicholas,项目名称:BaseFrame,代码行数:20,代码来源:RSAHelper.cs

示例3: Decrypt

    private static string Decrypt(byte[] encData)
    {
        var prvParams = "";

        using (var reader = new StreamReader(new FileStream("1.pub", FileMode.Open)))
        {
            prvParams = reader.ReadToEnd();
        }

        using (var rsa = new RSACryptoServiceProvider())
        {
            rsa.FromXmlString(prvParams);

            return ByteConverter.GetString(rsa.Decrypt(encData, false));
        }
    }
开发者ID:vrublevskiy,项目名称:UANB_wpf_client,代码行数:16,代码来源:Program.cs

示例4: EncryptString

 /// <summary>
 /// 字符串加密
 /// </summary>
 /// <param name="source">源字符串 明文</param>
 /// <param name="publicKey">公匙或私匙</param>
 /// <returns>加密遇到错误将会返回原字符串</returns>
 public static string EncryptString(string source, string key)
 {
     string encryptString = string.Empty;
     try
     {
         if (!CheckSourceValidate(source))
         {
             throw new Exception("source string too long");
         }
         RSACryptoServiceProvider.UseMachineKeyStore = true;
         RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
         rsaProvider.FromXmlString(FromBase64Key(key));
         byte[] data = rsaProvider.Encrypt(System.Text.Encoding.ASCII.GetBytes(source), false);
         encryptString = BytesToHexString(data);
     }
     catch{ }
     return encryptString;
 }
开发者ID:hj-nicholas,项目名称:BaseFrame,代码行数:24,代码来源:RSAHelper.cs

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

示例6: MazeUtil

    static MazeUtil()
    {
		//TODO:
		TextAsset textAsset = null;//JDKResourceManager.Instance.LoadAsset<TextAsset>(FileName);
        if (textAsset != null)
        {
            String pubKey;
            if (SimpleSymmetricCryptography.TryDecrypt(Encoding.ASCII.GetString(textAsset.bytes),
                Encoding.ASCII.GetString(Pwd), out pubKey))
            {
                Rsa = new RSACryptoServiceProvider();
                Rsa.FromXmlString(pubKey);
            }
            else
            {
                throw new Exception(String.Format("无效的公钥文件: {0} ,请核对后再试。", FileName));
            }
        }
        else
        {
            throw new Exception(String.Format("无法加载公钥文件: {0} , 请确认后再试。", FileName));
        }
    }
开发者ID:xclouder,项目名称:godbattle,代码行数:23,代码来源:MazeUtil.cs

示例7: Encrypt

	public static string Encrypt(string toEncrypt)
	{
		RSACryptoServiceProvider CSPRSA = null;
		string result;
		try
		{
			CSPRSA = new RSACryptoServiceProvider();
			CSPRSA.FromXmlString(SAFSecurityKeys.loadKeysFromFile());
			byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
			result = Convert.ToBase64String(CSPRSA.Decrypt(toEncryptArray, false));
		}
		catch
		{
			result = null;
		}
		finally
		{
			if (CSPRSA != null)
			{
				CSPRSA.Clear();
			}
		}
		return result;
	}
开发者ID:apedro-silva,项目名称:SF.Expand.SAF,代码行数:24,代码来源:CryptorEngineRSA.cs

示例8: verify

    /**
         * 根据传入的参数做验签
         * @param srcMsg 签名用源串
         * @param signMsg 通联响应中给出的签名串
         * @param certPath 证书路径
         * @param isAbsolatePath 是否绝对路径,如certpath参数值为证书绝对路径,则填true,否则填false
         */
    private bool verify(String srcMsg, String signMsg, String certPath, Boolean isAbsolatePath)
    {
        //base64解码签名串
            Byte[] signMsgBytes = decode(signMsg);

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            //读取x509证书
            X509Certificate2 x509 = new X509Certificate2();
            if (isAbsolatePath)
            {
                //设置证书的绝对路径
                //x509.Import(@"D:\cert\TLCert.cer");
                x509.Import(certPath);
            }
            else
            {
                //或者设置证书的相对路径
                //x509.Import(HttpContext.Current.Server.MapPath("../cert/TLCert.cer"));
                x509.Import(HttpContext.Current.Server.MapPath(certPath));
            }

            //x509.PublicKey.Key.ToXmlString();
            //灌注到rsa
            rsa.FromXmlString(x509.PublicKey.Key.ToXmlString(false));
            bool verifyResult = rsa.VerifyData(System.Text.Encoding.UTF8.GetBytes(srcMsg), "SHA1", signMsgBytes);

            return verifyResult;
    }
开发者ID:test-lin,项目名称:Utility-class,代码行数:35,代码来源:orderQueryResult.aspx.cs

示例9: encrypt

	public static byte[] encrypt(string PEMPublicKey, byte[] data) {
		byte[] encrData = null;
		
		if ((data != null) && (PEMPublicKey != null)) {
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			
			string publicKeyXml = opensslkey.DecodePEMKey(PEMPublicKey);
			if (publicKeyXml != null) {
				rsa.FromXmlString(publicKeyXml);
				
				encrData = rsa.Encrypt(data, false);
			}
			else {
				Console.WriteLine("incorrect PEM key. " + PEMPublicKey);
			}
		}
		
		return encrData;
	}
开发者ID:oupirum,项目名称:Cross-language_encryption,代码行数:19,代码来源:Encrypt.cs

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

示例11: StartClient

    public static void StartClient()
    {
        // Data buffer for incoming data.
        byte[] bytes;

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.
                //   byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

                // Send the data through the socket.
                // int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.

                string data = null;
                bytes = new byte[16000];
                while (true)
                {
                    int bytesCount = sender.Receive(bytes);

                    //answer = bytes;
                    data = Encoding.ASCII.GetString(bytes);
                    if (data.IndexOf("{Key}") > -1)
                    {
                        byte[] answer = new byte[256];
                        for (int i = 0; i < 256; i++)
                            answer[i] = bytes[i + 5];
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                        keyAES = rsa.Decrypt(answer, false);
                        byte[] buff = Encoding.UTF8.GetBytes("Ключ был успешно получен!");
                        sender.Send(buff);
                        Console.Write("Сессионный ключ был успешно получен\n");
                        data = null;
                        bytesCount = sender.Receive(bytes);

                        //answer = bytes;
                        data = Encoding.ASCII.GetString(bytes);

                    }
                    if (data!=null)
                    {

                        byte[] encMes = new byte[bytesCount];
                        Array.Copy(bytes, 0, encMes, 0, bytesCount);
                        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                        aes.KeySize = 256;
                        aes.Key = keyAES;
                        //aes.Padding = PaddingMode.Zeros;
                        byte[] iv = new byte[16];
                        aes.IV = iv;
                        ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                        // Create the streams used for decryption.
                        string plaintext;
                        using (MemoryStream msDecrypt = new MemoryStream(encMes))
                        {
                            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.
                                    plaintext = srDecrypt.ReadToEnd();
                                    File.WriteAllText("c:\\result", plaintext);
                                    Console.WriteLine("Расшифрованный принятый файл : {0}", plaintext);
                                }
                            }
                        }
                        break;
                    }
                }

                Console.Read();
                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
//.........这里部分代码省略.........
开发者ID:Zlover,项目名称:CipherFile,代码行数:101,代码来源:Program.cs

示例12: SignXML

    //-------------------------------------------------------------------------------------------
    private string SignXML(string xml)
    {
        // Signing XML Documents: http://msdn.microsoft.com/en-us/library/ms229745.aspx

          var rsaKey = new RSACryptoServiceProvider();
          string sales_licensekeys_privatekey = ConfigurationManager.AppSettings["sales_licensekeys_privatekey"];
          if (!File.Exists(sales_licensekeys_privatekey))
               throw new Exception("The private signing key is missing");
          rsaKey.FromXmlString(System.IO.File.ReadAllText(sales_licensekeys_privatekey));

          XmlDocument doc = new XmlDocument();
          doc.PreserveWhitespace = true;
          doc.LoadXml(xml);

          SignedXml signedXml = new SignedXml(doc);
          signedXml.SigningKey = rsaKey;

          // Create a reference to be signed.
          Reference reference = new Reference();
          reference.Uri = ""; // set to "" to sign the entire doc

          XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
          reference.AddTransform(env);

          signedXml.AddReference(reference);
          signedXml.ComputeSignature();

          XmlElement xmlDigitalSignature = signedXml.GetXml();

          doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

          MemoryStream ms = new MemoryStream();
          XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          //writer.Formatting = Formatting.Indented;

          doc.WriteContentTo(writer);
          writer.Flush();
          ms.Position = 0;
          StreamReader reader = new StreamReader(ms);
          return reader.ReadToEnd();
    }
开发者ID:weavver,项目名称:weavver,代码行数:43,代码来源:Sales_LicenseKeys.aspx.cs

示例13: Encrypt

    private static Byte[] Encrypt(string msg)
    {
        var pubParams = "";

        using (var reader = new StreamReader(new FileStream("1.pub", FileMode.Open)))
        {
            pubParams = reader.ReadToEnd();
        }

        using (var rsa = new RSACryptoServiceProvider())
        {
            rsa.FromXmlString(pubParams);

            return rsa.Encrypt(ByteConverter.GetBytes(msg), false);
        }
    }
开发者ID:vrublevskiy,项目名称:UANB_wpf_client,代码行数:16,代码来源:Program.cs


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