Home > Uncategorized > X509Certificate object c# performance and memory issues alternative – fixed

X509Certificate object c# performance and memory issues alternative – fixed

The Problem

For my PatchCleaner product I needed the ability to read the digital certificate off a file, like can be seen on the following tab on the file properties window

msi

I want to read the digital certificate and obtain the contents of the “Subject” Field that is a string formated similarly to an Active Directory OU path.

CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US

The Issue

I originally used the X509Certificate and X509ertificate2 objects like so:

 var cert1 = new X509Certificate(_file);
 var cert2 = X509Certificate2.CreateFromSignedFile(_file);

Both of these worked but I noticed that when accessing the certificate on a large file (200+ Mb):

  1. It was very slow
  2. It seemed to use alot of memory

In fact on closer investigation it appears the X509Certificate reads the entire object into memory! I had a file of 800Mb that I opened with X509Certificate2.CreateFromSignedFile(_file), and the memory usage on my application increased by the same 800Mb before releasing once I had read the value!! Not cool!!

The Solution

 
Performance

This image shows a test application that attempts to read a 294mb patch file in 3 different ways, with a 1 sec sleep between calls:

  1. T1 – read the digital certificate by the X509 Certificate
  2. T2 – read the certificate via WinCrypt all content
  3. T3 – my soltuion via WinCrypt with just PK7 content

You can clearly see two large memory spikes for test 1 and 2, but test 3 doesn’t even register.

Below is a full c# code sample.

I based my solution on the following stack overflow article

Get timestamp from Authenticode Signed files in .NET

References

The only extra class you need to import is:

  • System.Secuirty

WinCrypt

This is a copy paste from the stack overflow article:

CertificateHelper

This is my static class that implements two method calls.

  1. GetDigitalCertificateSlow() -This is the version behind T2 above
  2. GetDigitalCertificate() – this is the one you want

These methods were based on the IsTimestamp code in the StackOverflow article, but I have manage to tweak slightly to get superior performance.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)

Categories: Uncategorized Tags:
  1. April 2nd, 2016 at 05:18 | #1

    Thank you!!!! PatchCleaner saved the day when my Windows VM filled up again with dreck from security patches. I have no control over what gets pushed and wasn’t sure how to get some space back. PatchCleaner is obviously the work of someone who “gets it” — fast & easy to use. Bravo!

    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
  1. No trackbacks yet.