// internal implementation of translateKey() for public keys. See JCA doc private PublicKey translatePublicKey(PublicKey key) throws InvalidKeyException { if (key instanceof RSAPublicKey) { if (key instanceof RSAPublicKeyImpl) { return key; } RSAPublicKey rsaKey = (RSAPublicKey) key; try { return new RSAPublicKeyImpl(rsaKey.getModulus(), rsaKey.getPublicExponent()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPublicKey throw new InvalidKeyException("Invalid key", e); } } else if ("X.509".equals(key.getFormat())) { byte[] encoded = key.getEncoded(); return new RSAPublicKeyImpl(encoded); } else { throw new InvalidKeyException( "Public keys must be instance " + "of RSAPublicKey or have X.509 encoding"); } }