从私钥或密钥库生成CSR

时间:2016-07-02 12:08:32

标签: android keystore private-key public-key csr

如何从密钥库中生成CSR。

我已从密钥对生成CSR。以下是我的代码。

public static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String cn) throws IOException,
        OperatorCreationException {
    String principal = String.format(CN_PATTERN, cn);

    ContentSigner signer = new JCESigner (keyPair.getPrivate(),DEFAULT_SIGNATURE_ALGORITHM);

    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
            new X500Name(principal), keyPair.getPublic());
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(
            true));
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            extensionsGenerator.generate());
    Log.e("csr builder ","csr "+csrBuilder.toString());
    PKCS10CertificationRequest csr = csrBuilder.build(signer);

    return csr;
}

但我无法从Keystore(私钥)生成CSR。 有什么方法可以从Keystore生成密钥对吗?

请帮助我。谢谢。

2 个答案:

答案 0 :(得分:2)

您的代码与Android KeyStore兼容。您只需要在KeyPair

中生成Keystore即可

KeyStore可从Android 4.3(API级别18)获得。

之间存在细微差别

Android> = 18< 23

KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(alias)
                .setSubject(new X500Principal("CN=" + alias + ", O=Android Authority"))
                .setSerialNumber(BigInteger.ONE)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");

kpg.initialize(spec);
KeyPair keyPair = kpg.generateKeyPair();

Android> = 23

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");


kpg.initialize(new KeyGenParameterSpec.Builder(
                alias,
                KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                .build());

KeyPair keyPair = kpg.generateKeyPair();

答案 1 :(得分:0)

我认为你在谈论java.security.KeyStore。此抽象要求每个存储的PrivateKey具有相应的Certificate个实例链(一个或多个证书)。这意味着您应该能够从KeyPair的私钥条目创建KeyStore。例如,如果私钥存储在" test":

String alias = "test";
KeyStore keyStore = KeyStore.getInstance(...);
keyStore.load(...;);
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null);
PublicKey publicKey = keyStore.getCertificate(alias).getPublicKey();
KeyPair keyPair = new KeyPair(publicKey, privateKey);
generateCsr(keyPair, ...);