【问题标题】:upload X509 certificate using powershell - error 'Cannot find the requested object'使用 powershell 上传 X509 证书 - 错误“找不到请求的对象”
【发布时间】:2016-05-31 02:05:48
【问题描述】:

我目前正在开发一个原型 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# 解决方案来解决这个问题,但我会接受我能得到的任何建议。

【问题讨论】:

  • 在 powershell 中,您从未对证书内容进行 base64 编码

标签: c# powershell x509certificate2


【解决方案1】:

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

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

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

【讨论】:

  • 请注意,我也必须使用 ReadAllBytes() 而不是 ReadAllText()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2021-07-08
  • 1970-01-01
  • 2012-04-09
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
相关资源
最近更新 更多