How to import RSA key from KEY file - c#

I need to encrypt string in my app using RSA key from file .key.
It contains something like this:
---BEGIN RSA PRIVAET KEY---
MIICHATIABBgQDi+.....OKh4=
---END RSA PRIVATE KEY---
So, I know that I can use RSACryptoServiceProvider class to encrypt my string, but how can I import key from .key file?

You can use the Bouncycastle C# crypto library, specifically the PEMReader class. PEMReader.readObject() will read it in and return an AsymmetricCipherKeyPair containing the private and public keys. You can then use the DotNetUtilities class to convert to .NET objects.

Related

How to encrypt a message with Private Key and decrypt it elsewhere with only the Public Key

Lets say, Person1 has two files: person1.public.key and person1.private.key. This person uses his person1.private.key to encrypt a message and send it to me.
I only have the file person1.public.key, and I want to decrypt the message sent to me.
How to:
encrypt the message on Person1's side?
decrypt the message on my side?
I did search online, but all examples I saw was the code generating the keys on runtime. I want to use the keys in the files.
Did you try using RSA.ImportFromPem(...)?
It supports the following PEM labels:
PUBLIC KEY
PRIVATE KEY
RSA PRIVATE KEY
RSA PUBLIC KEY
var keyString = loadFileIntoReadyOnlySpan();
var rsaKey = RSA.Create();
rsaKey.ImportFromPem(keyString);
I assume you know/can figure out how to load a file

Get private key file with sha256 in C #

Currently I perform this operation through openssl, and I have had no problem with the generated file
openssl dgst -sha256 -sign privateKey.key -out file.txt.signature file.txt
Now, we want to automate the generation of the file using C #, but I have not been able to get the same result.
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(CreateToken("key...", "text"));
Console.ReadLine();
}
public static string CreateToken(string key, string message)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return System.Text.Encoding.UTF8.GetString(hashmessage);
}
}
I'm new to working with this, what would be the right way?
Am I not retrieving the information properly ?, Should I get the content directly from the file?
Thank you very much.
Signature generation is not the same thing as HMAC message authentication and it uses a different key. As HMAC can use a key of any size, it will probably take the private key, but that's not how it is supposed to work. RSA is an asymmetric algorithm that uses private and public keys, MAC uses symmetric, secret keys. The dgst -sign instead uses RSA PKCS#1 v1.5 padding to sign the file.
From the OpenSSL Wiki on dgst:
When signing a file, dgst will automatically determine the algorithm (RSA, ECC, etc) to use for signing based on the private key's ASN.1 info. When verifying signatures, it only handles the RSA, DSA, or ECDSA signature itself, not the related data to identify the signer and algorithm used in formats such as x.509, CMS, and S/MIME.
HMAC is not the same thing as SHA-256 either. RSA signature generation uses a hash, not a HMAC. You should use the SHA256 class to create a hash. HMAC is a message authentication code build using the SHA-256 hash. However, the SHA class is not needed as signature generation usually includes the hash generation (you sign a message, not a hash value).
So to create a signature, take a look at the RSAPKCS1SignatureFormatter class, it includes an example at the bottom. Try again using this example.
Make sure your message only contains ASCII (both in the text file as in your string) or your result may fail as well.

Encrypting Data with RSA in .NET

I have a DER file with sha1RSA as the Signature Algorithm. I have to encrypt some data using it.
Can anyone tell me how do I load the DER file and use the RSA public key in it to encrypt my data in .NET?
DER or Distinguished Encoding Rules is a method for encoding a data object, such as an X.509 certificate, to be digitally signed or to have its signature verified.
The X.509 certificate only contains the public key. You need the private key to decrypt!
Typically private keys are exchanged in .PFX files, which are password protected.
-- EDIT --
Sorry I misread your question. Yes, you can encrypt with the public key of X.509 certificate. You can load the .der by using System.Security.Cryptography.X509Certificates.X509Certificate2.Import method.
Then convert the public and encrypt, something like:
rsa = (RSACryptoServiceProvider) certificate.PublicKey.Key;
encryptedText = rsa.Encrypt(msg, true);

How to read der file and convert to AsymmetricCipherKeyPair?

I have a der file 'text.der' that contains a DER-encoded key. I want read it and convert to an instance of AsymmetricCipherKeyPair from the Bouncycastle C# library (here are the javadocs for the Java version).
For example for a pem file, we have PemReader/Writer in bouncycastle and we can do it.
How can I go from the encoded key in a file to an AsymmetricCipherKeyPair
Assuming its the usual binary format DER public key file, with the binary DER coding for the SubjectPublicKeyInfo structure (I think OpenSSL uses this for its DER output format), you can do:
byte[] derKeyBytes = File.ReadAllBytes("text.der"); // read in the binary file
// Decode the public key component
AsymmetricKeyParameter publicKey =
PublicKeyFactory.CreateKey(derKeyBytes);
You're better of just using the AsymmetricKeyParameter (which is the public part of the key), but if you absolutely want it in a AsymmetricCipherKeyPair, you can do this:
// Put the public key into a keyPair, leave the Private key uninitialized.
AsymmetricCipherKeyPair keyPair =
new AsymmetricCipherKeyPair(
publicKey,
new AsymmetricKeyParameter(true));

How to read a private key from pvk file in C#?

I have to read a private key, and this key is on pvk format. I use X509Certificate2 class, but i this class i have only public key access.
How can I get a private key from pvk file?
Luiz, you need to combine the CER and PVK into a single PFX file, then import the file as a cert so that when you load the X509Cert the PrivateKey will be there. See Decrypt with PrivateKey X.509 Certificate.
http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.privatekey.aspx
How about this ?
Have in mind:
Currently this property supports only
RSA or DSA keys, so it returns either
an RSACryptoServiceProvider or a
DSACryptoServiceProvider object. If no
private key is associated with the
certificate, a null reference (Nothing
in Visual Basic) is returned
You can use this command to combine them.
pvk2pfx -spc CA.cer -pvk CA.pvk -pfx CA.pfx
Decrypt with PrivateKey X.509 Certificate

Categories

Resources