ECDH使用Android KeyStore生成私钥

时间:2017-08-10 13:07:05

标签: java android keystore

我正在尝试使用Android KeyStore Provider生成的私有在Android中实现ECDH。

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)中捕获的:

  

E / failure:java.security.InvalidKeyException:无法识别EC私钥:java.security.InvalidKeyException:没有EC私钥的编码

我使用以下方法成功生成“Backend”公钥/私钥对:

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;
}

任何人都知道发生了什么,可以帮助我理解如何解决它?谢谢!

2 个答案:

答案 0 :(得分:3)

据我所知,通过研究和反复试验,目前支持

我相信您可以做的最好的事情是在AndroidKeyStore外部生成一个EC密钥对的公钥,并使用EC密钥对 存储在AndroidKeyStore中。然后,您可以使用您的签名密钥证书将此签名的公钥发送给另一方,生成共享密钥(在AndroidKeyStore之外),然后在生成的密钥上存储使用KDF派生的SecretKey。我建议使用这个非AndroidKeyStore生成的密钥对一次(因此只是为了导出秘密),并在必要时重复此过程重新密钥。

编辑:当我说'存储SecretKey'时,我的意思是在AndroidKeyStore中。在这种情况下,这个密钥最初会出现在所谓的“正常世界”中,但它是你现在能做的最好的。

答案 1 :(得分:0)

API级别23支持ECDH。请参阅Android Keystore System

上的android文档

此链接中也提供了示例代码..