Search code examples
c#file-uploadencryptioncertificatedigital-certificate

Convert FileUpload to X509Certificate2


How can I convert an uploaded file to an X509Certificate2 variable?

I have tried using the following code but it is not working:

public bool hasPublicKey(FileUpload file)
{
    bool check = false;

    try
    {
         X509Certificate2 cert = (X509Certificate2)file.PostedFile.InputStream;
    }
    catch(Exception)
    {
         check = false;
    }
 }

Solution

  • If the uploaded file is a valid certificate you should have a look at the constructor or Import method in the X509Certificate2 class.

    You'll see that you need to something like this:

    var fileLength = file.PostedFile.ContentLength;
    var certdata = new byte[fileLength];
    
    file.FileContent.Read(certData, 0, fileLength);
    
    var cert = new X509Certificate2(certData);
    

    (code not verified but it, or something very similar, should work).