2017-08-10 76 views
0

我試圖在Android中使用由Android KeyStore Provider生成的私鑰實現ECDH。使用Android KeyStore的ECDH生成私鑰

E /失敗:java.security.InvalidKeyException:

public byte[] ecdh(PublicKey otherPubKey) throws Exception { 

    try { 
     ECPublicKey ecPubKey = (ECPublicKey) otherPubKey; 
     KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH"); 
     PrivateKey pk = (PrivateKey) LoadPrivateKey("Backend"); 
     keyAgreement.init(pk); 
     keyAgreement.doPhase(ecPubKey, true); 

     return (keyAgreement.generateSecret()); 
    } 
    catch (Exception e) 
    { 
     Log.e("failure", e.toString()); 
     return null; 
    } 
} 

然而,這種異常在keyAgreement.init(PK)逮住不能識別EC私鑰:java.security.InvalidKeyException:無編碼EC私鑰

我產生之前成功的「後端」使用公鑰/私鑰對:

public void GenerateNewKeyPair(String alias) 
     throws Exception { 

    if (!keyStore.containsAlias(alias)) { 
     // use the Android keystore 
     KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE); 
     keyGen.initialize(
       new KeyGenParameterSpec.Builder(
         alias, 
         KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY | KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) 
         .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")) 
         .setDigests(KeyProperties.DIGEST_SHA256, 
           KeyProperties.DIGEST_SHA384, 
           KeyProperties.DIGEST_SHA512) 
         .setRandomizedEncryptionRequired(true) 
         .build()); 
     // generates the keypair 
     KeyPair keyPair = keyGen.generateKeyPair(); 
    } 

}

我使用加載私鑰:

public PrivateKey LoadPrivateKey(String alias) throws Exception { 
    PrivateKey key = (PrivateKey) keyStore.getKey(alias, null); 
    return key; 
} 

任何人有一個想法發生了什麼,可以幫助我瞭解如何解決它?謝謝!

回答

1

據我所知,通過研究和試驗和錯誤,這是而不是目前支持。

我相信你能做的最好的就是簽署你在AndroidKeyStore之外生成的一個EC密鑰對的公鑰,該密鑰對存儲在AndroidKeyStore中的一個EC密鑰對。然後,您可以使用簽名密鑰證書將簽署的公鑰發送給另一方,生成共享密鑰(AndroidKeyStore外部),然後將生成的密鑰中使用KDF派生的SecretKey存儲。我建議使用這個非AndroidKeyStore生成的密鑰對一次(因此僅用於派生祕密),並在必要時重複此過程以重新密鑰。

編輯:當我說'存儲SecretKey'時,我的意思是在AndroidKeyStore中。在這種情況下,這個關鍵點最初將處於所謂的「正常世界」,但它現在可以做的最好。