.NET MD5 signature does not match OpenSSL MD5 signature - c#

I have to sign messages for a web service. The service uses OpenSSL MD5 signatures. I generate the OpenSSL one from a PEM private key file:
openssl.exe dgst -md5 -hex -out signature.txt -sign privKey.pem textToSign.txt
Which generates the following signature:
7078388bd081d4b805feb020ab47352320919e4638e36b59d66a684c9bb12a745aaf172e4da2686c3e3750bf627c980a19700f6d8bbd0b62d8714a965a34be2e9f4147ac054c4af1050cdcebd9b475f0ef28e520681b0d67104b8e633ee592bb3ec2c517fb8cf7b13bd86424f00c89518e063d55e7922adab7cf607c85920862
I want to implement this in my code. My actual code looks like (the private key in the pfx file is the same as the one in the pem file):
private static string Sign(string stringToSign)
{
X509Certificate2 cert = new X509Certificate2("keys.pfx", "", X509KeyStorageFlags.Exportable);
byte[] data = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedData;
using (MD5 hasher = MD5.Create())
using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey)
{
signedData = rsa.SignData(data, hasher);
}
return Convert.ToBase64String(signedData);
}
This code produces the following signature...
cHg4i9CB1LgF/rAgq0c1IyCRnkY442tZ1mpoTJuxKnRarxcuTaJobD43UL9ifJgKGXAPbYu9C2LYcUqWWjS+Lp9BR6wFTErxBQzc69m0dfDvKOUgaBsNZxBLjmM+5ZK7PsLFF/uM97E72GQk8AyJUY4GPVXnkirat89gfIWSCGI=
...which does not match the OpenSLL one.
What should I do to match the OpenSSL one? Also I tried to use OpenSSL.NET, but I did not find any resources/tutoral for signing.
SOLVED
The correct code is:
private static string Sign(string stringToSign)
{
X509Certificate2 cert = new X509Certificate2("#02299991.pfx", "#02299991", X509KeyStorageFlags.Exportable);
byte[] data = Encoding.UTF8.GetBytes(stringToSign);
byte[] signedData;
using (MD5 hasher = MD5.Create())
using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey)
{
signedData = rsa.SignData(data, hasher);
}
return ByteArrayToString(signedData); //Convert.ToBase64String(signedData);
}
public static string ByteArrayToString(byte[] signedBytes)
{
StringBuilder hex = new StringBuilder(signedBytes.Length * 2);
foreach (byte b in signedBytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}

Your OpenSSL output is a hex string:
openssl.exe dgst -md5 -hex -out signature.txt -sign privKey.pem textToSign.txt
^
While your C# output is in Base64:
return Convert.ToBase64String(signedData);
^
Convert your byte[] output to a hex string:
How do you convert Byte Array to Hexadecimal String, and vice versa?

Related

Signature with RSA-SHA256

I've been since yesterday trying a lot of the "solutions" on StackOverflow, but none seems to work.
Given a .pfx certificate with a private key I need to sign a byte array (firmware version of the tracking unit we use).
Here are the things I've tried:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(certificate.PrivateKey.ToXmlString(true));
return key.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
}
And also:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
string alg = CryptoConfig.MapNameToOID("SHA256");
RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider)certificate.PrivateKey;
return rsaProvider.SignData(orig, alg);
}
And also:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
byte[] hash;
using (SHA256 sha256 = SHA256.Create())
{
hash = sha256.ComputeHash(data);
}
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);
RSAFormatter.SetKey(certificate.PrivateKey);
RSAFormatter.SetHashAlgorithm("SHA256");
return RSAFormatter.CreateSignature(hash);
}
And finally:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)certificate.PrivateKey;
SHA1Managed sha1 = new SHA1Managed();
SHA256Managed sha256 = new SHA256Managed();
byte[] hash = sha256.ComputeHash(data);
csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"));
}
On all of these I get the error:
System.Security.Cryptography.CryptographicException:
'Invalid algorithm specified.'
I know my key is 256hash compatible because I've used the command:
openssl x509 -in C:\cert.pfx -text -noout
And the Signature Algorithm was sha256WithRSAEncryption.

RSA Signing with .Net and verifying with OpenSSL command

I'm trying to sign a simple data with C# using Sha1 hash and RSA and then verify it with the OpenSSL command.
For my tests, I've taken the localhost certificate that is preexisting on Windows.
Here's the code used with C#:
static void Main(string[] args)
{
string sValTest = "sampledata";
byte[] signature = Sign(sValTest, "localhost");
string b64 = Convert.ToBase64String(signature);
bool verified = Verify(sValTest, signature, #"pathToCer");
}
static byte[] Sign(string text, string certSubject)
{
X509Store my = new X509Store(StoreName.My, StoreLocation.LocalMachine);
my.Open(OpenFlags.ReadOnly);
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
csp = (RSACryptoServiceProvider)cert.PrivateKey;
break;
}
}
SHA1Managed sha1 = new SHA1Managed();
byte[] data = Enconding.ASCII.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
}
static bool Verify(string text, byte[] signature, string certPath)
{
X509Certificate2 cert = new X509Certificate2(certPath);
RSACryptoServiceProvider csp = RSACryptoServiceProvider)cert.PublicKey.Key;
SHA1Managed sha1 = new SHA1Managed();
byte[] data = Encoding.ASCII.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
}
(In that example, verified yields true)
I sent the public part of the PFX to my linux computer as well as the signature as base 64.
I then did the following:
base64 --decode sig.b64 > sig
openssl x509 -inform der -in localhost.cer -out localhost.pem
openssl x509 -pubkey -noout -in localhost.pem > localhost.pub.pem
echo -n "sampledata" | openssl dgst -verify localhost.pub.pem -signature sig
Which ends with a Verification Failure.
I checked the serial number of the certificates on both sides and it matches.
Just in case, I also checked the md5 of the signature in both stations, all clear.
Any pointers on where is the obvious fail?
You are missing the hash algorithm identifier into the openssl dgst command, which defaults to MD5.
Your correct last line is
echo -n "sampledata" | openssl dgst -verify localhost.pub.pem -signature sig -sha1

What is the difference between signing by OpenSSL and Microsoft Cryptography libraries?

I wrote two methods for signing using RSA and SHA256, the first one with OpenSSL library and the second one with Microsoft Cryptography library.
OpenSSL implementation:
private string PasswordHandler(bool verify, object userdata)
{
return userdata.ToString();
}
private string Sign(string signParams)
{
var privateCertPath = HttpContext.Current.Server.MapPath(#"~\certificate.pem");
string privateKey;
using (StreamReader sr = new StreamReader(privateCertPath))
{
privateKey = sr.ReadToEnd();
}
OpenSSL.Crypto.RSA rsa = OpenSSL.Crypto.RSA.FromPrivateKey(new BIO(privateKey), PasswordHandler, _password);
//hash method
MessageDigest md = MessageDigest.SHA1;
BIO b = new BIO(signParams);
CryptoKey ck = new CryptoKey(rsa);
byte[] res1 = MessageDigestContext.Sign(md, b, ck);
return Uri.EscapeDataString(System.Convert.ToBase64String(res1));
}
Cryptography implementation:
private string Sign(string data)
{
var privateCertPath = HttpContext.Current.Server.MapPath(#"~\certificate.pfx");
X509Certificate2 privateCert = new X509Certificate2(privateCertPath, _password, X509KeyStorageFlags.Exportable);
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
RSACryptoServiceProvider privateKey1 = new RSACryptoServiceProvider();
privateKey1.ImportParameters(privateKey.ExportParameters(true));
// Get the bytes to be signed from the string
var bytes = System.Text.Encoding.UTF8.GetBytes(data);
//const string sha256Oid = "2.16.840.1.101.3.4.2.1";
//HashAlgorithm algorithm = new SHA256CryptoServiceProvider();
//byte[] hashBytes = algorithm.ComputeHash(bytes);
//byte[] signature = privateKey1.SignHash(hashBytes, sha256Oid);
byte[] signature = privateKey1.SignData(bytes, "SHA256");
// Base 64 encode the sig so its 8-bit clean
return Convert.ToBase64String(signature);
}
Signing with OpenSSL works, generates valid digital signature but signing with Cryptography lib generates invalid signature so my question is what I implemented wrong?
I tried to use different encoding but it did not help. Certificates are generated correctly.
It might by also useful to tell basic info about the .pem certificate:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC

C# - Encrypting and Decrypting Data using RSA

I have the following code in C#:
Main Class
X509Certificate2 cert = new X509Certificate2("C:/test.pfx", "hello", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
Encryption enc = new Encryption();
string encrypted = enc.Encrypt("hello there", cert);
string decrypted = enc.Decrypt(encrypted, cert);
Console.WriteLine("Encrypted Text: " + encrypted);
Console.WriteLine("Decrypted Text: " + decrypted);
Encryption Class
public string Encrypt(string plainText, X509Certificate2 cert)
{
RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false);
string encryptedText = encryptedBytes.ToString();
return encryptedText;
}
public string Decrypt(string encryptedText, X509Certificate2 cert)
{
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false);
string decryptedText = decryptedBytes.ToString();
return decryptedText;
}
As you can see, in the main class I am importing a certificate. Then I am creating an instance of the Encryption class. Then I pass plaintext to the Encrypt method along with the certificate in order to get the encrypted text. Afterwards, I pass the encrypted text to the Decrypt method to get the plaintext back.
My problem is that the result of printing the encrypted text is System.[]Byte (if I comment out the decryption call). If I do not comment out the decryption call, I get a Cryptographic Exception: Bad Data in the decryption method.
I guess that the encryptedBytes array is not being converted correctly to string. Furthermore, I am not sure if I am forming the RSAEncryptionProvider correctly. How can I solve this please?
Update
I solved one issue. When converting from byte array to string, I had to use Encoding.UTF8.GetString(EncryptedBytes). The problem now is that the decrypt method is giving me another cryptographic exception (he data to be decrypted exceeds the maximum for this modulus of 128 bytes).
Does anybody know why this is happening and how to solve it?
you can use base64 Format to convert type of variable (encryptedText) parameter by replace the functions
public string Encrypt(string plainText, X509Certificate2 cert)
{
RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false);
string encryptedText = Convert.ToBase64String(encryptedBytes);
return encryptedText;
}
public string Decrypt(string encryptedText, X509Certificate2 cert)
{
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false);
string decryptedText = Encoding.UTF8.GetString(decryptedBytes);
return decryptedText;
}
Don't treat encrypted data as a string. Encryption algorithms work on binary data, and produce binary data, which cannot be interpreted as a string. It's naive to think that UTF-8 or any other encoding will be able to interpret any given chunk of binary data as a valid character string.
In your case, if you need to output encrypted data to the console for debugging purposes, go ahead with byte[] and dump it in hexadecimal, like this:
for (int i = 0; i < data.Length; i++)
{
Console.Write(data[i].ToString("X2"));
Console.Write(" ");
if ((i+1) % 16 == 0) Console.WriteLine();
}

How to read a PEM RSA private key from .NET

I've got an RSA private key in PEM format, is there a straight forward way to read that from .NET and instantiate an RSACryptoServiceProvider to decrypt data encrypted with the corresponding public key?
Update 03/03/2021
.NET 5 now supports this out of the box.
To try the code snippet below, generate a keypair and encrypt some text at http://travistidwell.com/jsencrypt/demo/
var privateKey = #"-----BEGIN RSA PRIVATE KEY-----
{ the full PEM private key }
-----END RSA PRIVATE KEY-----";
var rsa = RSA.Create();
rsa.ImportFromPem(privateKey.ToCharArray());
var decryptedBytes = rsa.Decrypt(
Convert.FromBase64String("{ base64-encoded encrypted string }"),
RSAEncryptionPadding.Pkcs1
);
// this will print the original unencrypted string
Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes));
Original answer
I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:
var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(#"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
With respect to easily importing the RSA private key, without using 3rd party code such as BouncyCastle, I think the answer is "No, not with a PEM of the private key alone."
However, as alluded to above by Simone, you can simply combine the PEM of the private key (*.key) and the certificate file using that key (*.crt) into a *.pfx file which can then be easily imported.
To generate the PFX file from the command line:
openssl pkcs12 -in a.crt -inkey a.key -export -out a.pfx
Then use normally with the .NET certificate class such as:
using System.Security.Cryptography.X509Certificates;
X509Certificate2 combinedCertificate = new X509Certificate2(#"C:\path\to\file.pfx");
Now you can follow the example from MSDN for encrypting and decrypting via RSACryptoServiceProvider:
I left out that for decrypting you would need to import using the PFX password and the Exportable flag. (see: BouncyCastle RSAPrivateKey to .NET RSAPrivateKey)
X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true);
You might take a look at JavaScience's source for OpenSSLKey
There's code in there that does exactly what you want to do.
In fact, they have a lot of crypto source code available here.
Source code snippet:
//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey) ;
BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try {
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt !=0x00)
return null;
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems) ;
Console.WriteLine("showing components ..");
if (verbose) {
showBytes("\nModulus", MODULUS) ;
showBytes("\nExponent", E);
showBytes("\nD", D);
showBytes("\nP", P);
showBytes("\nQ", Q);
showBytes("\nDP", DP);
showBytes("\nDQ", DQ);
showBytes("\nIQ", IQ);
}
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus =MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception) {
return null;
}
finally {
binr.Close();
}
}
The stuff between the
-----BEGIN RSA PRIVATE KEY----
and
-----END RSA PRIVATE KEY-----
is the base64 encoding of a PKCS#8 PrivateKeyInfo (unless it says RSA ENCRYPTED PRIVATE KEY in which case it is a EncryptedPrivateKeyInfo).
It is not that hard to decode manually, but otherwise your best bet is to P/Invoke to CryptImportPKCS8.
Update: The CryptImportPKCS8 function is no longer available for use as of Windows Server 2008 and Windows Vista. Instead, use the PFXImportCertStore function.
ok, Im using mac to generate my self signed keys. Here is the working method I used.
I created a shell script to speed up my key generation.
genkey.sh
#/bin/sh
ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key
add the +x execute flag to the script
chmod +x genkey.sh
then call genkey.sh
./genkey.sh
I enter a password (important to include a password at least for the export at the end)
Enter pass phrase for host.key:
Enter Export Password: {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }
I then take everything in Base64.Key and put it into a string named sslKey
private string sslKey = "MIIJiAIBA...................................." +
"......................ETC...................." +
"......................ETC...................." +
"......................ETC...................." +
".............ugICCAA=";
I then used a lazy load Property getter to get my X509 Cert with a private key.
X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
get
{
if (_serverCertificate == null){
string pass = "Your Export Password Here";
_serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
}
return _serverCertificate;
}
}
I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.
My final use for this was the SslStream to secure TCP communication to my app
SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);
I hope this helps other people.
NOTE
Without a password I was unable to correctly unlock the private key for export.
I've tried the accepted answer for PEM-encoded PKCS#8 RSA private key and it resulted in PemException with malformed sequence in RSA private key message. The reason is that Org.BouncyCastle.OpenSsl.PemReader seems to only support PKCS#1 private keys.
I was able to get the private key by switching to Org.BouncyCastle.Utilities.IO.Pem.PemReader (note that type names match!) like this
private static RSAParameters GetRsaParameters(string rsaPrivateKey)
{
var byteArray = Encoding.ASCII.GetBytes(rsaPrivateKey);
using (var ms = new MemoryStream(byteArray))
{
using (var sr = new StreamReader(ms))
{
var pemReader = new Org.BouncyCastle.Utilities.IO.Pem.PemReader(sr);
var pem = pemReader.ReadPemObject();
var privateKey = PrivateKeyFactory.CreateKey(pem.Content);
return DotNetUtilities.ToRSAParameters(privateKey as RsaPrivateCrtKeyParameters);
}
}
}
I've created the PemUtils library that does exactly that. The code is available on GitHub and can be installed from NuGet:
PM> Install-Package PemUtils
or if you only want a DER converter:
PM> Install-Package DerConverter
Usage for reading a RSA key from PEM data:
using (var stream = File.OpenRead(path))
using (var reader = new PemReader(stream))
{
var rsaParameters = reader.ReadRsaKey();
// ...
}
For people who don't want to use Bouncy, and are trying some of the code included in other answers, I've found that the code works MOST of the time, but trips up on some RSA private strings, such as the one I've included below. By looking at the bouncy code, I tweaked the code provided by wprl to
RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);
RSAparams.DP = ConvertRSAParametersField(DP, P.Length);
RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);
RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);
private static byte[] ConvertRSAParametersField(byte[] bs, int size)
{
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb
fxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ
UHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR
k9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y
5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg
JhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8
sgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2
XKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV
Bhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd
+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3
oBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+
1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E
0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE
URmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK
S+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp
q7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw
K7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK
7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA
J+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo
k+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ
X24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s
peFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit
FaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0
NM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR
IWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==
-----END RSA PRIVATE KEY-----
Check http://msdn.microsoft.com/en-us/library/dd203099.aspx
under Cryptography Application Block.
Don't know if you will get your answer, but it's worth a try.
Edit after Comment.
Ok then check this code.
using System.Security.Cryptography;
public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) {
X509Certificate2 myCertificate;
try{
myCertificate = new X509Certificate2(PathToPrivateKeyFile);
} catch{
throw new CryptographicException("Unable to open key file.");
}
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}

Categories