如何在 Linux 和 MacOS 上导入 PKCS#8 - CngKey.Import 不可用
How to import PKCS#8 on Linux and MacOS - CngKey.Import is not available
我正在尝试使用 HTTP/2 APNS 发送 Apple 推送通知。为此,我需要使用证书和加密。我创建 JWT 令牌的代码:
private string CreateJwtToken()
{
var header = JsonHelper.Serialize(new { alg = "ES256", kid = p8privateKeyId });
var payload = JsonHelper.Serialize(new { iss = teamId, iat = ToEpoch(DateTime.UtcNow) });
var key = CngKey.Import(Convert.FromBase64String(p8privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
using (var dsa = new ECDsaCng(key))
{
dsa.HashAlgorithm = CngAlgorithm.Sha256;
var headerBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(header));
var payloadBasae64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(payload));
var unsignedJwtData = $"{headerBase64}.{payloadBasae64}";
var signature = dsa.SignData(Encoding.UTF8.GetBytes(unsignedJwtData));
return $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
}
}
虽然这在 Windows 上运行良好,但 Linux 和 MacOS 不支持 CngKey.Import
。我如何重写此代码以使其跨平台?
从 .NET Core 3.0 开始,所有 AsymmetricAlgorithm 类型都支持 PKCS#8 密钥导入。
private string CreateJwtToken()
{
var header = ...;
var payload = ...;
using (ECDsa key = ECDsa.Create())
{
key.ImportPkcs8PrivateKey(Convert.FromBase64String(p8privateKey), out _);
string headerBase64 = ...;
string payloadBase64 = ...;
string unsignedJwtData = ...;
byte[] encodedRequest = Encoding.UTF8.GetBytes(unsignedJwtData);
byte[] signature = key.SignData(encodedRequest, HashAlgorithmName.SHA256);
return $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
}
}
我正在尝试使用 HTTP/2 APNS 发送 Apple 推送通知。为此,我需要使用证书和加密。我创建 JWT 令牌的代码:
private string CreateJwtToken()
{
var header = JsonHelper.Serialize(new { alg = "ES256", kid = p8privateKeyId });
var payload = JsonHelper.Serialize(new { iss = teamId, iat = ToEpoch(DateTime.UtcNow) });
var key = CngKey.Import(Convert.FromBase64String(p8privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);
using (var dsa = new ECDsaCng(key))
{
dsa.HashAlgorithm = CngAlgorithm.Sha256;
var headerBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(header));
var payloadBasae64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(payload));
var unsignedJwtData = $"{headerBase64}.{payloadBasae64}";
var signature = dsa.SignData(Encoding.UTF8.GetBytes(unsignedJwtData));
return $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
}
}
虽然这在 Windows 上运行良好,但 Linux 和 MacOS 不支持 CngKey.Import
。我如何重写此代码以使其跨平台?
从 .NET Core 3.0 开始,所有 AsymmetricAlgorithm 类型都支持 PKCS#8 密钥导入。
private string CreateJwtToken()
{
var header = ...;
var payload = ...;
using (ECDsa key = ECDsa.Create())
{
key.ImportPkcs8PrivateKey(Convert.FromBase64String(p8privateKey), out _);
string headerBase64 = ...;
string payloadBase64 = ...;
string unsignedJwtData = ...;
byte[] encodedRequest = Encoding.UTF8.GetBytes(unsignedJwtData);
byte[] signature = key.SignData(encodedRequest, HashAlgorithmName.SHA256);
return $"{unsignedJwtData}.{Convert.ToBase64String(signature)}";
}
}