RSA無視PEM文件格式(pkcs#1,pkcs#8,有無密碼 )直接讀取PEM文件爲PrivateKey,PublicKey

 RSA無視PEM文件格式(pkcs#1,pkcs#8,有無密碼 )直接讀取PEM文件爲PrivateKey,PublicKeyjava

兇殘暴力app

import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.pkcs.PKCSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * RSA無視PEM文件格式(pkcs#1,pkcs#8,有無密碼 )直接讀取PEM文件爲PrivateKey,PublicKey
 */
public class RSAUtil {
    private final static Logger logger = LoggerFactory.getLogger(RSAUtil.class);

    static {
        java.security.Security.addProvider(
                new org.bouncycastle.jce.provider.BouncyCastleProvider()
        );

    }

    public static PrivateKey privateKey(String pemString, String password) {
        try {
            return (PrivateKey) parseKey(pemString, password);
        } catch (IOException e) {
            logger.error("privateKey error", e);
            e.printStackTrace();
        }
        return null;
    }

    public static PrivateKey privateKey(String pemString) {
        try {
            return (PrivateKey) parseKey(pemString, null);
        } catch (IOException e) {
            logger.error("privateKey error", e);
        }
        return null;
    }

    public static PublicKey publicKey(String pemString) {
        try {
            return (PublicKey) parseKey(pemString, null);
        } catch (IOException e) {
            logger.error("publicKey error", e);
        }
        return null;
    }

    /**
     * Parses a Key instance from a PEM representation.
     * <p>
     * When the provided key is encrypted, the provided pass phrase is applied.
     *
     * @param pemString  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  Key instance (never null)
     */
    public static Key parseKey(String pemString, String passPhrase) throws IOException {

        if (passPhrase == null) {
            passPhrase = "";
        }
        try (StringReader reader = new StringReader(pemString); //
             PEMParser pemParser = new PEMParser(reader)) {

            final Object object = pemParser.readObject();
            final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);

            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 if (object instanceof SubjectPublicKeyInfo) {
                return converter.getPublicKey((SubjectPublicKeyInfo) object);
            } else {
                // Unencrypted key - no password needed
                kp = converter.getKeyPair((PEMKeyPair) object);
            }
            return kp.getPrivate();
        }
    }


}
相關文章
相關標籤/搜索