Android KeyStore参数构建

时间:2018-11-14 18:21:43

标签: android encryption rsa keystore

我正在尝试通过KeyStore使用RSA加密,并且我需要为KeyPairGenerator指定参数,而我在这里迷路了。 KeyPairGeneratorPair挺简单的,但我不理解API> = 23

KeyGenParameterSpec

这就是我所做的,我想我已经else部分了,但是现在我对KeyGenParameterSpec感到困惑

RSAKeyGenParameterSpec中确切的公共指数是什么?

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

也有.setBlockMode()个方法可以调用,并且由于我正在使用RSA和RSA/None/OAEPWithSHA1AndMGF1Padding设置哪种阻止模式? ECB,CBC?

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");

1 个答案:

答案 0 :(得分:1)

方法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算法的密钥。