Tomas Toom

Tomas Toom

  • NA
  • 4
  • 6.7k

Decrypt p7m file in C# or .NET with privateKey from file

Dec 10 2011 5:36 PM
Hi,
Hopefully someone can help me with code because I am working on it 3 months without any success. I tried almost anything from internet but nothing does not work.

Problem: I have encrypted file p7m (size 158KB) (it is crypted text). I have certificate in file pfx, under password "a". In this certificate is the public key which is needed to decrypt p7m file.

I need something that will read xyyv.p7m file, decrypt it with public key, and save it as XYZ.xyz
I have files already in C: drive. So open the file is no problem. It could be easily read. Next steps to decrypt these bytes by private key from pfx file, or from installed at PC, simply does not work for me. The principle is simple:

1. read file to memory
2. read private key from pfx file
3. decrypt file in memory by private key
4. save decrypted text

...but #2 and #3 does not work.

for #2 I have this code:
X509KeyStorageFlags flags = X509KeyStorageFlags.Exportable;
X509Certificate2 cert = new X509Certificate2("my.pfx", "somepass", flags);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
RSAParameters rsaParam = rsa.ExportParameters(true);


but I have problem to use this info in #3 part - use it in decryption.

Any idea how put everything together to work? Thanks