Generating Public/Private Keys In C# And .NET (2024)

Generating Public/Private Keys In C# And .NET (1)

  • 223.6k
  • 0
  • 23

Asymmetric cryptography also known as public-key encryption uses a public/private key pair to encrypt and decrypt data. Public key in asymmetric cryptography is available to public but the private key must be protected with the user, else it can be used to decrypt data.

In .NET, the RSACryptoServiceProvider and DSACryptoServiceProvider classes are used for asymmetric encryption. A random public/private key pair is generated when a new instance of the class is created.

  1. RSACryptoServiceProviderRSA=newRSACryptoServiceProvider();

Once keys are generated, we can use ToXmlString or ExportParameters method to read the keys.

The ToXmlString method returns key information in XML as a string. The method takes a Boolean parameter. If passed false, it returns public key only. If passed true, it returns both private and public pair.

The following code snippet returns a public key.

  1. stringstr=RSA.ToXmlString(false);

The public key looks like the following with a Modulus value and an Exponent value.

  1. <RSAKeyValue>
  2. <Modulus>lF1Yof6FXaY9M/StHwPC1voW5K5JOqSu8BXndS4WH06L9mOfrNI9Et0cRaHjiYd2bQNFZB9+AZmN4ODc36DgVPqQqYY2tbH+9UY0hcdi+WnDuUZe7sgvWKfGwBKTcy7g8uUAzpTWEP1W0FqeMunmXljD8Iouoqp5oHtTW1GHIlE=</Modulus>
  3. <Exponent>AQAB</Exponent>
  4. </RSAKeyValue>

When a true value is passed.

  1. stringstr=RSA.ToXmlString(true);

The output looks like the following that has both public and private keys.

  1. <RSAKeyValue>
  2. <Modulus>tMvvUeHhggKAVex8JzYKXYQ32HVmr05PdtT1KV3kTkKE26jO/9IVmg+bWwxR1vuMzmY7spwguSJQsnjutJXamH0mblNgYHmWwhyhJMSTtnZp57VDNNedjCFQnLOn211yk/PpCQHEiDDvt84hnmcdXNBlfZfkQzQ+UO/elhP5NH0=</Modulus>
  3. <Exponent>AQAB</Exponent>
  4. <P>22SSx3JpSqYVUWuxiSKwmh/8RDDcgDvq8l+4dMlQ/F+BJhthTQ3UJGupWaxiJyXX95AYAJIJJvWVvmvI7tqbxw==</P><Q>0va2WFy0oUwX4eJtZElRbot9TOrwGcqI64rMAYjvxl/mayCRXf0ypwKofKWOsmjK/pX0xWaqnFWB/NdLFt4Fmw==</Q><DP>VbIYPz2qcRUkmJQnWbiqINnDkONBDfnZkOjgxQVp09p+OONTA2UWa09+a9+Qy1fV3wZyya5BUu10m1fAucO8Ow==</DP>
  5. <DQ>Lm8hOZfGJk6SXySwgUdmBhfrz3dSu8qJkpatSpUyeY54MBIuDOsDMCF0pmLmYryQGbM1+hEb8mcbwmQ84d6iiw==</DQ>
  6. <InverseQ>L67OLIIK+M3OF1nxSHTjZ+Kv/hwOHJPvdHHSuh9VEmw93kPGn6Qt6GudEreFb6xlFsuR6UM19LUIweapgaUagQ==</InverseQ>
  7. <D>YbaGlZ6bHoTzj3zMbPTMDVbUR+zLnpuYXwUhq0XPimxxGbbWiXSlsCoXMNIruSEjLLocMaAoH2bobkzl1jvXdAI30NdZ/rpG5SRldpaeIundLfHkSnZfHwHuP9OGXJSXmbmLCrO8dq7BjLauS4JiTRgjiXoq8c995MEF+vhw9hE=</D>
  8. </RSAKeyValue>

The ExportParameters method returns an RSAParameters structure that holds the key information in separate fields.

  1. //Getkeyintoparameters
  2. RSAParametersRSAKeyInfo=RSA.ExportParameters(true);
  3. Console.WriteLine($"Modulus:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Modulus)}");
  4. Console.WriteLine($"Exponent:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Exponent)}");
  5. Console.WriteLine($"P:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.P)}");
  6. Console.WriteLine($"Q:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Q)}");
  7. Console.WriteLine($"DP:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.DP)}");
  8. Console.WriteLine($"DQ:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.DQ)}");

Here is a complete working example.

  1. usingSystem;
  2. usingSystem.Security.Cryptography;
  3. classPrivatePublicKeyGenerator{
  4. staticvoidMain(string[]args){
  5. //Generateapublic/privatekeyusingRSA
  6. RSACryptoServiceProviderRSA=newRSACryptoServiceProvider();
  7. //Readpublickeyinastring
  8. stringstr=RSA.ToXmlString(true);
  9. Console.WriteLine(str);
  10. //Getkeyintoparameters
  11. RSAParametersRSAKeyInfo=RSA.ExportParameters(true);
  12. Console.WriteLine($"Modulus:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Modulus)}");
  13. Console.WriteLine($"Exponent:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Exponent)}");
  14. Console.WriteLine($"P:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.P)}");
  15. Console.WriteLine($"Q:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.Q)}");
  16. Console.WriteLine($"DP:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.DP)}");
  17. Console.WriteLine($"DQ:{System.Text.Encoding.UTF8.GetString(RSAKeyInfo.DQ)}");
  18. Console.ReadKey();
  19. }
  20. }
Generating Public/Private Keys In C# And .NET (2024)

FAQs

How to create public key and private key in C#? ›

Here is a complete working example.
  1. using System;
  2. using System.Security.Cryptography;
  3. class PrivatePublicKeyGenerator {
  4. static void Main(string[] args) {
  5. // Generate a public/private key using RSA.
  6. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  7. // Read public key in a string.
Jan 8, 2019

How do I generate a public and private key? ›

To generate an SSH private/public key pair for your use, you can use the ssh-keygen command-line utility. You can run the ssh-keygen command from the command line to generate an SSH private/public key pair. If you are using Windows, by default you may not have access to the ssh-keygen command.

Which algorithm is used to generate public and private keys? ›

Public Key Cryptography (asymmetric) uses encryption algorithms such as RSA and Elliptic Curve Cryptography (ECC) to create the public and private keys.

How many public keys can be generated from a private key? ›

It's actually possible to generate several public keys from the same private key. However, you'll only ever have one private key. And while it's theoretically possible to guess or calculate the public key from the private key, the reverse would take hundreds of years to crack.

How to generate public and private key in PEM format? ›

How to generate an RSA PEM (asymmetric) key pair?
  1. openssl genrsa -aes256 -out private-key.pem 4096.
  2. openssl rsa -in private-key.pem -pubout > public-key.pem.
  3. cat public-key.pem.
Jan 24, 2023

How to generate private and public key in Windows? ›

For Windows 10 & 11
  1. Press the Windows key or open up the Start Menu. Type “cmd”.
  2. Under “Best Match”, click “Command Prompt”.
  3. In the command prompt, use the ssh-keygen command: ...
  4. The system will now generate the key pair and display the key fingerprint and a randomart image. ...
  5. Open your file explorer.

How are private keys generated? ›

How Is a Private Key Generated? Private keys are usually generated by a user's Bitcoin wallet. However, the user almost never has to see or directly interact with their private keys as their wallet handles all of the complex math behind the scenes. Bitcoin wallets use an industry standard to derive private keys.

Can a private key be used to generate a public key? ›

In this article, we've looked at how we can generate the public key from a given private key using different command-line tools. We've started by demonstrating the ssh-keygen command, which allows us to also convert the public key into different formats in addition to generating it.

How to generate secret key in C#? ›

The following code snippet generates a key and IV using TripleDES algorithm.
  1. TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
  2. TDES. GenerateIV();
  3. TDES. GenerateKey();
Jan 8, 2019

How do I create a public and private key for JWT? ›

Generate JWT Keys
  1. openssl genrsa -out ./private.key 4096.
  2. ssh-keygen -t rsa -b 4096 -m PEM -f private.key.
  3. openssl rsa -in private.key -pubout -outform PEM -out public.key.
  4. ssh-keygen -f private.key -e -m PKCS8 > public.key.

Can we create private class in C#? ›

You cannot have a private class unless it is nested. In what scenario other then for an innter class would you like to have a 'private' class ? You can use the internal modifier to create a class that is only visible in the current assembly.

How to create private method in C#? ›

To set private methods, use the private access specifier. Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.

Top Articles
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5778

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.