STORM
STORM

Reputation: 4331

How to encrypt with private key and decrypt with public key in c# RSA

I found several solutions where I can use the .Net RSA Provider to Encrypt a message with the public key and Decrypt it with the private one.

But what I want to have is to Encrypt with the private key and Decrypt with the public key.

I want t store the public key in my app and encrypt a license for example on my dev machine with the private key, send it to the app and let the information decrypt with a public key.

How can I achieve that?

Upvotes: 21

Views: 34276

Answers (1)

Syeda Zunaira
Syeda Zunaira

Reputation: 5206

You can use signature generation, In which the private key is used to generate a signature that verifies that your message is authentic.

// Create message and signature on your end
string message = "Here is the license message";

var converter = new ASCIIEncoding();
byte[] plainText = converter.GetBytes(message);

var rsaWrite = new RSACryptoServiceProvider();
var privateParams = rsaWrite.ExportParameters(true);

// Generate the public key / these can be sent to the user.
var publicParams = rsaWrite.ExportParameters(false);

byte[] signature =
    rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider());

// Verify from the user's side. Note that only the public parameters
// are needed.
var rsaRead = new RSACryptoServiceProvider();
rsaRead.ImportParameters(publicParams);
if (rsaRead.VerifyData(plainText,
                       new SHA1CryptoServiceProvider(),
                       signature))
{
    Console.WriteLine("Verified!");
}
else
{
    Console.WriteLine("NOT verified!");
}

you can take further help from HERE

Upvotes: 16

Related Questions