如何用PowerShell/Python读取PEM证书与私钥实现API认证签名?
PowerShell读取独立PEM私钥并实现RSA签名(Azure Runbook适配)
1. 读取PEM私钥并导入为RSA对象
PowerShell默认证书导入cmdlet仅支持PFX格式,处理纯PEM私钥需借助.NET System.Security.Cryptography类手动解析:
# 读取PEM私钥内容(Azure Runbook中可从Blob存储/Key Vault获取) $pemContent = Get-Content -Path "path/to/your/private.key" -Raw # 移除PEM首尾标记,提取Base64编码的密钥主体 $pemClean = $pemContent -replace "-----BEGIN RSA PRIVATE KEY-----", "" ` -replace "-----END RSA PRIVATE KEY-----", "" ` -replace "\r\n", "" -replace "\n", "" # Base64解码为字节数组 $keyBytes = [Convert]::FromBase64String($pemClean) # 导入私钥到RSA对象 $rsa = [System.Security.Cryptography.RSA]::Create() # 若为PKCS#1格式PEM,用ImportRSAPrivateKey;PKCS#8格式用ImportPkcs8PrivateKey $rsa.ImportRSAPrivateKey($keyBytes, [ref]$null)
2. 构造认证对象并生成签名
按API要求拼接待签名字段(示例以JSON序列化为例,可按需调整格式):
# 生成随机nonce $nonce = [Guid]::NewGuid().ToString("N") $apiKey = "your-api-key-value" # 构造认证结构体(按需添加时间戳等必填字段) $authObject = @{ nonce = $nonce apikey = $apiKey timestamp = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() } # 序列化为紧凑JSON字符串(API要求的待签名格式) $signData = $authObject | ConvertTo-Json -Compress # 执行RSA签名(对应PHP openssl_sign,哈希算法和填充方式需与API要求一致) $hashAlgorithm = [System.Security.Cryptography.HashAlgorithmName]::SHA256 $padding = [System.Security.Cryptography.RSASignaturePadding]::Pkcs1 $signatureBytes = $rsa.SignData([System.Text.Encoding]::UTF8.GetBytes($signData), $hashAlgorithm, $padding) # 转换为Base64格式签名(API通常要求此格式) $signature = [Convert]::ToBase64String($signatureBytes) # 输出结果用于后续API请求 Write-Output "Nonce: $nonce" Write-Output "Signature: $signature"
3. Azure Runbook适配要点
- 若私钥存储在Azure Key Vault,通过以下方式获取内容:
$secret = Get-AzKeyVaultSecret -VaultName "your-vault-name" -Name "private-key-secret" $pemContent = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($secret.SecretValueText)) - 确保Runbook身份拥有私钥存储位置的访问权限(如Key Vault的
Secret Get权限)。 - Azure Runbook默认使用PowerShell 7.x,
.NET RSA类的导入方法完全兼容,无需额外配置。
内容的提问来源于stack exchange,提问作者vilmarci
相关产品推荐
相关产品推荐

