Example usage for org.apache.commons.ssl PKCS8Key getPrivateKey

List of usage examples for org.apache.commons.ssl PKCS8Key getPrivateKey

Introduction

In this page you can find the example usage for org.apache.commons.ssl PKCS8Key getPrivateKey.

Prototype

public PrivateKey getPrivateKey() 

Source Link

Usage

From source file:com.ibm.mqlight.api.security.KeyStoreUtils.java

/**
 * Creates a {@link PrivateKey} instance from the passed private key PEM format file and certificate chain.
 *
 * @param pemKeyFile//  ww  w  . j  a  va  2 s.  c om
 *            A PEM format file containing the private key.
 * @param passwordChars
 *            The password that protects the private key.
 * @return the private key, created by this method.
 * @throws IOException if the file cannot be read.
 * @throws GeneralSecurityException if a cryptography problem is encountered.
 */
public static PrivateKey createPrivateKey(File pemKeyFile, char[] passwordChars)
        throws IOException, GeneralSecurityException {
    final String methodName = "createPrivateKey";
    logger.entry(methodName, pemKeyFile);

    // Read the private key from the PEM format file
    final PemFile privateKeyPemFile = new PemFile(pemKeyFile);
    final byte[] privateKeyBytes = privateKeyPemFile.getPrivateKeyBytes();

    final PrivateKey privateKey;
    if (privateKeyPemFile.containsEncryptedPrivateKey()) {
        // We should be able to do the follows (using standard JDK classes):
        //    EncryptedPrivateKeyInfo encryptPrivateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyBytes);
        //    Cipher cipher = Cipher.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordChars);
        //    SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    Key pbeKey = secFac.generateSecret(pbeKeySpec);
        //    AlgorithmParameters algParams = encryptPrivateKeyInfo.getAlgParameters();
        //    cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
        //    KeySpec keySpec = encryptPrivateKeyInfo.getKeySpec(cipher);
        //    privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
        // but this can fail with a: "Unsupported key protection algorithm" if key was generated with openssl
        //
        // Instead we use the Apache commons SSL PKCS8Key class from Julius Davies (see not-yet-commons-ssl in Maven)
        // which seems more reliable
        final PKCS8Key key = new PKCS8Key(privateKeyBytes, passwordChars);
        privateKey = key.getPrivateKey();
    } else {
        final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        InvalidKeySpecException keyFactoryException = null;
        PrivateKey key = null;
        for (String alg : new String[] { "RSA", "DSA", "DiffieHellman", "EC" }) {
            try {
                key = KeyFactory.getInstance(alg).generatePrivate(keySpec);
                break;
            } catch (InvalidKeySpecException e) {
                if (keyFactoryException == null)
                    keyFactoryException = e;
            }
        }
        if (key == null)
            throw keyFactoryException;
        privateKey = key;
    }

    logger.exit(methodName, privateKey);

    return privateKey;
}

From source file:com.valco.utility.FacturasUtility.java

private static java.security.PrivateKey getPrivateKey(byte[] bytesClave, String clave)
        throws GeneralSecurityException {
    PKCS8Key pkcs8 = null;
    pkcs8 = new PKCS8Key(bytesClave, clave.toCharArray());
    java.security.PrivateKey pk;//from   w w  w  . ja v a2s. c  o  m
    pk = pkcs8.getPrivateKey();
    return pk;
}

From source file:fr.aliasource.webmail.common.message.Mime4jFormatter.java

private PrivateKey loadPK() {
    PrivateKey privateKey = null;
    File f = new File("/etc/minig/dkim_pk.pem");
    if (!f.exists()) {
        return privateKey;
    }// w  w w  .  j  av a  2  s .c o m

    try {
        PKCS8Key pkcs8 = new PKCS8Key(new FileInputStream(f), null);
        privateKey = pkcs8.getPrivateKey();
    } catch (Exception e) {
        logger.error("Error loading private key for DKIM signing", e);
    }
    return privateKey;
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida el password y que la llave privada corresponda a la
 * llave publica//from   w  w w. ja va2 s  . c om
 *
 * @return true si el password y llave privada corresponden, en otro caso
 * false
 */
public boolean validaCorrespondencias() {

    try {

        PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray());
        //valida el pass
        PrivateKey pk = pkcs8.getPrivateKey();
        //valida que la llave privada corresponda  a la llave publica
        X509Certificate cert = X509Certificate.getInstance(this.clavePublica);
        Signature firma = Signature.getInstance("SHA1withRSA");
        firma.initSign(pk);
        byte[] firmado = firma.sign();
        firma.initVerify(cert.getPublicKey());
        if (firma.verify(firmado)) {
            return this.correcto;
        } else {
            return this.error;
        }
    } catch (GeneralSecurityException e) {

        return this.error;
    } catch (CertificateException e) {

        return this.error;
    }
}

From source file:org.apache.james.jdkim.mailets.DKIMSign.java

public void init() throws MessagingException {
    signatureTemplate = getInitParameter("signatureTemplate");
    String privateKeyString = getInitParameter("privateKey");
    String privateKeyPassword = getInitParameter("privateKeyPassword", null);
    forceCRLF = getInitParameter("forceCRLF", true);
    try {//  www.j a v a2 s  .  c  om
        PKCS8Key pkcs8 = new PKCS8Key(new ByteArrayInputStream(privateKeyString.getBytes()),
                privateKeyPassword != null ? privateKeyPassword.toCharArray() : null);
        privateKey = pkcs8.getPrivateKey();
        // privateKey = DKIMSigner.getPrivateKey(privateKeyString);
    } catch (NoSuchAlgorithmException e) {
        throw new MessagingException("Unknown private key algorythm: " + e.getMessage(), e);
    } catch (InvalidKeySpecException e) {
        throw new MessagingException(
                "PrivateKey should be in base64 encoded PKCS8 (der) format: " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new MessagingException("General security exception: " + e.getMessage(), e);
    }
}

From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHGeneratorKeyFileProviderTest.java

@Test
public void convertSimpleKey() throws Exception {
    File temp = File.createTempFile(this.getClass().getCanonicalName(), ".pem");
    temp.deleteOnExit();//from  w  ww.j  av  a 2 s. c  om

    SimpleGeneratorHostKeyProvider simpleGenerator = new SimpleGeneratorHostKeyProvider(temp);
    simpleGenerator.setKeySize(2048);
    simpleGenerator.setAlgorithm("DSA");
    List<KeyPair> keys = simpleGenerator.loadKeys();
    KeyPair simpleKeyPair = keys.stream().findFirst().get();

    Assert.assertEquals("DSA", simpleKeyPair.getPrivate().getAlgorithm());

    OpenSSHKeyPairProvider provider = new OpenSSHKeyPairProvider(temp, "DSA", 2048);
    KeyPair convertedKeyPair = provider.loadKeys().iterator().next();
    Assert.assertEquals("DSA", convertedKeyPair.getPrivate().getAlgorithm());

    Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(),
            convertedKeyPair.getPrivate().getEncoded());
    Assert.assertArrayEquals(simpleKeyPair.getPublic().getEncoded(), convertedKeyPair.getPublic().getEncoded());

    //also test that the original file has been replaced
    PKCS8Key pkcs8 = new PKCS8Key(Files.newInputStream(temp.toPath()), null);
    KeyPair keyPair = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
    Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), keyPair.getPrivate().getEncoded());

}

From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHKeyPairProvider.java

private KeyPair getKeyPair(FileInputStream is) throws GeneralSecurityException, IOException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    KeyPair kp = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
    return kp;//from  w  w w .j  av  a 2  s  . c  o m
}

From source file:org.apache.karaf.shell.ssh.OpenSSHGeneratorFileKeyProvider.java

@Override
protected KeyPair doReadKeyPair(String resourceKey, InputStream is)
        throws IOException, GeneralSecurityException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    return new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
}

From source file:org.apache.kerby.pkix.PkiLoader.java

private PrivateKey doLoadPrivateKey(InputStream inputStream, String password)
        throws GeneralSecurityException, IOException {
    if (password == null) {
        password = "";
    }//from  ww  w.ja  va 2  s  .c  o  m
    // If the provided InputStream is encrypted, we need a password to decrypt
    // it. If the InputStream is not encrypted, then the password is ignored
    // (can be null).  The InputStream can be DER (raw ASN.1) or PEM (base64).
    PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());

    // If an unencrypted PKCS8 key was provided, then this actually returns
    // exactly what was originally passed inputStream (with no changes).  If an OpenSSL
    // key was provided, it gets reformatted as PKCS #8 first, and so these
    // bytes will still be PKCS #8, not OpenSSL.
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);

    // A Java PrivateKey object is born.
    PrivateKey pk = null;
    if (pkcs8.isDSA()) {
        pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
    } else if (pkcs8.isRSA()) {
        pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    // For lazier types:
    pk = pkcs8.getPrivateKey();

    return pk;
}

From source file:org.auscope.portal.server.web.controllers.GridLoginController.java

/**
 * Extracts and decrypts the XML response received from the SLCS server
 *///ww  w  .  j av  a2 s .c o  m
private String extractSlcsResponse(HttpServletRequest request) throws GeneralSecurityException, IOException {
    String responseXML = null;
    String certReqDataHex = request.getParameter("CertificateRequestData");
    String sessionKeyHex = request.getParameter("SessionKey");
    if (certReqDataHex == null || sessionKeyHex == null) {
        logger.error("CertificateRequestData or SessionKey empty!");
    } else {
        // load host key
        FileInputStream in = new FileInputStream(HOST_KEY_FILE);
        PKCS8Key pem = new PKCS8Key(in, null);
        Key privateKey = pem.getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);

        // unwrap session key and decrypt request data
        byte[] wrappedKey = unhexlify(sessionKeyHex);
        ByteArrayInputStream certReqDataEnc = new ByteArrayInputStream(unhexlify(certReqDataHex));
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        responseXML = decryptString(certReqDataEnc, cipher);
    }
    return responseXML;
}