// internal implementation of translateKey() for private keys. See JCA doc private PrivateKey translatePrivateKey(PrivateKey key) throws InvalidKeyException { if (key instanceof RSAPrivateCrtKey) { if (key instanceof RSAPrivateCrtKeyImpl) { return key; } RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; try { return new RSAPrivateCrtKeyImpl( rsaKey.getModulus(), rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPrivateCrtKey throw new InvalidKeyException("Invalid key", e); } } else if (key instanceof RSAPrivateKey) { if (key instanceof RSAPrivateKeyImpl) { return key; } RSAPrivateKey rsaKey = (RSAPrivateKey) key; try { return new RSAPrivateKeyImpl(rsaKey.getModulus(), rsaKey.getPrivateExponent()); } catch (RuntimeException e) { // catch providers that incorrectly implement RSAPrivateKey throw new InvalidKeyException("Invalid key", e); } } else if ("PKCS#8".equals(key.getFormat())) { byte[] encoded = key.getEncoded(); return RSAPrivateCrtKeyImpl.newKey(encoded); } else { throw new InvalidKeyException( "Private keys must be instance " + "of RSAPrivate(Crt)Key or have PKCS#8 encoding"); } }
// internal implementation of generatePrivate. See JCA doc private PrivateKey generatePrivate(KeySpec keySpec) throws GeneralSecurityException { if (keySpec instanceof PKCS8EncodedKeySpec) { PKCS8EncodedKeySpec pkcsSpec = (PKCS8EncodedKeySpec) keySpec; return RSAPrivateCrtKeyImpl.newKey(pkcsSpec.getEncoded()); } else if (keySpec instanceof RSAPrivateCrtKeySpec) { RSAPrivateCrtKeySpec rsaSpec = (RSAPrivateCrtKeySpec) keySpec; return new RSAPrivateCrtKeyImpl( rsaSpec.getModulus(), rsaSpec.getPublicExponent(), rsaSpec.getPrivateExponent(), rsaSpec.getPrimeP(), rsaSpec.getPrimeQ(), rsaSpec.getPrimeExponentP(), rsaSpec.getPrimeExponentQ(), rsaSpec.getCrtCoefficient()); } else if (keySpec instanceof RSAPrivateKeySpec) { RSAPrivateKeySpec rsaSpec = (RSAPrivateKeySpec) keySpec; return new RSAPrivateKeyImpl(rsaSpec.getModulus(), rsaSpec.getPrivateExponent()); } else { throw new InvalidKeySpecException( "Only RSAPrivate(Crt)KeySpec " + "and PKCS8EncodedKeySpec supported for RSA private keys"); } }