Question

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;
    }
 }
Was it helpful?

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).

OTHER TIPS

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

        try
        {
            X509Certificate2 cert = new X509Certificate2(file.FileBytes);

            if (cert.PublicKey != null)
            {
                check = true;
            }
        }
        catch(Exception)
        {
            check = false;
        }
        return check;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top