使用 .pem 证书注册 Apple 服务

Register Apple Service using a .pem certificate

我想向 iOS 设备发送测试 PUSH 消息。我获得了设备令牌和一个 .pem 文件作为证书。但我似乎无法找到使用此 .pem 文件创建新 ApplePushChannelSettings 对象的方法。网络上的示例都使用带有密码的 .p12 文件。

//Create our push services broker
var push = new PushBroker();

//Registering the Apple Service and sending an iOS Notification
var appleCert = File.ReadAllBytes("ApnsSandboxCert.p12"));
push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "pwd"));
push.QueueNotification(new AppleNotification()
                           .ForDeviceToken("DEVICE TOKEN HERE")
                           .WithAlert("Hello World!")
                           .WithBadge(7)
                           .WithSound("sound.caf"));

我应该为目标应用程序申请 .p12 证书,还是有办法将 .pem 文件与 PushSharp 一起使用?

根据我的经验,所有推送通知服务都需要 .p12 证书。你应该试试看。

编辑:
quick search 之后,我认为您别无选择。 .p12 是。

其实可以的,我研究了半天终于做到了。首先,得到这个:https://github.com/jrnker/CSharp-easy-RSA-PEM。它包含一个名为 Crypto 的 class 和另一个名为 HelpersHelpers,我用它来发送带有 .pem 文件的推送。

    X509Certificate2 GetCertificate(string pemFilePath, string pemFilePassword)
    {

        var pemString = File.ReadAllText(pemFilePath);
        var certificateString = readSectionFromPem(pemString, "CERTIFICATE");
        var keyString = readSectionFromPem(pemString, "RSA PRIVATE KEY");
        var certificateBuffer = Helpers.GetBytesFromPEM(certificateString, PEMtypes.PEM_X509);

        X509Certificate2 certificate = new X509Certificate2(certificateBuffer);
        RSACryptoServiceProvider provider = Crypto.DecodeRsaPrivateKey(keyString, pemFilePassword);
        certificate.PrivateKey = provider;

        return certificate;     
    }

    string readSectionFromPem(string pem, string section)
    {
        string header = String.Format("-----BEGIN {0}-----", section);
        string footer = String.Format("-----END {0}-----", section);
        int start = pem.IndexOf(header);
        int end = pem.IndexOf(footer, start) + footer.Length;
        return pem.Substring(start, end - start);
    }

获得 X509Certificate2 实例后,您可以实例化 ApnsConfigurationApnsBroker 实例使用以下代码

ApnsConfiguration config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, GetCertificate(certificatePath, certificatePass));
ApnsServiceBroker apnsBroker = new ApnsServiceBroker(config);