Search code examples
androidauthenticationsslcertificateclient-certificates

Generating a client certificate on an Android device


I want to create an Android application which will use SSL client certificate authentication.

I have found sample codes which show me how two use SSL client certificate authentication in an Android application. This is clear to me.

My problem is however that I want to generate an SSL client certificate on the device. Simply stated, I want my program to do the following:

When the program is installed on the device, a client certificate should be generated on the device (when running it for the first time), and a public key finger print will be sent to my server. (The certificate must be generated on first use).

How can I generate a client certificate on and Android device from my application?


Solution

  • You can run the following code on Android to generate a keypair and retrieve the fingerprint. It uses the excellent JSCH library from jCraft.

    public void generatePublicPrivateKeyPair() throws Exception {
    
            ByteArrayOutputStream privateKeyOutputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream publicKeyOutputStream = new ByteArrayOutputStream();
    
            JSch jsch=new JSch();
            KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA);
            //kpair.setPassphrase(passphrase);
            kpair.writePrivateKey(privateKeyOutputStream);
            kpair.writePublicKey(publicKeyOutputStream, "Generated by vPro Management Console");
    
            String fingerPrint = kpair.getFingerPrint();
            System.out.println("Finger print: "+ fingerPrint);
            kpair.dispose();
    
            byte[] privateKey = privateKeyOutputStream.toByteArray();
            byte[] publicKey = publicKeyOutputStream.toByteArray();
    
            System.out.println("Private key " + new String(privateKey));
            System.out.println("Public key " + new String(publicKey));
    
    
    }   
    

    Simply place the JAR in your libs folder and you're good to go.

    If you use maven, you can reference the JSCH dependency like this:

    <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.50</version>
    </dependency>