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:com.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

private boolean verifyUserCertSignature(X509Certificate x509Certificate, String signedInfo,
        byte[] signatureValue) {

    try {//from   w  w w  .  j av  a  2  s  .  c o  m
        PublicKey publicKey = x509Certificate.getPublicKey();
        Signature signature = Signature.getInstance("SHA256WithRSA");
        signature.initVerify(publicKey);
        signature.update(signedInfo.getBytes());
        return signature.verify(signatureValue);
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new InvalidCredentialsException("User certificate token signature validation failed.", e);
    }
}

From source file:KeystoreGeneratorTest.java

@Test
public void test() throws Exception {
    File dir = null;//from  w  w w .  j av  a 2  s .  c  o m
    FileInputStream fis = null;
    try {
        dir = Files.createTempDir();
        File keystoreFile = new File(dir, KEYSTORE_NAME);

        String config = GSON.toJson(ImmutableMap.builder().put("password", KEYSTORE_PASSWORD)
                .put("entries", ImmutableList.builder()
                        .add(ImmutableMap.builder().put("label", "rsatest1").put("algorithm", "SHA256WithRSA")
                                .put("keyAlgorithm", "RSA").put("rsaKeySize", "2048").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest1")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp192r1").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest2")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp256r1").build())
                        .build())
                .build());
        // generate
        KeyStore store = new KeystoreGenerator().generate(GSON.fromJson(config, KeystoreConfig.class));
        // write to disk
        try (FileOutputStream out = new FileOutputStream(keystoreFile)) {
            store.store(out, KEYSTORE_PASSWORD.toCharArray());
        }
        // load
        fis = new FileInputStream(keystoreFile);
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String al = aliases.nextElement();
            System.out.println("Label: [" + al + "]");
            X509Certificate cert = (X509Certificate) ks.getCertificate(al);
            System.out.println("  Algorithm: [" + cert.getSigAlgName() + "]");
            PublicKey key = cert.getPublicKey();
            if (key instanceof ECKey) {
                ECKey eckey = (ECKey) key;
                ECParameterSpec spec = eckey.getParams();
                System.out.println("  EC spec: [" + spec + "]");
            }
        }
    } finally {
        closeQuietly(fis);
        FileUtils.deleteDirectory(dir);
    }
}

From source file:gov.niem.ws.util.SecurityUtil.java

/**
 * Check that the certificate in the holder of key assertion matches
 * the passed certificate, sent via another channel (e.g. SSL client auth).
 * The certificate must be validated separately, before making this call.
 * @param assertion SAML holder of key assertion.
 * @param presentedCert certificate claimed to be presented in the HoK.
 * @return//from   w  ww . jav a 2 s  . c o m
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public static boolean confirmHolderOfKey(Document assertion, X509Certificate presentedCert)
        throws ParserConfigurationException, SAXException, IOException {
    Node keyInfoNode = null;
    try {
        keyInfoNode = (Node) subjectConfirmationKeyInfoPath.evaluate(assertion, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    if (keyInfoNode == null) {
        System.out.println("key info not found in subject confirmation");
        return false;
    }
    X509Certificate assertionCert = getCertificateFromKeyInfo(keyInfoNode);
    if (assertionCert != null) {
        return assertionCert.equals(presentedCert);
    }

    PublicKey publicKey = getPublicKeyFromKeyInfo(keyInfoNode);
    if (publicKey != null) {
        return publicKey.equals(presentedCert.getPublicKey());
    }

    return false;
}

From source file:com.axway.ebxml.KeyInfoWriter.java

/**
 * Builds <code>KeyInfo</code> instance given an array of <code>X509Certificate</code>. The
 * <code>KeyInfo</code> can be serialized and used within the Certificate element of an ebXML CPP or CPA
 * @param certs Array of certificates to include. The certificates in the array must be related in a certificate chain
 *      The first certificate in the array must be the end-entity certificate.
 * @return Initialized <code>KeyInfo</code> ready to be serialized
 * @throws IllegalArgumentException Null or Empty certificate list is passed as parameter
 * @throws KeyInfoWriterException Thrown when there is any other error encountered. The <code>KeyInfoWriterException</code>
 *  may wrap other exceptions caught within this method.
 *///from ww w.j  a  v a 2 s  .  c  o m
public KeyInfo buildKeyInfo(X509Certificate[] certs) throws KeyInfoWriterException {
    if (certs == null || certs.length == 0)
        throw new IllegalArgumentException("cert is null or empty");

    try {
        org.w3c.dom.Document doc = XmlUtil.buildDocument();

        KeyInfo keyInfo = new KeyInfo(doc);
        X509Data x509Data;
        for (X509Certificate cert : certs) {
            if (cert == certs[0]) // Only add KeyInfo for the first certificate in the chain (the end entity certificate)
                keyInfo.add(cert.getPublicKey());
            x509Data = buildX509Data(doc, cert); // Add X509Data elements for all the certificates in the chain
            keyInfo.add(x509Data);
        }

        doc.appendChild(keyInfo.getElement());
        return keyInfo;
    } catch (ParserConfigurationException e) {
        logger.error("Exception writing KeyInfo", e);
        throw new KeyInfoWriterException(e);
    } catch (XMLSecurityException e) {
        logger.error("Exception writing KeyInfo", e);
        throw new KeyInfoWriterException(e);
    }
}

From source file:be.fedict.trust.service.ocsp.OCSPResponderServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String contentType = request.getContentType();
    if (false == OCSP_REQUEST_CONTENT_TYPE.equals(contentType)) {
        LOG.error("incorrect content type: " + contentType);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;/*from  w ww  . j ava 2  s  . c  o  m*/
    }

    InputStream ocspRequestInputStream = request.getInputStream();
    OCSPReq ocspReq = new OCSPReq(ocspRequestInputStream);

    Req[] requestList = ocspReq.getRequestList();
    if (1 != requestList.length) {
        LOG.error("OCSP request list size not 1: " + requestList.length);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    Req ocspRequest = requestList[0];

    CertificateID certificateID = ocspRequest.getCertID();
    LOG.debug("certificate Id hash algo OID: " + certificateID.getHashAlgOID());
    if (false == CertificateID.HASH_SHA1.equals(certificateID.getHashAlgOID())) {
        LOG.debug("only supporting SHA1 hash algo");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    BigInteger serialNumber = certificateID.getSerialNumber();
    byte[] issuerNameHash = certificateID.getIssuerNameHash();
    byte[] issuerKeyHash = certificateID.getIssuerKeyHash();
    LOG.debug("serial number: " + serialNumber);
    LOG.debug("issuer name hash: " + new String(Hex.encodeHex(issuerNameHash)));
    LOG.debug("issuer key hash: " + new String(Hex.encodeHex(issuerKeyHash)));

    Date revocationDate = this.validationService.validate(serialNumber, issuerNameHash, issuerKeyHash);

    PrivateKeyEntry privateKeyEntry = this.validationService.getPrivateKeyEntry();
    if (null == privateKeyEntry) {
        LOG.debug("missing service identity");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PublicKey publicKey = certificate.getPublicKey();
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    try {
        BasicOCSPRespGenerator basicOCSPRespGenerator = new BasicOCSPRespGenerator(publicKey);
        CertificateStatus certificateStatus;
        if (null == revocationDate) {
            certificateStatus = CertificateStatus.GOOD;
        } else {
            certificateStatus = new RevokedStatus(revocationDate, CRLReason.unspecified);
        }
        basicOCSPRespGenerator.addResponse(certificateID, certificateStatus);
        BasicOCSPResp basicOCSPResp = basicOCSPRespGenerator.generate("SHA1WITHRSA", privateKey, null,
                new Date(), BouncyCastleProvider.PROVIDER_NAME);
        OCSPRespGenerator ocspRespGenerator = new OCSPRespGenerator();
        OCSPResp ocspResp = ocspRespGenerator.generate(OCSPRespGenerator.SUCCESSFUL, basicOCSPResp);
        response.setContentType("application/ocsp-response");
        response.getOutputStream().write(ocspResp.getEncoded());
    } catch (Exception e) {
        LOG.error("OCSP generator error: " + e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
}

From source file:com.securekey.samplerp.web.BriidgeController.java

@RequestMapping(value = "verifyJWT.json", method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody String verifyJWT(@RequestParam("jwt") String jwt) throws Exception {

    JWSObject jws = JWSObject.parse(jwt);
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(jws.getHeader().getX509CertURL().toString());
    request.addHeader("Accept", "text/plain");

    try {/*from   w  ww. j  a v a2s .  c  om*/
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {

            String pemFileContent = entity == null ? null : EntityUtils.toString(entity);
            PemReader pemReader = new PemReader(new StringReader(pemFileContent));
            byte[] pubK = pemReader.readPemObject().getContent();
            pemReader.close();
            Certificate serverCert = CertificateFactory.getInstance("X.509")
                    .generateCertificate(new ByteArrayInputStream(pubK));
            pemReader.close();

            if (serverCert instanceof X509Certificate) {

                X509Certificate cert = (X509Certificate) serverCert;
                PublicKey publicKey = cert.getPublicKey();
                if (publicKey instanceof RSAPublicKey) {
                    JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
                    if (jws.verify(verifier)) {
                        return "{\"status\":\"jwt_verified\"}";
                    } else {
                        return "{\"status\":\"jwt_verify_fail\"}";
                    }
                } else {
                    return "{\"status\":\"jwt_pub_key_not_rsa\"}";
                }

            } else {
                return "{\"status\":\"jwt_pem_not_cert\"}";
            }
        } else {
            return "{\"status\":\"jwt_pem_download_fail\"}";
        }
    } catch (IOException e) {
        return "{\"status\":\"jwt_pem_download_fail\"}";
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * @param cert/*from  w  w w . j  a v  a 2 s .com*/
 * @return true when the certificate is self signed
 */
public static boolean isCertificateSelfSigned(X509Certificate cert) {
    try {
        PublicKey publicKey = cert.getPublicKey();
        cert.verify(publicKey);
        return true;
    } catch (java.security.SignatureException sigEx) {
        LOG.info("ERROR : SignatureException {}", sigEx.getMessage());
        LOG.debug("ERROR : SignatureException {}", sigEx);
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        LOG.info("ERROR : InvalidKeyException {}", keyEx.getMessage());
        LOG.debug("ERROR : InvalidKeyException {}", keyEx);
        return false;
    } catch (CertificateException certExc) {
        LOG.info("ERROR : CertificateException {}", certExc.getMessage());
        LOG.debug("ERROR : CertificateException {}", certExc);
        return false;
    } catch (NoSuchAlgorithmException nsaExc) {
        LOG.info("ERROR : Bad algorithm: " + nsaExc.getMessage());
        LOG.debug("ERROR : Bad algorithm: " + nsaExc);
        return false;
    } catch (NoSuchProviderException nspExc) {
        LOG.info("ERROR : Bad provider: " + nspExc.getMessage());
        LOG.debug("ERROR : Bad provider: " + nspExc);
        return false;
    }
}

From source file:de.petendi.commons.crypto.HybridCrypto.java

public HybridCrypto addRecipient(String recipientIdentifier, X509Certificate certificate) {
    try {// w w w .  java2s  . c  o  m
        createSymmetricPassphrase();
        byte[] encryptedPassPhrase = asymmetricCrypto.encrypt(concatenated, certificate.getPublicKey());
        encryptedMessage.getRecipients().put(recipientIdentifier, encryptedPassPhrase);
        StringWriter pemWriter = new StringWriter();
        securityProviderConnector.writeCertificate(pemWriter, certificate);
        encryptedMessage.getCertificates().put(recipientIdentifier, pemWriter.toString());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return this;
}

From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 *//*from   ww  w  .j av  a 2s  .  c  o m*/
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();

        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");

        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(
                sslContextBuilder.build(), caHostname, certificates));

        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn,
                    domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(
                    TlsHelper.calculateHMac(token, request.getPublicKey()),
                    TlsHelper.pemEncodeJcaObject(request));

            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(
                    new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));

            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"),
                    httpPost)) {
                jsonResponseString = IOUtils.toString(
                        new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024),
                        StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }

        if (responseCode != Response.SC_OK) {
            throw new IOException(
                    RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }

        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }

        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper
                .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }

        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());

        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }

        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper
                .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton//from ww w  .j  a v a2 s . c  o m
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}