如何在C#中使用APNs Auth Key(.p8文件)?

我正在尝试使用基于令牌的身份validation向iOS设备发送推送通知。

根据需要,我在Apple的开发门户中生成了一个APNs Auth Key,并下载了它(它是一个带有p8扩展名的文件)。

要从我的C#服务器发送推送通知,我需要以某种方式使用此p8文件来签署我的JWT令牌。 我怎么做?

我试图将文件加载到X509Certificate2,但X509Certificate2似乎不接受p8文件,所以然后我尝试将文件转换为pfx / p12,但是找不到实际工作的方法。

我找到了一种方法,使用BouncyCastle :

private static CngKey GetPrivateKey() { using (var reader = File.OpenText("path/to/apns/auth/key/file.p8")) { var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject(); var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded(); var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded(); var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned(); return EccKey.New(x, y, d); } } 

现在创建和签署令牌(使用jose-jwt ):

 private static string GetProviderToken() { var epochNow = (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; var payload = new Dictionary() { {"iss", "your team id"}, {"iat", epochNow} }; var extraHeaders = new Dictionary() { {"kid", "your key id"} }; var privateKey = GetPrivateKey(); return JWT.Encode(payload, privateKey, JwsAlgorithm.ES256, extraHeaders); }