Android Conscrypt不会引发InvalidKeyException

时间:2019-02-21 17:53:25

标签: android encryption openssl cryptography

当生成不同密钥大小的密钥(未指定提供者并且默认选择Conscrypt),然后使用KeyAgreement生成共享密钥时,我希望InvalidKeyException是抛出。

在3台Android设备上进行测试后,我发现在运行Android 9的设备上正确抛出了InvalidKeyException

但是,在运行Android 6和Android 7的设备上,未抛出InvalidKeyException

这是在已测试的测试中运行的测试和代码:

测试

@Test
public void generateECDHSharedSecret_returnsNull_ifKeySizesDifferent() throws NoSuchAlgorithmException {
    KeyPairGenerator deviceKeyGenerator = KeyPairGenerator.getInstance("EC");
    deviceKeyGenerator.initialize(224);
    KeyPairGenerator serverKeyGenerator = KeyPairGenerator.getInstance("EC");
    serverKeyGenerator.initialize(256);
    PublicKey serverPublicKey = deviceKeyGenerator.generateKeyPair().getPublic();
    PrivateKey devicePrivateKey = serverKeyGenerator.generateKeyPair().getPrivate();
    byte[] sharedSecret = ServerKeyAgreement.generateECDHSharedSecret(devicePrivateKey, serverPublicKey);

    Assert.assertNull(sharedSecret);
}

实施

package com.bla.bla;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.KeyAgreement;

class ServerKeyAgreement {
    static byte[] generateECDHSharedSecret(PrivateKey privateKey, PublicKey publicKey) {
        try {
            KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
            keyAgreement.init(privateKey);
            keyAgreement.doPhase(publicKey, true);
            return keyAgreement.generateSecret();
        } catch (NoSuchAlgorithmException |
                InvalidKeyException |
                RuntimeException e) {
            return null;
        }
    }
}

为什么InvalidKeyException不会在Android 6和7上抛出,并且生成的共享机密实际上有效吗?

0 个答案:

没有答案