Search code examples
javassl-certificatebouncycastlecsr

How to determine the Public Key Size from the CSR file using Bouncy Castle in java?


I have a CSR file provided by the client, i'm able to find the key type (RSA/DSA) via JcaPKCS10CertificationRequest getPublicKey().getAlgorithm() method, but i'm unable to find any suitable way to determine the length/size of the public key (ex: 1024/2048/4096 bits).


Solution

  • As far as I understand it there isn't any common way to obtain the 'key size' of a public key. Instead, check your public key to see if it implements interfaces such as RSAPublicKey or DSAPublicKey. If it does, use the various interface methods to extract a property from the key and get the bit length of that, for example:

    PublicKey publicKey = yourRequest.getPublicKey();
    int keySize
    if (publicKey instanceof RSAPublicKey) {
        keySize = ((RSAPublicKey)publicKey).getPublicExponent().bitLength();
    } else if (publicKey instance DSAPublicKey) {
        keySize = ((DSAPublicKey)publicKey).getY().bitLength();
    } else {
        // handle other public key types.
    }