Powershell 5.1与7同代码处理p12证书加密差异及JWT生成问题求解
问题根因
PowerShell 5.1 基于.NET Framework 运行,默认导入P12证书时会使用 legacy CSP(加密服务提供程序)存储私钥,返回的RSACryptoServiceProvider实例默认仅支持SHA1签名,不支持SHA256,因此调用new-jwt时会触发算法不匹配报错。而PowerShell 7基于.NET Core+ 运行,默认使用CNG(下一代加密)存储私钥,返回的RSA实例原生支持SHA2系列算法,因此运行正常。
可行实现方案
方案1:私钥参数转换(全版本.NET Framework兼容)
通过导出原私钥的RSA参数,重新生成支持SHA256的RSA实例,无需高版本.NET环境支持:
$certfilepath = 'C:\gsuite-325413-4e17f897eees.p12' $SecStrPass = ConvertTo-SecureString -string "notasecret" -AsPlainText -Force # 导入证书时添加可导出标识,方便后续私钥参数导出 $cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2( $certfilepath, $SecStrPass, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet ) # 导出RSA参数并重新生成支持SHA256的私钥实例 $rsaPrivateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::Create() $rsaPrivateKey.ImportParameters($cert.PrivateKey.ExportParameters($true)) # 此时$rsaPrivateKey的KeyExchangeAlgorithm为RSA,可直接传入new-jwt函数使用 $rsaPrivateKey
方案2:强制使用CNG存储导入证书(需.NET Framework 4.7.2+)
如果系统已安装.NET Framework 4.7.2及以上版本,可直接在导入时指定优先使用CNG存储,得到和PowerShell 7完全一致的私钥实例:
$certfilepath = 'C:\gsuite-325413-4e17f897eees.p12' $SecStrPass = ConvertTo-SecureString -string "notasecret" -AsPlainText -Force # 32对应X509KeyStorageFlags.PreferCng枚举值,强制使用CNG存储私钥 $cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2( $certfilepath, $SecStrPass, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable -bor 32 ) # 此时$cert.PrivateKey的KeyExchangeAlgorithm为RSA $cert.PrivateKey
有效性验证
可通过以下代码验证私钥是否支持SHA256签名,无报错即可正常用于JWT生成:
$testContent = [System.Text.Encoding]::UTF8.GetBytes("test signature") $signResult = $rsaPrivateKey.SignData( $testContent, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1 )
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

