I have a pre-existing public/private key pair for RSA encryption which I need to use in .net . All the examples I can find online demonstrate how to generate a new private/public pair and then encrypt/decrypt. ie. something like this:
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "SpiderContainer";
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);
.....
rsa.encrypt(...)
rsa.decrypt(...)
As can be seen, there is no avenue for specifying a pre-existing public/private key.
Would anyone know how to accomplish what I am trying to do? Any help would be much appreciated.
Cheers Naren
As their names suggest, a public key is shared publicly, while a private key is secret and known only by the key pair creator (it must not be shared with anyone). In RSA, either of the keys can encrypt the data, while the other key decrypts it. If for instance the public key is used for encryption, the private key must be used to decrypt the data.
In RSA, either of the keys can encrypt the data, while the other key decrypts it. If for instance the public key is used for encryption, the private key must be used to decrypt the data. This is very applicable especially when sending sensitive data across a network such as the Internet.
RSA.ImportRSAPublicKey takes a DER-encoded PKCS#1 RSAPublicKey structure as input. The first thing we need to do is convert that DER blob into a CSP Public Key blob . To do this, we can call CryptDecodeObjectEx and pass the flag RSA_CSP_PUBLICKEYBLOB.
But with some extension methods and a little help from CryptoAPI, we can fill that gap. Although .NET Core 3.0 and newer versions don’t provide a RSA.ExportToPem method, they do provide 2 other useful methods: RSA.ExportRSAPublicKey , which exports a public key as a DER-encoded PKCS#1 RSAPublicKey structure.
To use an existing key, you can use the ImportParameters
-method:
RSAParameters parameters = new RSAParameters()
parameters.Modulus = // ...
parameters.Exponent = // ...
RSA rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(parameters);
rsa.Encrypt(/*...*/);
You can add the private parameters, too, in order to use it for decrypting or signing.
In order to tell you how to get from your existing keydata to the parameters, we need to know exactly how they are encoded. Try showing us the strings (replace most of the private key with Xs if it is a real key).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With