I read this article.
It says how to generate a KeyPair
, however it doesn\'t specify how to generate a Certificate Signing Request based on the generated
The best way to create a CSR on Android is to use SpongyCastle, which is an implementation of BouncyCastle for Android. SpongyCastle already does a lot of the heavy-lifting for you so it will make your life much easier.
My implementation is heavily based on the answer found here, but uses the Android KeyStore for security and SpongyCastle's JcaContentSignerBuilder()
instead of the custom ContentSigner
.
build.gradle
file:compile 'com.madgag.spongycastle:core:1.51.0.0'
compile 'com.madgag.spongycastle:pkix:1.51.0.0'
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); // store the key in the Android KeyStore for security purposes
keyGen.initialize(new KeyGenParameterSpec.Builder(
"key1",
KeyProperties.PURPOSE_SIGN)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setDigests(KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA384,
KeyProperties.DIGEST_SHA512)
.build()); // defaults to RSA 2048
KeyPair keyPair = keyGen.generateKeyPair();
private final static String CN_PATTERN = "CN=%s, O=Aralink, OU=OrgUnit";
//Create the certificate signing request (CSR) from private and public keys
public static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String cn) throws IOException, OperatorCreationException {
String principal = String.format(CN_PATTERN, cn);
ContentSigner signer = new JcaContentSignerBuilder(DEFAULT_RSA_SIGNATURE_ALGORITHM).build(keyPair.getPrivate());
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());
PKCS10CertificationRequest csr = csrBuilder.build(signer);
return csr;
}
}
And that's it, now you have a PKCS10CertificationRequest
that you can send to your server.