C#rsa algorithm implementation + How to convert the public key into PEM format for object-c use

Source: Internet
Author: User
Tags decrypt modulus



. NET, for security reasons, the RSACryptoServiceProvider class, which only has both a public and private key to decrypt. The reason is that the public key is public and will be held by multiple people. Such data transmission is not secure. C#rsa private key encryption, public key decryption error reason!

Using RSA algorithm to generate public and private key methods in C #:


After the public key is generated, it is saved under the folder with the same name, such as:



Public key generation, where the path is "Rsa\rsa\bin\debug"
 
Using System;
Using System.IO;
Using System.Security.Cryptography;//must reference

Namespace RSA
{
     Class Program
     {
         Static void Main(string[] args)
         {
             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
             Using (StreamWriter writer = new StreamWriter("PrivateKey.xml")) //This file should be kept secret...
             {
                 writer.WriteLine(rsa.ToXmlString(true));
             }
             Using (StreamWriter writer = new StreamWriter("PublicKey.xml"))
            {
                 writer.WriteLine(rsa.ToXmlString(false));
            }
         }
     }
}



Method Two:
Public static void GKEY()//(computer) generates a key GKEY(generate key),generate the RSA public and private keys
     {
         Using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
         {
             String publicKey = rsa.ToXmlString(false); // public key
             String privateKey = rsa.ToXmlString(true); // private key
         }
     }


Direct breakpoint mode copy public key out


RSA Cryptographic Decryption Class
#region RSA
    /// <summary>
    /// RSA encryption
    /// </summary>
    /// <param name="publickey"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    Public static string RSAEncrypt(string publickey, string content)
    {
        publickey = @ "<RSAKeyValue> <Modulus> 0wE26IHp4U9OLtPhJ + fT8ej6aWORFP8pd ++ MjUuhkQQm / zhcImbxQbjxtSAftz + kkDwGDFJpSldQPyigOGcUx7PofTc6VhiFik9E9SsxV9n0iEEtqUndDfmBJfPAWt + 4UDMwKakgZqFoapDuwjKlTErFvKCyKCs + qN9OZvZwKWk = </ Modulus> <Exponent> AQAB </ Exponent> </ RSAKeyValue>";
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        Byte[] cipherbytes;
        rsa.FromXmlString(publickey);
        Cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);

        Return Convert.ToBase64String(cipherbytes);

    }

    /// <summary>
    /// RSA decryption
    /// </summary>
    /// <param name="privatekey"></param>
    /// <param name="content"></param>
    /// <returns></returns>
    Public static string RSADecrypt(string privatekey, string content)
    {
        privatekey = @ "<RSAKeyValue> <Modulus> 0wE26IHp4U9OLtPhJ + fT8ej6aWORFP8pd ++ MjUuhkQQm / zhcImbxQbjxtSAftz + kkDwGDFJpSldQPyigOGcUx7PofTc6VhiFik9E9SsxV9n0iEEtqUndDfmBJfPAWt + 4UDMwKakgZqFoapDuwjKlTErFvKCyKCs + qN9OZvZwKWk = </ Modulus> <Exponent> AQAB </ Exponent> <P> 8Ei6NIsZtgV3DQjuGHfGLS6o1O + IUXxzjqLxdMm77yhEPUxR9YPIxODJ2VVTddXSAHxViJJt30yJ7JhVz6cpQw == </ P> < Q> 4M49NrmalgVQFMsea2RMB1qN8fAPfIw5G9q9hzsLcWSCmkeRRIQlvPYflVEKAYKiDVVzENETbnnduFXWBABx4w == </ Q> <DP> t + JQbemN0Zi5FQaif6MZzHYKynpNTl75aE0Wj5Pa + RlNr8N6bXNe8Bw / HM2Jw4HQ5oJASvYUk3DVlHS4JuP8VQ == </ DP> <DQ> lT62iv9brp9mU / epgVh71SH8PJPIZEJfo6tryjyb0zMMNcqvmZI1z6aCv0mm3 + vPFBUXqCF1yhFj7n4l8FAvSw == </ DQ> <InverseQ> flrvgxHvf4l + fdymEVDgKjsfGqshOpppoNgZj9kpeWBto3o8z ++ Ki6eSLQT3nVnpx2QCZeTWkxTED4nhSLKscw == </ InverseQ> <D> cQTCg1Eqk7sltmFYxUYgOP / AOPjSufteG9acYwYymPkvZh6rAuY + rSRBmvGE62NUYskzuB / gM6iG2 / 2HrA5SixfNgCvZ + nsK + kX5pzQRsYdD71ViQW0hOanXwj45I2zHRgBiuTtCUP0fs5pISmQkaeJkDL5pO2l + wvlgl + wunj0 = </ D> </ RSAKeyValue> ";
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        Byte[] cipherbytes;
        rsa.FromXmlString(privatekey);
        Cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);

        Return Encoding.UTF8.GetString(cipherbytes);
    }
    #endregion 




How do I convert the public key to PEM format in XML format?


Need to rely on a third-party library called Bouncycastle
The code to get the installation package online is as follows:


PM > Install-package bouncycastle


If you don't know how to open the vs2013 console, look below
Tips: Open the VS2013 console method



Open the VS2013 console method. png

Install third-party library success diagram. png method one: Online conversion

Click here to jump >> online conversion

How do I transfer the key XML format and PEM format? "Tips: Here's the key, the public key uses a different method." First, convert the XML format key to PEM
Public static void XMLConvertToPEM()//XML format key to PEM
     {
         Var rsa2 = new RSACryptoServiceProvider();
         Using (var sr = new StreamReader("e:\\PrivateKey.xml"))
         {
             rsa2.FromXmlString(sr.ReadToEnd());
         }
         Var p = rsa2.ExportParameters(true);

         Var key = new RsaPrivateCrtKeyParameters(
             New BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D),
             New BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ),
             New BigInteger(1, p.InverseQ));

         Using (var sw = new StreamWriter("e:\\PrivateKey.pem"))
         {
             Var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
             pemWriter.WriteObject(key);
         }
     }




One, the PEM format key to XML
 
 
Public static void PEMConvertToXML()//PEM format key to XML
    {
        AsymmetricCipherKeyPair keyPair;
        Using (var sr = new StreamReader("e:\\PrivateKey.pem"))
        {
            Var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
            keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
        }
        Var key = (RsaPrivateCrtKeyParameters)keyPair.Private;
        Var p = new RSAParameters
        {
            Modulus = key.Modulus.ToByteArrayUnsigned(),
            Exponent = key.PublicExponent.ToByteArrayUnsigned(),
            D = key.Exponent.ToByteArrayUnsigned(),
            P = key.P.ToByteArrayUnsigned(),
            Q = key.Q.ToByteArrayUnsigned(),
            DP = key.DP.ToByteArrayUnsigned(),
            DQ = key.DQ.ToByteArrayUnsigned(),
            InverseQ = key.QInv.ToByteArrayUnsigned(),
        };
        Var rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters(p);
        Using (var sw = new StreamWriter("e:\\PrivateKey.xml"))
        {
            sw.Write(rsa.ToXmlString(true));
        }
    } 


Please click: reference

Other "Tips: Pending Test"


Generation and use of CER and PFX certificates



CER and PFX certificates. png
Generate public key. png


C#rsa algorithm Implementation + How to convert the public key to PEM format for object-c use


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.