首页 > 解决方案 > 通过 PowerShell 创建 PEM 文件

问题描述

我正在尝试编写脚本以在 powershell 中创建 PEM 证书文件。我不确定我所做的是否完全错误,但是当我尝试在和 socat OPENSSL 中使用 PEM 文件时,它返回了错误:

$ socat OPENSSL-LISTEN:1337,cert=cert.pem,verify=0 -

socat[1209] E SSL_CTX_use_certificate_file(): error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag
#create certificate
$cert = New-SelfSignedCertificate `
    -Subject "MYHOSTNAME" `
    -TextExtension @("2.5.29.17={text}DNS=MYHOSTNAME&IPAddress=192.168.1.100") `
    -KeySpec Signature `
    -HashAlgorithm SHA256 `
    -KeyExportPolicy Exportable

#publicKey
$PublicKey = $cert.GetPublicKey();
$PublicKeyB64 = [Convert]::ToBase64String($PublicKey,"InsertLineBreaks");

#privateKey
$RSACng  = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert);
$PrivateKey = $RSACng.Key;
$PrivateKeyByte = $PrivateKey.Export("PRIVATEBLOB");
$PrivateKeyB64 = [Convert]::ToBase64String($PrivateKeyByte,"InsertLineBreaks");

#createFile
$out = New-Object string[] -ArgumentList 6;
$out[0] = "-----BEGIN PRIVATE KEY-----";
$out[1] = $PrivateKeyB64;
$out[2] = "-----END PRIVATE KEY-----"

$out[3] = "-----BEGIN CERTIFICATE-----"
$out[4] = $publicKeyB64;
$out[5] = "-----END CERTIFICATE-----"

[IO.File]::WriteAllLines("C:\Users\Public\cert.pem",$out)

我不确定我所做的是否完全错误,但我找不到任何资源来帮助我继续。

一些执行在 powershell 中创建 PEM 文件的类似操作的脚本或有关如何继续的一些提示可能对帮助我修复此问题很有价值。

标签: certificatersapowershell

解决方案


您也可以使用 CertUtil.exe。经历一次

Certutil.exe 是一个命令行程序,作为证书服务的一部分安装。

使用powershell创建.PEM的简单脚本如下:

 $certpwd = '***'
$certpwd1 = ConvertTo-SecureString -String $certpwd -Force –AsPlainText
$certpwd2 = 'pass:' + $certpwd
$certname = $env:COMPUTERNAME
del c:\temp\$certname.*

$cert = New-SelfSignedCertificate -DnsName $certname -certStorelocation cert:\localmachine\my -KeyLength 2048  -KeyFriendlyName $certname -FriendlyName $friendlyName -HashAlgorithm sha256 -keyexportpolicy exportableencrypted -keyspec KeyExchange -NotAfter (Get-Date).AddYears(2) | Out-Null

$cert2=Get-ChildItem Cert:\LocalMachine\my |
Where-Object { $_.FriendlyName -match $friendlyName }


$path = ‘cert:\localMachine\my\’ + $cert2.thumbprint
Export-Certificate -cert $path -FilePath c:\temp\$certname.der -type CERT –noclobber | Out-Null
certutil -encode c:\temp\$certname.der c:\temp\$certname.pem | Out-Null

脚本的作用是

1)首先它创建自签名证书

2)然后以.der的形式将其导出到某个物理路径

3)使用 Certutil 进行编码,从而创建 .pem 文件(在此示例中,.pem 将保存在 c:\temp\ 中)


推荐阅读