使用powershell上传X509证书 - 错误'找不到请求的对象'

时间:2016-05-30 17:04:34

标签: c# powershell x509certificate2

我目前正在开发一个原型C#MVC应用程序,允许用户将证书和CRL上传到存储库。例如,应用程序将使用上传的.cer,并使用X509Certificate2的Import()方法对其进行解析。我这样做是为了验证用户上传的内容确实是证书:

    public CertModel(byte[] bytes)
    {
        this._Certificate = new X509Certificate2();
        try // Attempt to parse as a certificate to see if this is actually a cert
        { 
            this._Certificate.Import(bytes);
            this.Subject = _Certificate.Subject;
            this.Sha1Fingerprint = _Certificate.Thumbprint;
            this.RawData = Convert.ToBase64String(_Certificate.RawData);
        }
        catch (CryptographicException e)
        {
            this._Certificate = null;
        } 

    }

有一个MVC网页显示上传表单,最终调用上面的代码。这在直接使用Web表单时工作正常。

还有另一个团队编写powershell脚本,他们正在尝试使用Invoke-WebRequest命令行开关进行上载。这是我们无法开展的工作。

$filePath = "%HOMEPATH%\Desktop\certs\myCert.cer"
$fileInfo = gi $filePath

# Get the raw data of the cert to upload #

$rawCertData = [System.IO.File]::ReadAllText($fileInfo)
$length = $rawCertData.Length;
Write-Host $rawCertData
## Type of file you are uploading ##
$fileType = "Certificate"


## Build the POST Body ##
$boundary = [System.Guid]::NewGuid().ToString()
$lf = "`n"

$bodyLines = (
    "--$boundary",
    'Content-Disposition: form-data; name="Type"',
    '',
    "$fileType",
    "--$boundary",
    'Content-Disposition: form-data; name="upload"; filename="myCert.cer"',
    'Content-Type: application/octet-stream',
    '',
    "$rawCertData",
    "--$boundary--"
) -join $lf


$contentType = "multipart/form-data; boundary=$boundary"
$uri = "http://localhost:58484/repo/upload_service"
$response = Invoke-WebRequest -Uri $uri  -Method POST -ContentType $contentType -Body $bodyLines -WebSession $session 
$tempStore.Clear()

对于同一个文件,我已经验证了请求有效负载看起来完全一样。此外,我可以验证传递给Import()的字节数组是否相同。但是,使用curl / Invoke-WebRequest方法时。我在CryptographicException中收到“找不到请求的对象”消息。

我之前从未接触过PowerShell,所以我希望我能解决这个问题的C#解决方案,但我会接受任何建议。

1 个答案:

答案 0 :(得分:0)

@Eris感谢您在评论中提供解决方案。

$rawCertData = [System.IO.File]::ReadAllBytes($fileInfo)
$rawCertData = [System.Convert]::ToBase64String($rawCertData);

我唯一感到奇怪的是,使用Web表单时字节数组是不同的,但似乎X509Certificate2.Import()在任何一种情况下都知道如何正确解析它。