How to validate public key xml file? - c#

I have created a public key using RSACryptoServiceProvider in c#.
Later in my program I want to store it's content in database. How can I make sure that the file is a true public key.
Note: I have checked it's structure against xsd. but I need more.
Any help?
the code to produce public key:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
string publicKey = rsa.ToXmlString(false);

finally I've found a solution:
first I check the schema against a xsd file,
and then
try
{
var csp = new RSACryptoServiceProvider();
var reader = new StreamReader(address);
var xml = reader.ReadToEnd();
csp.FromXmlString(xml);
}
catch
{
//not a rsa public key
}

Related

Deserialize RSA public and private key C#

As a part of my project I have to encrypt some text with RSA and I have got a public key from another company. The public key looks like this:
var publicKey="MIGfMA0GCSq2GSIb3DQEBAQUAA4GNADCBiQKBgQCgFGVfrY4jQSoZQWWygZ83roKXWD4YeT2x2p41dGkPixe73rT2IW04glatgN2vgoZsoHuOPqah5and6kAmK2ujmCHu6D1auJhE2tXP+yLkpSiYMQucDKmCsWXlC5K7OSL77TXXcfvTvyZcjObEz6LIBRzs6+FqpFbUO9SJEfh6wIDAQAB"
The problem is that I don't know what is its format and how to deserialize it to RSAParameters. Other examples on the Internet have used XML serialization. The key is created by Java.
Then I also want to know how to deserialize its related private key which I don't have access to any sample of it right now.
Update :
Here is part of my code :
var pk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiiTx4F35eWP10AFMAo8MLhCKq2ryKFG9PKKWeMLQuwMSdiQq347BkMYA+Q+YscScf7weUSTk9BHVNNfTchDwzjQrIoz6TZGggqD+ufin1Ccy0Sp6QeBMnIB89JsdzQGpVcsoTxk53grW0nYY8D+rlFvBwFicKe/tmVPVMYsEyFwIDAQAB";
...
public static RSACryptoServiceProvider ImportPublicKey(string pem)
{
//var newPem = "-----BEGIN PUBLIC KEY-----\n" + pem + "-----END PUBLIC KEY-----";
Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(Pem));
Org.BouncyCastle.Crypto.AsymmetricKeyParameter publicKey = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pr.ReadObject();
RSAParameters rsaParams = Org.BouncyCastle.Security.DotNetUtilities.ToRSAParameters((Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}
The posted key is a PEM encoded public key in X.509 (SPKI) format, but without header (-----BEGIN PUBLIC KEY-----) and footer (-----END PUBLIC KEY-----). This can be easily verified with an ASN.1 parser, e.g. here.
The import of such a key depends on the .NET version. .NET Core offers from v3.0 on methods that directly support the import of PKCS#1, PKCS#8 and X.509 keys, e.g. RSA.ImportSubjectPublicKeyInfo for the latter. This option is not available for .NET Framework, but BouncyCastle offers a similarly comfortable solution.
Here (see ImportPublicKey method) is an example that imports a PEM encoded public key in X.509 (SPKI) format using BouncyCastle. However, the PemReader used there expects the complete PEM data, including header and footer, both separated from the body by line breaks. Therefore, when using the public keys posted here, header and footer must be added accordingly, e.g:
using System.IO;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
...
// from: https://gist.github.com/valep27/4a720c25b35fff83fbf872516f847863
public static RSACryptoServiceProvider ImportPublicKey(string pemBody)
{
var pem = "-----BEGIN PUBLIC KEY-----\n" + pemBody + "\n-----END PUBLIC KEY-----"; // Add header and footer
PemReader pr = new PemReader(new StringReader(pem));
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pr.ReadObject();
RSAParameters rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKey);
RSACryptoServiceProvider csp = new RSACryptoServiceProvider();// cspParams);
csp.ImportParameters(rsaParams);
return csp;
}

C# - Load .DER public key from file and use for encryption

I have a public key in a .der extension file from a vendor. I have to use this to encrypt something using C# and add the result to an API call. I am new to this type of stuff and can't figure out how to load the key in the .der file into code and use it to encrypt my string. Any help?
Thanks!
You can use the X509Certificate2 to load the certificate, I.E.:
var cert = new X509Certificate2(#"C:\path\to\key.der");
var publicKey = cert.GetRSAPublicKey();
var privateKey = cert.GetRSAPrivateKey();
To actually encrypt/decrypt data, you would do something similar to the following depending on the specifications
var plaintext = Encoding.UTF8.GetBytes("Some Secret");
var encrypted = publicKey.Encrypt(plaintext, RSAEncryptionPadding.OaepSHA256);
var decrypted = privateKey.Decrypt(encrypted, RSAEncryptionPadding.OaepSHA256);
Console.WriteLine(Encoding.UTF8.GetString(decrypted));

Initializing RSA from String

I am trying to decrypt some text that is encrypted with RSA, I have the public key to do this
`
-----BEGIN RSA PUBLIC KEY-----
MIGWAoGBAMqfGO9sPz+kxaRh/qVKsZQGul7NdG1gonSS3KPXTjtcHTFfexA4MkGA
mwKeu9XeTRFgMMxX99WmyaFvNzuxSlCFI/foCkx0TZCFZjpKFHLXryxWrkG1Bl9+
+gKTvTJ4rWk1RvnxYhm3n/Rxo2NoJM/822Oo7YBZ5rmk8NuJU4HLAhAYcJLaZFTO
sYU+aRX4RmoF
-----END RSA PUBLIC KEY-----
`
How can I load this into RSACryptoServiceProvider because this can only load from XMLString and I do not know how to convert this to Xml format
The key size is 128
I tried to initialize it using the following code
public byte[] Decrypt128(byte[] input)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(128);
rsa.ImportCspBlob(Encoding.ASCII.GetBytes(_longKey));
return rsa.Decrypt(input, true);
}
_longKey is the content between BEGIN and END and also including the BEGIN and END, bot Bad Version of provider.
This is not a duplicate question of How do you convert Byte Array to Hexadecimal String, and vice versa?
I already know how to convert byte to hex and hex to byte, but that in any way does not help me initializing RSACryptoServiceProvider maybe give me example how that would help but at this point it doesn't
You could use BouncyCastle which has a PemReader allowing you to extract the modulus and exponent for the key:
using (var reader = File.OpenText("mykey.key"))
{
var pem = new PemReader(reader);
var o = (RsaKeyParameters)pem.ReadObject();
using (var rsa = new RSACryptoServiceProvider())
{
var parameters = new RSAParameters();
parameters.Modulus = o.Modulus.ToByteArray();
parameters.Exponent = o.Exponent.ToByteArray();
rsa.ImportParameters(parameters);
// Do what you need to do with the RSACryptoServiceProvider instance
}
}
If you don't want to have a dependency on BouncyCastle in your project, once loaded the public key into the RSACryptoServiceProvider using this method you could export it to XML for future use:
string xml = rsa.ToXmlString(false);
File.WriteAllText("mykey.xml", xml);

RSA public key to base 64

I have generated and RSA public key :
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096);
var pub_key = rsaProvider.ExportParameters(false); // export public key
var priv_key = rsaProvider.ExportParameters(true); // export private key
I need a way to decode pub_key it into base64 so I can send it, any suggestions
When you say Base64 do you mean that you need the public key in Base64 PEM format? If so, consider using BouncyCastle.
var kp = [Org.BouncyCastle.Security.DotNetUtilities].GetKeyPair(rsaProvider);
using (var sw = new System.IO.StringWriter())
{
var pw = new Org.BouncyCastle.OpenSsl.PemWrite(sw);
pw.WriteObject(kp.Public);
var pem = sw.ToString();
return pem;
}
It is not clear exactly what you need but I'm guessing you are looking to serialize the key. In that case you can use the RSA.ToXmlString() method. If you really need to base64 encode it then you the method in Nickolay Olshevsky's answer to further encode the XML string.
In .NET there is a builtin function to convert to Base64 : http://msdn.microsoft.com/en-us/library/dhx0d524.aspx

CryptographicException "Key not valid for use in specified state." while trying to export RSAParameters of a X509 private key

I am staring at this for quite a while and thanks to the MSDN documentation I cannot really figure out what's going. Basically I am loading a PFX file from the disc into a X509Certificate2 and trying to encrypt a string using the public key and decrypt using the private key.
Why am I puzzled: the encryption/decryption works when I pass the reference to the RSACryptoServiceProvider itself:
byte[] ed1 = EncryptRSA("foo1", x.PublicKey.Key as RSACryptoServiceProvider);
string foo1 = DecryptRSA(ed1, x.PrivateKey as RSACryptoServiceProvider);
But if the export and pass around the RSAParameter:
byte[] ed = EncryptRSA("foo", (x.PublicKey.Key as RSACryptoServiceProvider).ExportParameters(false));
string foo = DecryptRSA(ed, (x.PrivateKey as RSACryptoServiceProvider).ExportParameters(true));
...it throws a "Key not valid for use in specified state." exception while trying to export the private key to RSAParameter. Please note that the cert the PFX is generated from is marked exportable (i.e. I used the pe flag while creating the cert). Any idea what is causing the exception?
static void Main(string[] args)
{
X509Certificate2 x = new X509Certificate2(#"C:\temp\certs\1\test.pfx", "test");
x.FriendlyName = "My test Cert";
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
try
{
store.Add(x);
}
finally
{
store.Close();
}
byte[] ed1 = EncryptRSA("foo1", x.PublicKey.Key as RSACryptoServiceProvider);
string foo1 = DecryptRSA(ed1, x.PrivateKey as RSACryptoServiceProvider);
byte[] ed = EncryptRSA("foo", (x.PublicKey.Key as RSACryptoServiceProvider).ExportParameters(false));
string foo = DecryptRSA(ed, (x.PrivateKey as RSACryptoServiceProvider).ExportParameters(true));
}
private static byte[] EncryptRSA(string data, RSAParameters rsaParameters)
{
UnicodeEncoding bytConvertor = new UnicodeEncoding();
byte[] plainData = bytConvertor.GetBytes(data);
RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();
publicKey.ImportParameters(rsaParameters);
return publicKey.Encrypt(plainData, true);
}
private static string DecryptRSA(byte[] data, RSAParameters rsaParameters)
{
UnicodeEncoding bytConvertor = new UnicodeEncoding();
RSACryptoServiceProvider privateKey = new RSACryptoServiceProvider();
privateKey.ImportParameters(rsaParameters);
byte[] deData = privateKey.Decrypt(data, true);
return bytConvertor.GetString(deData);
}
private static byte[] EncryptRSA(string data, RSACryptoServiceProvider publicKey)
{
UnicodeEncoding bytConvertor = new UnicodeEncoding();
byte[] plainData = bytConvertor.GetBytes(data);
return publicKey.Encrypt(plainData, true);
}
private static string DecryptRSA(byte[] data, RSACryptoServiceProvider privateKey)
{
UnicodeEncoding bytConvertor = new UnicodeEncoding();
byte[] deData = privateKey.Decrypt(data, true);
return bytConvertor.GetString(deData);
}
Just to clarify in the code above the bold part is throwing:
string foo = DecryptRSA(ed, (x.PrivateKey as RSACryptoServiceProvider)**.ExportParameters(true)**);
I believe that the issue may be that the key is not marked as exportable. There is another constructor for X509Certificate2 that takes an X509KeyStorageFlags enum. Try replacing the line:
X509Certificate2 x = new X509Certificate2(#"C:\temp\certs\1\test.pfx", "test");
With this:
X509Certificate2 x = new X509Certificate2(#"C:\temp\certs\1\test.pfx", "test", X509KeyStorageFlags.Exportable);
For the issue I encountered a code change was not an option as the same library was installed and working elsewhere.
Iridium's answer lead me to look making the key exportable and I was able to this as part of the MMC Certificate Import Wizard.
Hope this helps someone else. Thanks heaps
I've met some similar issue, and X509KeyStorageFlags.Exportable solved my problem.
I'm not exactly an expert in these things, but I did a quick google, and found this:
http://social.msdn.microsoft.com/Forums/en/clr/thread/4e3ada0a-bcaf-4c67-bdef-a6b15f5bfdce
"if you have more than 245 bytes in your byte array that you pass to your RSACryptoServiceProvider.Encrypt(byte[] rgb, bool fOAEP) method then it will throw an exception."
For others that end up here through Google, but don't use any X509Certificate2, if you call ToXmlString on RSACryptoServiceProvider but you've only loaded a public key, you will get this message as well. The fix is this (note the last line):
var rsaAlg = new RSACryptoServiceProvider();
rsaAlg.ImportParameters(rsaParameters);
var xml = rsaAlg.ToXmlString(!rsaAlg.PublicOnly);
AFAIK this should work and you're likely hitting a bug/some limitations. Here's some questions that may help you figure out where's the issue.
How did you create the PKCS#12 (PFX) file ? I've seen some keys that CryptoAPI does not like (uncommon RSA parameters). Can you use another tool (just to be sure) ?
Can you export the PrivateKey instance to XML, e.g. ToXmlString(true), then load (import) it back this way ?
Old versions of the framework had some issues when importing a key that was a different size than the current instance (default to 1024 bits). What's the size of your RSA public key in your certificate ?
Also note that this is not how you should encrypt data using RSA. The size of the raw encryption is limited wrt the public key being used. Looping over this limit would only give you really bad performance.
The trick is to use a symmetric algorithm (like AES) with a totally random key and then encrypt this key (wrap) using the RSA public key. You can find C# code to do so in my old blog entry on the subject.
Old post, but maybe can help someone.
If you are using a self signed certificate and make the login with a different user, you have to delete the old certificate from storage and then recreate it. I've had the same issue with opc ua software

Categories

Resources