.NET Standard 2.0如何从公私钥字符串获取RSA实例?
在.NET Standard 2.0中从PEM字符串获取RSA实例(用于DocuSign JWT生成)
前提准备
首先安装兼容.NET Standard 2.0的Bouncy Castle包:
Install-Package BouncyCastle.NetCore
从PEM私钥字符串获取RSA实例
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Security; using System.Security.Cryptography; using System.IO; public static RSA GetRsaFromPrivateKeyPem(string privateKeyPem) { // 从内存字符串读取私钥 using var reader = new StringReader(privateKeyPem); var pemReader = new PemReader(reader); var keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject(); // 将Bouncy Castle私钥参数转换为.NET兼容的RSAParameters var rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private); // 创建并导入参数的RSA实例 var rsa = RSA.Create(); rsa.ImportParameters(rsaParams); return rsa; }
从PEM公钥字符串获取RSA实例
public static RSA GetRsaFromPublicKeyPem(string publicKeyPem) { using var reader = new StringReader(publicKeyPem); var pemReader = new PemReader(reader); var publicKeyParam = (AsymmetricKeyParameter)pemReader.ReadObject(); // 转换为.NET兼容的RSAParameters var rsaParams = DotNetUtilities.ToRSAParameters((RsaKeyParameters)publicKeyParam); var rsa = RSA.Create(); rsa.ImportParameters(rsaParams); return rsa; }
使用示例(生成DocuSign JWT)
结合兼容.NET Standard 2.0的System.IdentityModel.Tokens.Jwt包(推荐v6.x版本),生成符合要求的JWT:
using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; public static string GenerateDocuSignJwt(string privateKeyPem, string clientId, string userId, string issuer, string audience) { using var rsa = GetRsaFromPrivateKeyPem(privateKeyPem); var signingCredentials = new SigningCredentials( new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256 ); var claims = new[] { new Claim("sub", userId), new Claim("iss", issuer), new Claim("aud", audience), new Claim("exp", DateTimeOffset.UtcNow.AddMinutes(45).ToUnixTimeSeconds().ToString()) }; var token = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(45), signingCredentials: signingCredentials ); return new JwtSecurityTokenHandler().WriteToken(token); }
注意事项
- 确保私钥/公钥PEM格式完整,包含对应的起始和结束标记
- 所有操作均在内存中完成,无需读写文件,满足45分钟刷新JWT的需求
- 若遇到格式解析错误,检查PEM字符串是否存在多余换行或空格
内容的提问来源于stack exchange,提问作者Gup3rSuR4c
相关产品推荐
相关产品推荐

