我試圖在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;
}
任何人有一個想法發生了什麼,可以幫助我瞭解如何解決它?謝謝!