Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Private Key Rsa Encryption

I need to encrypt a string using an RSA 1.5 algorithm. I have been provided with a private key. However, I cannot for the life of me figure out how to add this key to the class. It seems as tho the key needs to be of type RSAParameter stuct. However this requires a set of values I have not been given such as Modulus, Exponent, P, Q, etc.. All I have is the private key. Can anyone help?

like image 314
Steve Kiss Avatar asked May 17 '11 11:05

Steve Kiss


People also ask

Can RSA private key be used for encryption?

RSA(Rivest-Shamir-Adleman) is an Asymmetric encryption technique that uses two different keys as public and private keys to perform the encryption and decryption. With RSA, you can encrypt sensitive information with a public key and a matching private key is used to decrypt the encrypted message.

How use RSA encryption in C#?

Create an RSA public/private keypair. Transmit the public key (or for proof of concept, just move it in a string variable) Create a new RSA crypto provider and encrypt a string with the public key. Transmit the encrypted string (or data) back to the original crypto provider and decrypt the string.

Can private key be used for encryption?

A private key is also used in asymmetric cryptography, which is also known as public key cryptography. In this case, the private key refers to the secret key of a public key pair. In public key cryptography, the private key is used for encryption and digital signatures.

Which is better RSA or AES?

RSA is more computationally intensive than AES, and much slower. It's normally used to encrypt only small amounts of data.


1 Answers

You should be aware of the Bouncycastle C# library. There are in particular two very useful classes: Org.BouncyCastle.OpenSsl.PemReader which will convert from the openssl style key you have to a bouncycastle key object, and Org.BouncyCastle.Security.DotNetUtilities, which will convert a bouncycastle key to a .NET RSAParameters object.

Here is a tiny bit of untested code that shows how to use it

using System;
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;

namespace RSAOpensslToDotNet
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader("../../privatekey.pem");
            PemReader pr = new PemReader(sr);
            AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
            RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);
        }
    }
}
like image 146
President James K. Polk Avatar answered Sep 21 '22 19:09

President James K. Polk