如何使用 PowerShell 读取证书的详细信息

问题描述 投票:0回答:2

我正在尝试使用 PowerShell 解码并获取有关证书的信息。我希望能够有一个变量 $Cert,然后提取有关证书的信息,即

$Cert.Subject
$Cert.Issuer
$Cert.ValidFrom
$Cert.ValidTo

我有证书作为变量。

$Cert = -----BEGIN CERTIFICATE-----
Content Here
-----END CERTIFICATE-----

通过阅读博客等。我正在使用以下内容来转换它。

将Base64内容解码为字节数组

$CertificateBytes = [System.Convert]::FromBase64String($Cert)

**错误 - MethodInitationException:使用“1”个参数调用“FromBase64String”时出现异常:“输入不是有效的 Base-64 字符串,因为它包含非 Base 64 字符、两个以上的填充字符或填充字符中存在非法字符。” **

我尝试看看是否有隐藏角色等

当我从 $Cert 变量中删除 -----BEGIN CERTIFICATE----- & -----END CERTIFICATE----- 时,我确实取得了一些进展

我再次运行命令

将Base64内容解码为字节数组

$CertificateBytes = [System.Convert]::FromBase64String($Cert) and it completes. 

$CertificateBytes

仅包含数字列表。

然后运行以下命令。

从字节数组创建 X.509 证书对象

$certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2`
`$certificate.Import($certificateBytes)

错误 - MethodInitationException:使用“1”个参数调用“Import”时出现异常:“X509Certificate 在此平台上是不可变的。请改用等效的构造函数。”

尝试过

$certificate= New-Object -TypeName system.Security.Cryptography.X509Certificates.X509Certificate2($CertificateBytes)

错误 - 新对象:找不到“X509Certificate2”的重载和参数计数:“1608”。

$certificateBytes.Count

=1608

我现在想知道这是否可能,因为我似乎每一步都遇到了障碍。

想法?

powershell certificate
2个回答
0
投票

要么直接使用

new
静态构造方法:

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificateBytes)

...或在调用

New-Object
时将参数变量包装在数组文字中,以避免 PowerShell 将每个字节作为单独的参数值传递:

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @(,$certificateBytes)

如果证书文件存储在磁盘上,请将文件路径直接传递给

X509Certificate2
构造函数 - 它也会为您处理所有 Base64 解码:

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new((Convert-Path path\to\file.cer))

0
投票

如果您的证书为纯文本,则必须先转换为字节,然后您可以使用其中一个构造函数:

$text = "-----BEGIN CERTIFICATE-----
Content Here
-----END CERTIFICATE-----"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)

然后像这样访问您请求的属性:

$cert.Subject
$cert.Issuer
$cert.NotBefore
$cert.NotAfter

您可能还想随后调用 Dispose:

 $cert.Dispose()
© www.soinside.com 2019 - 2024. All rights reserved.