All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adobe.platform.operation.internal.util.PrivateKeyParser Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
/*
 * Copyright 2019 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it. If you have received this file from a source other than Adobe,
 * then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 */

package com.adobe.platform.operation.internal.util;

import java.io.StringReader;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;

import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PrivateKeyParser {

    private static final Logger LOGGER = LoggerFactory.getLogger(PrivateKeyParser.class);

    public static PrivateKey parsePrivateKey(String privateKey) {
        PrivateKey returnKey;

        try {
            KeySpec keySpec;
            KeyFactory factory = KeyFactory.getInstance("RSA");

            // PKCS8
            if (privateKey.contains("-----BEGIN PRIVATE KEY-----")) {
                //TODO DCSV-3760 handle windows encoding issues with pvt keys
                privateKey = privateKey.replace("-----BEGIN PRIVATE KEY-----\n", "");
                privateKey = privateKey.replace("-----END PRIVATE KEY-----", "");
                privateKey = privateKey.replaceAll("\\s", "");

                keySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));
            }
            // PKCS1
            else {
                PEMParser pemParser = new PEMParser(new StringReader(privateKey));
                Object object = pemParser.readObject();
                JcaPEMKeyConverter converter = new JcaPEMKeyConverter();

                PEMKeyPair ukp = (PEMKeyPair) object;
                KeyPair kp = converter.getKeyPair(ukp);

                keySpec = factory.getKeySpec(kp.getPrivate(), RSAPrivateCrtKeySpec.class);
            }

            returnKey = factory.generatePrivate(keySpec);
        } catch (Exception ex) {
            LOGGER.error("Unable to parse provided private key: {}", ex);
            throw new IllegalArgumentException("Private key file could not be parsed. Exception ", ex);
        }
        return returnKey;

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy