Android KeyStore参数构建

Android KeyStore parameters building

我正在尝试将 RSA 加密与 KeyStore 结合使用,我需要为 KeyPairGenerator 指定参数,但我迷路了。 KeyPairGeneratorPair 有点直截了当,但我不明白 KeyGenParameterSpec for API>=23

这就是我所做的,我想我在 else 部分得到了所有内容,但现在我对 KeyGenParameterSpec

感到困惑

RSAKeyGenParameterSpec 中的 public 指数到底是什么?

我应该指定 .setDigests 中的哪些摘要?

还有 .setBlockMode() 方法可以调用,因为我使用的是 RSA 并且 RSA/None/OAEPWithSHA1AndMGF1Padding 要设置哪个块模式?欧洲央行、加拿大央行?

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                generator.initialize(new KeyGenParameterSpec.Builder("PrivateKey", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, RSAKeyGenParameterSpec.F4))
                        .setDigests(KeyProperties.DIGEST_SHA1,
                                KeyProperties.DIGEST_SHA256)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
                        .setCertificateSerialNumber(BigInteger.ONE)
                        .setCertificateSubject(new X500Principal("CN=" + "PrivateKey"))
                        .setCertificateNotBefore(calendar.getTime())
                        .setCertificateNotAfter(endCalendar.getTime())
                        .setKeySize(2048).build());
            } else {
                generator.initialize(new KeyPairGeneratorSpec.Builder(MainActivity.this)
                        .setAlias("PrivateKey")
                        .setSerialNumber(BigInteger.ONE)
                        .setSubject(new X500Principal("CN=" + "PrivateKey"))
                        .setStartDate(calendar.getTime())
                        .setEndDate(endCalendar.getTime())
                        .setKeySize(2048).build()      

 );
            }

Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding");

方法 setDigests() 为您的填充模式设置摘要方法,setBlockMode() 设置加密模式,这取决于您的工作。

我觉得你设置了很多不必要的字段。例如,我使用此方法创建自己的 RSA 密钥:

public boolean createKey() {
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA,
                "AndroidKeyStore"
        );

        mKeyStore.load(null);
        KeyGenParameterSpec.Builder builder =
                new KeyGenParameterSpec.Builder(
                        MY_KEY,
                        KeyProperties.PURPOSE_DECRYPT).
                setKeySize(MY_KEYLEN).
                setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP).
                setDigests(KeyProperties.DIGEST_SHA256);

        keyPairGenerator.initialize(builder.build());
        keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException | CertificateException | IOException |
            InvalidAlgorithmParameterException | NoSuchProviderException e) {
        return false;
    }

    return true;
}

我创建此密钥是为了与 RSA/ECB/OAEPWithSHA-256AndMGF1Padding 算法一起使用。