How to Generate Public/Private Key Using RSA

Public/Private key in .net using C# is very easy. Dotnet framework provides several classes in System.Security.Cryptography namespace.

RSACryptoServiceProvider is class which is used to generate public/private key pairs. This class provides several methods to generate keys and do encryption and decryption. Here is one sample code in C# which is generating public/private key pair and public ley as XML string.

    public class MyCrypto
        RSACryptoServiceProvider rsa = null;
        string publicPrivateKeyXML;
        string publicOnlyKeyXML;
        public void AssignNewKey()
            const int PROVIDER_RSA_FULL = 1;
            const string CONTAINER_NAME = "KeyContainer";
            CspParameters cspParams;
            cspParams = new CspParameters(PROVIDER_RSA_FULL);
            cspParams.KeyContainerName = CONTAINER_NAME;
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            rsa = new RSACryptoServiceProvider(cspParams);

            //Pair of public and private key as XML string.
            //Do not share this to other party
            publicPrivateKeyXML = rsa.ToXmlString(true);

            //Private key in xml file, this string should be share to other parties
            publicOnlyKeyXML = rsa.ToXmlString(false);

Method ToXmlString(true) will generate public/private key pair and ToXmlString(false) will generate only public key. publicOnlyKeyXML should be shared with other party to encrypt data while publicPrivateKeyXML will be used to decrypt data.

After generating these keys xml one can directly make instance of RSACryptoServiceProvider as given below.

For encrypting data use publicOnlyKeyXMl as given below

public byte[] Encrypt(string publicKeyXML, string dataToDycript)
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    return rsa.Encrypt(ASCIIEncoding.ASCII.GetBytes(dataToDycript), true);

Above method will encrypt data with public key.

For decrypting data use  publicPrivateKeyXML  as given below.

public string Decrypt(string publicPrivateKeyXML, byte[] encryptedData)
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

    return ASCIIEncoding.ASCII.GetString( rsa.Decrypt(encryptedData, true));