Decode a PKCS#12 file

Rohan West picture Rohan West · Feb 17, 2009 · Viewed 7.5k times · Source

I am looking for ways to decode a PKCS#12 file in .NET, I need to extract the private key and any certificates so that i can programatically access the following.

  • modulus
  • publicExponent
  • privateExponent
  • prime1
  • prime2
  • exponent1
  • exponent2
  • coefficient

I need this informatio so that i can successfully use PKCS#11 to create a private key and cetificate on a USB token.

I have found a website that uses OpenSSL to output this data. I was pretty excited when I found OpenSSL.NET however the functionallity to split PKCS#12 files hasn't been implemented yet. I was wondering if anyone knew of any altenatives.

Thanks

Rohan

Answer

Rohan West picture Rohan West · Feb 17, 2009

Cheers Manuel,

I downloaded the Bouncy Castle API and it didn't take long to find what i needed. The source code includes an extensive list of unit tests.

static void Main(string[] args)
{
    char[] password = new char[] {'p','a','s','s','w','o','r','d'};

    using(StreamReader reader = new StreamReader(@"Test.pfx"))
    {
        Pkcs12Store store = new Pkcs12Store(reader.BaseStream,password);
        foreach (string n in store.Aliases)
        {
            if(store.IsKeyEntry(n))
            {
                AsymmetricKeyEntry key = store.GetKey(n);

                if(key.Key.IsPrivate)
                {
                    RsaPrivateCrtKeyParameters parameters = key.Key as RsaPrivateCrtKeyParameters;
                    Console.WriteLine(parameters.PublicExponent);
                }                       
            }
        }
    }
}