public static final int getKeySize ( Key key ) { int size = - 1 ; if ( key instanceof Length ) { try { Length ruler = ( Length ) key ; size = ruler . length ( ) ; } catch ( UnsupportedOperationException usoe ) { // ignore the exception } if ( size >= 0 ) { return size ; } } // try to parse the length from key specification if ( key instanceof SecretKey ) { SecretKey sk = ( SecretKey ) key ; String format = sk . getFormat ( ) ; if ( "RAW" . equals ( format ) && sk . getEncoded ( ) != null ) { size = ( sk . getEncoded ( ) . length * 8 ) ; } // Otherwise, it may be a unextractable key of PKCS#11, or // a key we are not able to handle. } else if ( key instanceof RSAKey ) { RSAKey pubk = ( RSAKey ) key ; size = pubk . getModulus ( ) . bitLength ( ) ; } else if ( key instanceof ECKey ) { ECKey pubk = ( ECKey ) key ; ECParameterSpec params = pubk . getParams ( ) ; // According to RFC 3279 section 2.3.5, EC keys are allowed // to inherit parameters in an X.509 certificate issuer's // key parameters, so the parameters may be null. The parent // key will be rejected if its parameters don't pass, so this // is okay. if ( params != null ) { size = params . getOrder ( ) . bitLength ( ) ; } } else if ( key instanceof DSAKey ) { DSAKey pubk = ( DSAKey ) key ; DSAParams params = pubk . getParams ( ) ; // According to RFC 3279 section 2.3.2, DSA keys are allowed // to inherit parameters in an X.509 certificate issuer's // key parameters, so the parameters may be null. The parent // key will be rejected if its parameters don't pass, so this // is okay. if ( params != null ) { size = params . getP ( ) . bitLength ( ) ; } } else if ( key instanceof DHKey ) { DHKey pubk = ( DHKey ) key ; size = pubk . getParams ( ) . getP ( ) . bitLength ( ) ; } // Otherwise, it may be a unextractable key of PKCS#11, or // a key we are not able to handle. return size ; }
Returns the key size of the given key object in bits .