Example usage for org.bouncycastle.cert.jcajce JcaX509CertificateHolder getSubjectPublicKeyInfo

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateHolder getSubjectPublicKeyInfo

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CertificateHolder getSubjectPublicKeyInfo.

Prototype

public SubjectPublicKeyInfo getSubjectPublicKeyInfo() 

Source Link

Document

Return the SubjectPublicKeyInfo describing the public key this certificate is carrying.

Usage

From source file:com.nimbusds.jose.jwk.ECKey.java

License:Apache License

/**
 * Parses a public Elliptic Curve JWK from the specified X.509
 * certificate. Requires BouncyCastle.// w  ww .  j a va  2 s.c o m
 *
 * <p><strong>Important:</strong> The X.509 certificate is not
 * validated!
 *
 * <p>Sets the following JWK parameters:
 *
 * <ul>
 *     <li>The curve is obtained from the subject public key info
 *         algorithm parameters.
 *     <li>The JWK use inferred by {@link KeyUse#from}.
 *     <li>The JWK ID from the X.509 serial number (in base 10).
 *     <li>The JWK X.509 certificate chain (this certificate only).
 *     <li>The JWK X.509 certificate SHA-256 thumbprint.
 * </ul>
 *
 * @param cert The X.509 certificate. Must not be {@code null}.
 *
 * @return The public Elliptic Curve JWK.
 *
 * @throws JOSEException If parsing failed.
 */
public static ECKey parse(final X509Certificate cert) throws JOSEException {

    if (!(cert.getPublicKey() instanceof ECPublicKey)) {
        throw new JOSEException("The public key of the X.509 certificate is not EC");
    }

    ECPublicKey publicKey = (ECPublicKey) cert.getPublicKey();

    try {
        JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert);

        String oid = certHolder.getSubjectPublicKeyInfo().getAlgorithm().getParameters().toString();

        Curve crv = Curve.forOID(oid);

        if (crv == null) {
            throw new JOSEException("Couldn't determine EC JWK curve for OID " + oid);
        }

        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");

        return new ECKey.Builder(crv, publicKey).keyUse(KeyUse.from(cert))
                .keyID(cert.getSerialNumber().toString(10))
                .x509CertChain(Collections.singletonList(Base64.encode(cert.getEncoded())))
                .x509CertSHA256Thumbprint(Base64URL.encode(sha256.digest(cert.getEncoded()))).build();
    } catch (NoSuchAlgorithmException e) {
        throw new JOSEException("Couldn't encode x5t parameter: " + e.getMessage(), e);
    } catch (CertificateEncodingException e) {
        throw new JOSEException("Couldn't encode x5c parameter: " + e.getMessage(), e);
    }
}