簡體   English   中英

將Apple APNs身份驗證密鑰加載到Java PrivateKey

[英]Loading Apple APNs auth key to Java PrivateKey

問題

我在將APN的身份驗證密鑰加載到Java時遇到困難。 我的理解是Java可以讀取PKCS8編碼的私鑰,但是我遇到了異常。

我使用充氣城堡(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-----

基本上,Apple不使用RSA算法,而是使用ECC(橢圓曲線密碼學),因此在加載私鑰時必須使用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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM