【问题标题】:Convert FileUpload to X509Certificate2将 FileUpload 转换为 X509Certificate2
【发布时间】:2013-04-27 02:54:02
【问题描述】:

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

我尝试使用以下代码,但它不起作用:

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

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

【问题讨论】:

  • 你上传的到底是什么?是证书还是其他类型的文件?
  • 我已经有另一种方法可以检查文件的扩展名是否对应于证书的扩展名。现在,我想将上传的文件转换为 X509Certificate2 数据类型,以便从中获取公钥。但是,Visual Studio 给了我这个错误消息:错误 1 ​​无法将类型 'System.IO.Stream' 转换为 'System.Security.Cryptography.X509Certificates.X509Certificate2'

标签: c# file-upload encryption certificate digital-certificate


【解决方案1】:

如果上传的文件是有效证书,您应该查看 X509Certificate2 类中的 constructor 或 Import 方法。

你会发现你需要这样的东西:

var fileLength = file.PostedFile.ContentLength;
var certdata = new byte[fileLength];

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

var cert = new X509Certificate2(certData);

(代码未经验证,但它或非常类似的东西应该可以工作)。

【讨论】:

  • 他已经拥有InputStream。我认为cert.Import(file.PostedFile.InputStream) 应该足够了。
  • @StefanM:没有Import(Stream) 过载。
  • @JoeBorg:啊,是的。 FileBytes 也可以。忘记那个属性了。
【解决方案2】:
    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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2013-07-03
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多