Search in sources :

Example 11 with PemReader

use of org.bouncycastle.util.io.pem.PemReader in project platformlayer by platformlayer.

the class KeyParser method parse.

public Object parse(String s) {
    Object key = null;
    if (key == null) {
        if (s.contains(BEGIN_PRIVATE_KEY)) {
            String payload = s.substring(s.indexOf(BEGIN_PRIVATE_KEY) + BEGIN_PRIVATE_KEY.length());
            if (payload.contains(END_PRIVATE_KEY)) {
                payload = payload.substring(0, payload.indexOf(END_PRIVATE_KEY));
                key = tryParsePemFormat(payload);
            }
        }
    }
    if (key == null) {
        try {
            PemReader reader = new PemReader(new StringReader(s));
            PemObject pemObject = reader.readPemObject();
            reader.close();
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemObject.getContent());
            KeyFactory kf = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = kf.generatePrivate(keySpec);
            if (privateKey instanceof RSAPrivateCrtKey) {
                RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) privateKey;
                RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPrivateCrtKey.getModulus(), rsaPrivateCrtKey.getPublicExponent());
                PublicKey publicKey = kf.generatePublic(publicKeySpec);
                key = new KeyPair(publicKey, privateKey);
            } else {
                key = privateKey;
            }
        } catch (Exception e) {
            log.debug("Error reading pem data", e);
            return null;
        }
    }
    if (key == null) {
        try {
            // TODO: Check if looks like base64??
            byte[] fromBase64 = Base64.decode(s);
            key = parse(fromBase64);
        } catch (Exception e) {
            log.debug("Cannot decode as base64", e);
        }
    }
    return key;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) StringReader(java.io.StringReader) PemObject(org.bouncycastle.util.io.pem.PemObject) KeyFactory(java.security.KeyFactory)

Example 12 with PemReader

use of org.bouncycastle.util.io.pem.PemReader in project keywhiz by square.

the class ExpirationExtractor method expirationFromEncodedCertificateChain.

@Nullable
public static Instant expirationFromEncodedCertificateChain(byte[] content) {
    PemReader reader = new PemReader(new InputStreamReader(new ByteArrayInputStream(content), UTF_8));
    PemObject object;
    try {
        object = reader.readPemObject();
    } catch (IOException e) {
        // Should never occur (reading form byte array)
        throw Throwables.propagate(e);
    }
    Instant earliest = null;
    while (object != null) {
        if (object.getType().equals("CERTIFICATE")) {
            Instant expiry = expirationFromRawCertificate(object.getContent());
            if (earliest == null || expiry.isBefore(earliest)) {
                earliest = expiry;
            }
        }
        try {
            object = reader.readPemObject();
        } catch (IOException e) {
            // Should never occur (reading form byte array)
            throw Throwables.propagate(e);
        }
    }
    return earliest;
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) Instant(java.time.Instant) IOException(java.io.IOException) Nullable(javax.annotation.Nullable)

Example 13 with PemReader

use of org.bouncycastle.util.io.pem.PemReader in project sonarqube by SonarSource.

the class GithubAppSecurityImpl method readApplicationPrivateKey.

private static Algorithm readApplicationPrivateKey(long appId, String encodedPrivateKey) {
    byte[] decodedPrivateKey = encodedPrivateKey.getBytes(UTF_8);
    try (PemReader pemReader = new PemReader(new InputStreamReader(new ByteArrayInputStream(decodedPrivateKey)))) {
        Security.addProvider(new BouncyCastleProvider());
        PemObject pemObject = pemReader.readPemObject();
        if (pemObject == null) {
            throw new IllegalArgumentException("Failed to decode Github Application private key");
        }
        PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(pemObject.getContent());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec1);
        return Algorithm.RSA256(new RSAKeyProvider() {

            @Override
            public RSAPublicKey getPublicKeyById(String keyId) {
                throw new UnsupportedOperationException("getPublicKeyById not implemented");
            }

            @Override
            public RSAPrivateKey getPrivateKey() {
                return (RSAPrivateKey) privateKey;
            }

            @Override
            public String getPrivateKeyId() {
                return "github_app_" + appId;
            }
        });
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid Github Application private key", e);
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
Also used : RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) KeyFactory(java.security.KeyFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 14 with PemReader

use of org.bouncycastle.util.io.pem.PemReader in project web3sdk by FISCO-BCOS.

the class PEMManager method load.

public void load(InputStream in) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException, NoSuchProviderException {
    PemReader pemReader = new PemReader(new InputStreamReader(in));
    pem = pemReader.readPemObject();
    if (pem == null) {
        throw new IOException("The file does not represent a pem account.");
    }
    // logger.debug(" load pem, type: {}, header: {}", pem.getType(), pem.getHeaders());
    pemReader.close();
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException)

Example 15 with PemReader

use of org.bouncycastle.util.io.pem.PemReader in project neo4j by neo4j.

the class Certificates method loadPrivateKey.

public PrivateKey loadPrivateKey(File privateKeyFile) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
    try (PemReader r = new PemReader(new FileReader(privateKeyFile))) {
        PemObject pemObject = r.readPemObject();
        if (pemObject != null) {
            byte[] encodedKey = pemObject.getContent();
            KeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
            try {
                return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
            } catch (InvalidKeySpecException ignore) {
                try {
                    return KeyFactory.getInstance("DSA").generatePrivate(keySpec);
                } catch (InvalidKeySpecException ignore2) {
                    try {
                        return KeyFactory.getInstance("EC").generatePrivate(keySpec);
                    } catch (InvalidKeySpecException e) {
                        throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e);
                    }
                }
            }
        }
    }
    // Ok, failed to read as PEM file, try and read it as a raw binary private key
    try (DataInputStream in = new DataInputStream(new FileInputStream(privateKeyFile))) {
        byte[] keyBytes = new byte[(int) privateKeyFile.length()];
        in.readFully(keyBytes);
        KeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        return KeyFactory.getInstance(DEFAULT_ENCRYPTION).generatePrivate(keySpec);
    }
}
Also used : PemReader(org.bouncycastle.util.io.pem.PemReader) PemObject(org.bouncycastle.util.io.pem.PemObject) KeySpec(java.security.spec.KeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) FileReader(java.io.FileReader) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream)

Aggregations

PemReader (org.bouncycastle.util.io.pem.PemReader)31 StringReader (java.io.StringReader)20 PemObject (org.bouncycastle.util.io.pem.PemObject)20 IOException (java.io.IOException)13 ByteArrayInputStream (java.io.ByteArrayInputStream)10 X509Certificate (java.security.cert.X509Certificate)10 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)9 KeyFactory (java.security.KeyFactory)6 CertificateException (java.security.cert.CertificateException)6 CertificateFactory (java.security.cert.CertificateFactory)6 FileReader (java.io.FileReader)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 Certificate (java.security.cert.Certificate)5 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)5 ArrayList (java.util.ArrayList)5 InputStreamReader (java.io.InputStreamReader)4 PrivateKey (java.security.PrivateKey)4 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)4 PublicKey (java.security.PublicKey)3 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)3