Example usage for java.security.cert X509Certificate getPublicKey

List of usage examples for java.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:be.fedict.eid.idp.model.admin.AdminManagerBean.java

private String getId(X509Certificate certificate) {
    PublicKey publicKey = certificate.getPublicKey();
    return DigestUtils.shaHex(publicKey.getEncoded());
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the speechlet request./*from  w  w w  . j  ava  2s  .  com*/
 *
 * @param serializedSpeechletRequest
 *            speechlet request serialized as a string of JSON
 * @param baseEncoded64Signature
 *            the signature for provided in the request header
 * @param signingCertificateChainUrl
 *            the certificate chain URL provided in the request header
 */
public static void checkRequestSignature(final byte[] serializedSpeechletRequest,
        final String baseEncoded64Signature, final String signingCertificateChainUrl) {
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException("Missing signature/certificate for the provided speechlet request");
    }

    try {
        X509Certificate signingCertificate;
        if (CERTIFICATE_CACHE.containsKey(signingCertificateChainUrl)) {
            signingCertificate = CERTIFICATE_CACHE.get(signingCertificateChainUrl);
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(Sdk.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(serializedSpeechletRequest);
        if (!signature.verify(Base64.decodeBase64(baseEncoded64Signature.getBytes(Sdk.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided speechlet request");
        }
    } catch (CertificateException | SignatureException | NoSuchAlgorithmException | InvalidKeyException
            | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided speechlet request", ex);
    }
}

From source file:org.jasig.portal.security.provider.saml.PublicKeyVerifyingSSLSocketFactory.java

/**
 * This method makes a connection to the server by utilizing the base class
 * method, but it adds a validation of the server's public key if one was
 * supplied previously./*from  w w  w.jav a  2  s.  c  o m*/
 * 
 * @see org.apache.http.conn.ssl.SSLSocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams)
 */
@Override
public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {
    SSLSocket newSocket = (SSLSocket) super.connectSocket(sock, host, port, localAddress, localPort, params);

    if (publicKey != null) {
        logger.debug("Verifying SSL Socket to {}:{} against configured public key {}",
                new Object[] { host, port, publicKey });

        SSLSession session = newSocket.getSession();
        Certificate[] certs = session.getPeerCertificates();
        boolean matchFound = false;

        for (int i = 0; i < certs.length; i++) {
            X509Certificate x509 = (X509Certificate) certs[i];
            PublicKey certKey = x509.getPublicKey();

            if (certKey.equals(publicKey)) {
                logger.debug("Validated public key against server key: {}", certKey);
                matchFound = true;
                break;
            }
            logger.debug("server key doesn't match public key: {} ", certKey);
        }
        if (!matchFound) {
            newSocket.close();
            throw new IOException("Unable to verify the server's public key");
        }
    }
    return newSocket;
}

From source file:be.fedict.eid.applet.beta.admin.AdministratorServiceBean.java

public void validateCertificateChain(List<X509Certificate> certificateChain) throws SecurityException {
    /*/*from w  ww . j  a  v  a 2s .c  o  m*/
     * We're not using the entire PKI infrastructure here since we are in
     * control of the admin token ourselves.
     */
    X509Certificate adminCert = certificateChain.get(0);
    PublicKey adminPublicKey = adminCert.getPublicKey();
    String userId = getUserId(adminCert);
    if (isRegistered()) {
        LOG.debug("admin login");
    } else {
        LOG.debug("admin registration");
        register(adminPublicKey, userId);
    }

    String adminPassword = new String(Hex.encodeHex(adminPublicKey.getEncoded()));

    HttpServletRequest httpServletRequest;
    try {
        httpServletRequest = (HttpServletRequest) PolicyContext
                .getContext("javax.servlet.http.HttpServletRequest");
    } catch (PolicyContextException e) {
        throw new RuntimeException("JACC error: " + e.getMessage());
    }

    HttpSession httpSession = httpServletRequest.getSession();
    Credentials credentials = (Credentials) httpSession.getAttribute("org.jboss.seam.security.credentials");

    LOG.debug("username: " + userId);
    /*
     * Pass the eID credentials to the JBoss Seam security framework.
     */
    credentials.setUsername(userId);
    credentials.setPassword(adminPassword);
}

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 */// w ww  .  ja v  a 2 s .co  m
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (final ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:com.netflix.genie.security.oauth2.pingfederate.PingFederateJWTConfig.java

/**
 * The public key used to verify the signatures of JWT tokens.
 *
 * @param keyValue The string of the public key to use in either RSA or X.509 format
 * @return A public key object to use when validating JWT tokens
 * @throws IOException             On reading or closing byte array input stream
 * @throws JoseException           When trying to create the key using jose library
 * @throws InvalidKeySpecException When the cert has an invalid spec
 * @throws CertificateException    When trying to create a X.509 specification object
 *//*from  w w  w  .j  a  v a2 s.  co  m*/
@Bean
public PublicKey jwtPublicKey(
        @Value("${genie.security.oauth2.pingfederate.jwt.keyValue}") final String keyValue)
        throws IOException, JoseException, InvalidKeySpecException, CertificateException {
    final String certBegin = "-----BEGIN CERTIFICATE-----";
    final String rsaBegin = "-----BEGIN PUBLIC KEY-----";
    if (StringUtils.isEmpty(keyValue)) {
        // In future try a key resolver to pull the key from the server
        throw new IllegalArgumentException("No value set for security.oauth2.resource.jwt.keyValue");
    }

    if (keyValue.startsWith(certBegin)) {
        // X.509 cert
        try (ByteArrayInputStream bis = new ByteArrayInputStream(keyValue.getBytes("UTF-8"))) {
            final CertificateFactory fact = CertificateFactory.getInstance("X.509");
            final X509Certificate cer = (X509Certificate) fact.generateCertificate(bis);
            return cer.getPublicKey();
        }
    } else if (keyValue.startsWith(rsaBegin)) {
        // RSA Public Key
        return new RsaKeyUtil().fromPemEncoded(keyValue);
    } else {
        throw new IllegalArgumentException(
                "Only support X.509 pem certs or Public RSA Keys for security.oauth2.resource.jwt.keyValue");
    }
}

From source file:net.sf.keystore_explorer.gui.actions.ExportTrustedCertificatePublicKeyAction.java

private PublicKey getPublicKey(String alias) throws CryptoException {
    try {/*from  w  ww.j ava  2  s .  c  o  m*/
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStore keyStore = history.getCurrentState().getKeyStore();

        X509Certificate cert = X509CertUtil.convertCertificate(keyStore.getCertificate(alias));

        return cert.getPublicKey();
    } catch (KeyStoreException ex) {
        String message = MessageFormat
                .format(res.getString("ExportTrustedCertificatePublicKeyAction.NoAccessEntry.message"), alias);
        throw new CryptoException(message, ex);
    }
}

From source file:com.google.api.auth.DefaultJwksSupplier.java

private JsonWebKeySet extractX509Certificate(String json) {
    Map<String, String> certificates = parse(json, new TypeReference<Map<String, String>>() {
    });/*from w  ww  . ja v  a 2 s.  c om*/
    ImmutableList.Builder<JsonWebKey> jwkBuilder = ImmutableList.builder();
    X509Util x509Util = new X509Util();
    for (Entry<String, String> entry : certificates.entrySet()) {
        try {
            String cert = entry.getValue().trim().replace(X509_CERT_PREFIX, "").replace(X509_CERT_SUFFIX, "");
            X509Certificate x509Certificate = x509Util.fromBase64Der(cert);
            PublicKey publicKey = x509Certificate.getPublicKey();
            JsonWebKey jwk = toJsonWebKey(publicKey);
            jwk.setKeyId(entry.getKey());
            jwkBuilder.add(jwk);
        } catch (JoseException exception) {
            throw new UnauthenticatedException("Failed to parse public key", exception);
        }
    }
    return new JsonWebKeySet(jwkBuilder.build());
}

From source file:be.e_contract.mycarenet.etee.EncryptionToken.java

/**
 * RFC 3820// ww w  . j ava  2s .c  o m
 * 
 * @param certificate
 * @param issuer
 */
private void verifyProxyCertificate(X509Certificate certificate, X509Certificate issuer) {
    try {
        certificate.verify(issuer.getPublicKey());
        issuer.checkValidity();
    } catch (Exception e) {
        throw new SecurityException("not a proxy certificate");
    }
}