将FileUpload转换为X509Certificate2

4

我该如何将上传的文件转换为X509Certificate2变量?

我尝试使用以下代码,但它并没有起作用:

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

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

1
你要上传什么?是证书还是其他类型的文件? - Stefan
我已经有另一种方法来检查文件的扩展名是否与证书的扩展名相对应。现在,我想将上传的文件转换为X509Certificate2数据类型,以便可以从中获取公钥。然而,Visual Studio 给了我这个错误信息:Error 1 Cannot convert type 'System.IO.Stream' to 'System.Security.Cryptography.X509Certificates.X509Certificate2'。 - Joe Borg
2个回答

4
如果上传的文件是有效的证书,您应该查看X509Certificate2类中的constructorImport方法。您会发现需要做如下操作:
var fileLength = file.PostedFile.ContentLength;
var certdata = new byte[fileLength];

file.FileContent.Read(certData, 0, fileLength);

var cert = new X509Certificate2(certData);
< p > < em >(代码未经验证,但它或类似的东西应该可以工作)。


1
他已经有了 InputStream。我认为 cert.Import(file.PostedFile.InputStream) 应该就足够了。 - Stefan
1
@StefanM:没有Import(Stream)重载。 - Sani Huttunen
1
@JoeBorg:啊,是的。FileBytes也可以用。我忘了那个属性了。 - Sani Huttunen

1
    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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接