簡體   English   中英

使用Powershell上傳X509證書-錯誤“找不到所需的對象”

[英]upload X509 certificate using powershell - error 'Cannot find the requested object'

我目前正在開發一個原型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 Commandlet進行上傳。 這是我們無法開始的工作。

$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#解決方案來解決此問題,但是我會采納我能得到的任何建議。

@Eris感謝您的評論中的解決方案。

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

對我來說唯一奇怪的是,使用Web表單時字節數組是不同的,但是X509Certificate2.Import()似乎知道如何在兩種情況下正確解析它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM