正在将 Apple APNs 授权密钥加载到 Java 私钥

Loading Apple APNs auth key to Java PrivateKey

问题

我无法将 APN 的授权密钥 加载到 Java。我的理解是 Java 可以读取 PKCS8 编码的私钥,但我遇到异常。

我在使用 Bouncy Castle (bcprov-jdk15on-1.55) 时出现异常

org.bouncycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException: unable to process key spec: java.io.IOException: algorithm identifier 1.2.840.10045.2.1 in key not recognised
    at org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:366)
Caused by: java.io.IOException: algorithm identifier 1.2.840.10045.2.1 in key not recognised
    at org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.generatePrivate(Unknown Source)
    ... 29 more

异常我使用 Java (jdk1.8.0_74)

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Invalid RSA private key
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
Caused by: java.security.InvalidKeyException: Invalid RSA private key
    at sun.security.rsa.RSAPrivateCrtKeyImpl.parseKeyBits(RSAPrivateCrtKeyImpl.java:206)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:342)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
    ... 28 more
Caused by: java.io.IOException: Version must be 0
    at sun.security.rsa.RSAPrivateCrtKeyImpl.parseKeyBits(RSAPrivateCrtKeyImpl.java:192)
    ... 34 more

实施

我试过同时使用 Java 和 bouncycastle 提供商:

byte[] pkcs8EncodedKey = Base64.getDecoder().decode(APNS_PRIVATE_KEY);
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

我创建了一个示例项目:http://tutorialpoint.com

这是测试密钥

-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg9eWdXw19hL94+Jx1xjb79Y3Hr9rAaRYaoe4XSv6BnPigCgYIKoZIzj0DAQehRANCAAR9VOiSABvXFHeq/hCMEx63Vq0mYneI2aqQu5sLu5x8DrzUd82BodKoUG3dMPWY9m86dGYAR9xhVUlBDpap9TfH
-----END PRIVATE KEY-----

解决方案

苹果基本上不用RSA算法,而是用ECC(Elliptic curve cryptography)所以我在加载私钥的时候不得不用EC算法

http://rahulatjava.blogspot.si/2014/02/elliptical-curve-cryptography-in-java.html

工作版本

byte[] pkcs8EncodedKey = Base64.getDecoder().decode(APNS_PRIVATE_KEY);
KeyFactory factory = KeyFactory.getInstance("EC");
PrivateKey privateKey = factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));