如何在PowerShell中用RSA-SHA512算法及PFX私钥签名字符串?
问题描述
我正在尝试在PowerShell中使用从PFX证书导出的私钥(PKCS#8格式),通过RSA-SHA512算法对字符串进行签名。目前已完成待签名字符串的构建,代码如下:
$x_request_id = New-Guid $x_request_id_Final = "x-request-id: $x_request_id" $string = "" $bytes = [System.Text.Encoding]::UTF8.GetBytes($string) $sha512 = [System.Security.Cryptography.SHA512]::Create() $hash = $sha512.ComputeHash($bytes) $Digest = [System.Convert]::ToBase64String($hash) $Digest_Final = "digest: SHA512=$Digest" $SignString = $Digest_Final + "`n" + $x_request_id_Final
输出的待签名字符串示例:
digest: SHA512=z4PhNX7vuL3xVChQ1m2AB9Yg5AULVxXcg/SpIdNs6c5H0NE8XYXysP+DGNKHfuwvY7kxvUdBeoGlODJ6+SfaPg== x-request-id: f1856125-24bd-47c1-a1af-1ab6bd507634
持有私钥格式如下:
-----BEGIN PRIVATE KEY----- Base64ContentHere -----END PRIVATE KEY-----
需要指导如何在PowerShell中完成签名操作。
解决方案
可以通过以下步骤完成RSA-SHA512签名:
- 处理私钥字符串:移除私钥开头的
-----BEGIN PRIVATE KEY-----和结尾的-----END PRIVATE KEY-----标记,提取中间的Base64内容并解码为字节数组。 - 导入私钥到RSA对象:使用
[System.Security.Cryptography.RSA]::Create()创建RSA实例,通过ImportPkcs8PrivateKey方法导入解码后的私钥字节。 - 对待签名字符串签名:将待签名字符串转为UTF8字节,调用RSA实例的
SignData方法,指定哈希算法为SHA512,填充方式为Pkcs1(多数场景默认使用此填充)。 - 转换签名结果:将签名后的字节数组转为Base64字符串,得到最终可用的签名值。
完整代码示例:
# 1. 定义私钥内容(替换为你的实际私钥) $privateKeyContent = @" -----BEGIN PRIVATE KEY----- Base64ContentHere -----END PRIVATE KEY----- "@ # 2. 处理私钥,提取Base64并解码 $cleanedKey = $privateKeyContent -replace "-----BEGIN PRIVATE KEY-----", "" -replace "-----END PRIVATE KEY-----", "" -replace "\s", "" $keyBytes = [System.Convert]::FromBase64String($cleanedKey) # 3. 导入私钥到RSA对象 $rsa = [System.Security.Cryptography.RSA]::Create() $rsa.ImportPkcs8PrivateKey($keyBytes, [ref]$null) # 4. 待签名字符串(你已完成的部分) $x_request_id = New-Guid $x_request_id_Final = "x-request-id: $x_request_id" $string = "" $bytes = [System.Text.Encoding]::UTF8.GetBytes($string) $sha512 = [System.Security.Cryptography.SHA512]::Create() $hash = $sha512.ComputeHash($bytes) $Digest = [System.Convert]::ToBase64String($hash) $Digest_Final = "digest: SHA512=$Digest" $SignString = $Digest_Final + "`n" + $x_request_id_Final # 5. 执行签名 $signingBytes = [System.Text.Encoding]::UTF8.GetBytes($SignString) $signatureBytes = $rsa.SignData($signingBytes, [System.Security.Cryptography.HashAlgorithmName]::SHA512, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) $signatureBase64 = [System.Convert]::ToBase64String($signatureBytes) # 输出签名结果 Write-Host "签名结果:$signatureBase64" # 释放资源 $rsa.Dispose()
注意事项
- 确保私钥格式为PKCS#8(即
BEGIN PRIVATE KEY开头),如果是PKCS#1格式(BEGIN RSA PRIVATE KEY),需要改用ImportRSAPrivateKey方法。 - 签名的填充方式需与验证方保持一致,若验证方使用其他填充(如Pss),需替换为
RSASignaturePadding.Pss。
内容的提问来源于stack exchange,提问作者Current Redemption
相关产品推荐
相关产品推荐

