Java Code Examples for org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter#getKeyPair()

The following examples show how to use org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter#getKeyPair() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicKeyStore.java    From env-keystore with MIT License 6 votes vote down vote up
protected static PrivateKey getPrivateKeyFromPEM(final Reader keyReader)
    throws IOException {
  final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();

  final PEMParser pem = new PEMParser(keyReader);

  PrivateKey key;
  Object pemContent = pem.readObject();
  if (pemContent instanceof PEMKeyPair) {
    PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
    KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
    key = keyPair.getPrivate();
  } else if (pemContent instanceof PrivateKeyInfo) {
    PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
    key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
  } else {
    throw new IllegalArgumentException("Unsupported private key format '" + pemContent.getClass().getSimpleName() + '"');
  }

  pem.close();
  return key;
}
 
Example 2
Source File: JwtCreatorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 6 votes vote down vote up
private static PrivateKey generatePrivateKey(PrivateKeyInfo info)
    throws InvalidKeySpecException, GeneralSecurityException, NoSuchAlgorithmException, IOException, PEMException
{
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMParser pr = new PEMParser(new StringReader(new String(info.keyBytes, StandardCharsets.UTF_8)));
    Object o = pr.readObject();

    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        throw new IllegalStateException("Didn't find OpenSSL key");
    }
    KeyPair kp;
    if (o instanceof PEMEncryptedKeyPair) {
        JcePEMDecryptorProviderBuilder bcDecProvider = new JcePEMDecryptorProviderBuilder().setProvider("BC");
        char[] charArray = info.password.toCharArray();
        PEMDecryptorProvider decProv = bcDecProvider.build(charArray);
        kp = converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv));
    }
    else {
        kp = converter.getKeyPair((PEMKeyPair)o);
    }

    PrivateKey privKey = kp.getPrivate();
    return privKey;
}
 
Example 3
Source File: DKIMSign.java    From james-project with Apache License 2.0 6 votes vote down vote up
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    try (InputStreamReader pemReader = new InputStreamReader(rawKey)) {
        try (PEMParser pemParser = new PEMParser(pemReader)) {
            Object pemObject = pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair keyPair;
            if (pemObject instanceof PrivateKeyInfo) {
                return converter.getPrivateKey((PrivateKeyInfo)pemObject);
            }
            if (pemObject instanceof PEMEncryptedKeyPair) {
                PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
                keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv));
            } else {
                keyPair = converter.getKeyPair((PEMKeyPair) pemObject);
            }

            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class);

            return keyFac.generatePrivate(privateKeySpec);
        }
    }
}
 
Example 4
Source File: SSLFactory.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Reads a base64-format PEM key and returns a Java KeyPair for it.
 * @param privateKey PEM-encoded private key
 */
public static KeyPair readKeyPair(String privateKey) {
    try (StringReader keyReader = new StringReader(privateKey);
         PEMParser pemReader = new PEMParser(keyReader)) {
        
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        return converter.getKeyPair((PEMKeyPair) pemReader.readObject());
    } catch (IOException x) {
        // Shouldn't occur, since we're only reading from strings
        throw new RuntimeException(x);            
    }
}
 
Example 5
Source File: AccessTokenRetrieverServiceImpl.java    From okta-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Get Private key from input PEM file.
 *
 * @param reader
 * @return {@link PrivateKey}
 * @throws IOException
 */
PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException {
    PrivateKey privateKey;

    try (PEMParser pemParser = new PEMParser(reader)) {
        JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
        Object pemContent = pemParser.readObject();

        if (pemContent == null) {
            throw new IllegalArgumentException("Invalid Private Key PEM file");
        }

        if (pemContent instanceof PEMKeyPair) {
            PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent;
            KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
            privateKey = keyPair.getPrivate();
        } else if (pemContent instanceof PrivateKeyInfo) {
            PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent;
            privateKey = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo);
        } else {
            throw new IllegalArgumentException("Unsupported Private Key format '" +
                pemContent.getClass().getSimpleName() + '"');
        }
    }

    return privateKey;
}
 
Example 6
Source File: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Deprecated
private void startSession() throws IOException {
    final ConnectFuture connectFuture;
    connectFuture = client.connect(deviceInfo.name(),
            deviceInfo.ip().toString(),
            deviceInfo.port())
            .verify(connectTimeout, TimeUnit.SECONDS);
    session = connectFuture.getSession();
    //Using the device ssh key if possible
    if (deviceInfo.getKey() != null) {
        try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
            try {
                KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
                session.addPublicKeyIdentity(kp);
            } catch (IOException e) {
                throw new NetconfException("Failed to authenticate session with device " +
                        deviceInfo + "check key to be a valid key", e);
            }
        }
    } else {
        session.addPasswordIdentity(deviceInfo.password());
    }
    session.auth().verify(connectTimeout, TimeUnit.SECONDS);
    Set<ClientSession.ClientSessionEvent> event = session.waitFor(
            ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
                    ClientSession.ClientSessionEvent.CLOSED,
                    ClientSession.ClientSessionEvent.AUTHED), 0);

    if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
        log.debug("Session closed {} {}", event, session.isClosed());
        throw new NetconfException("Failed to authenticate session with device " +
                deviceInfo + "check the user/pwd or key");
    }
    openChannel();
}
 
Example 7
Source File: CertificateManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * Parses a PrivateKey instance from a PEM representation.
 *
 * When the provided key is encrypted, the provided pass phrase is applied.
 *
 * @param pemRepresentation a PEM representation of a private key (cannot be null or empty)
 * @param passPhrase optional pass phrase (must be present if the private key is encrypted).
 * @return a PrivateKey instance (never null)
 * @throws IOException if there was a problem parsing the key
 */
public static PrivateKey parsePrivateKey(InputStream pemRepresentation, String passPhrase) throws IOException {

    if ( passPhrase == null ) {
        passPhrase = "";
    }
    try (Reader reader = new InputStreamReader(pemRepresentation); //
            PEMParser pemParser = new PEMParser(reader)) {

        final Object object = pemParser.readObject();
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider( "BC" );

        final KeyPair kp;

        if ( object instanceof PEMEncryptedKeyPair )
        {
            // Encrypted key - we will use provided password
            final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build( passPhrase.toCharArray() );
            kp = converter.getKeyPair( ( (PEMEncryptedKeyPair) object ).decryptKeyPair( decProv ) );
        }
        else if ( object instanceof PKCS8EncryptedPrivateKeyInfo )
        {
            // Encrypted key - we will use provided password
            try
            {
                final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build( passPhrase.toCharArray() );
                final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo( provider );
                return converter.getPrivateKey( privateKeyInfo );
            }
            catch ( PKCSException | OperatorCreationException e )
            {
                throw new IOException( "Unable to decrypt private key.", e );
            }
        }
        else if ( object instanceof PrivateKeyInfo )
        {
            return converter.getPrivateKey( (PrivateKeyInfo) object );
        }
        else
        {
            // Unencrypted key - no password needed
            kp = converter.getKeyPair( (PEMKeyPair) object );
        }
        return kp.getPrivate();
    }
}