Example usage for java.security.cert Certificate getPublicKey

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

Introduction

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

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:com.ct855.util.HttpsClientUtil.java

private void print_https_cert(HttpsURLConnection con) {

    if (con != null) {

        try {/*from   www  .  j  a va 2 s .  c o  m*/

            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");

            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                System.out.println("Cert Type : " + cert.getType());
                System.out.println("Cert Hash Code : " + cert.hashCode());
                System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                System.out.println("\n");
            }

        } catch (SSLPeerUnverifiedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

boolean verifySigned(File keystore, Certificate agentCertificate) {
    try {/*from  w  w w .j  a v  a2  s  .  com*/
        KeyStore store = KeyStore.getInstance("JKS");
        FileInputStream inputStream = new FileInputStream(keystore);
        store.load(inputStream, PASSWORD_AS_CHAR_ARRAY);
        IOUtils.closeQuietly(inputStream);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));
        Certificate intermediateCertificate = intermediateEntry.getCertificate();
        agentCertificate.verify(intermediateCertificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:jenkins.bouncycastle.EncodignDecodingTest.java

@Test
public void testReadCertificatePEM() throws Exception {
    PEMEncodable pemEncCer = PEMEncodable.read(CERTIFICATE_PEM);
    PEMEncodable pemEncKey = PEMEncodable.read(CERTIFICATE_PUBLIC_KEY_PEM);

    Certificate certificate = pemEncCer.toCertificate();
    PublicKey publicKey = pemEncKey.toPublicKey();
    assertNotNull(certificate);// w ww .j  a  va 2s  .  c  om
    assertNotNull(publicKey);
    assertEquals(new String(Base64.encode(certificate.getPublicKey().getEncoded()), StandardCharsets.UTF_8),
            new String(Base64.encode(publicKey.getEncoded()), StandardCharsets.UTF_8));
}

From source file:jenkins.bouncycastle.EncodignDecodingTest.java

@Test
public void testReadCertificateWithPasswordPEM() throws Exception {
    PEMEncodable pemEncCer = PEMEncodable.read(CERTIFICATE_PW_PEM);
    PEMEncodable pemEncKey = PEMEncodable.read(CERTIFICATE_PUBLIC_KEY_PW_PEM);

    Certificate certificate = pemEncCer.toCertificate();
    PublicKey publicKey = pemEncKey.toPublicKey();
    assertNotNull(certificate);//from  w w w. jav  a 2 s  .c  o  m
    assertNotNull(publicKey);
    assertEquals(new String(Base64.encode(certificate.getPublicKey().getEncoded()), StandardCharsets.UTF_8),
            new String(Base64.encode(publicKey.getEncoded()), StandardCharsets.UTF_8));
}

From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator.java

@Override
public AuthenticationInfo authenticate(Request request, Response response) {
    String requestUri = request.getRequestURI();
    SignedJWT jwsObject;/*from w  w  w.j a  v a2 s  .c o  m*/
    String username;
    String tenantDomain;
    int tenantId;
    String issuer;

    AuthenticationInfo authenticationInfo = new AuthenticationInfo();
    if (requestUri == null || "".equals(requestUri)) {
        authenticationInfo.setStatus(Status.CONTINUE);
    }
    if (requestUri == null) {
        requestUri = "";
    }
    StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
    String context = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
    if (context == null || "".equals(context)) {
        authenticationInfo.setStatus(Status.CONTINUE);
    }

    try {
        String authorizationHeader = request.getHeader(JWT_ASSERTION_HEADER);
        jwsObject = SignedJWT.parse(authorizationHeader);
        username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME);
        tenantDomain = MultitenantUtils.getTenantDomain(username);
        tenantId = Integer.parseInt(jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_TENANT_ID));
        issuer = jwsObject.getJWTClaimsSet().getIssuer();
    } catch (ParseException e) {
        log.error("Error occurred while parsing JWT header.", e);
        authenticationInfo.setMessage("Error occurred while parsing JWT header");
        return authenticationInfo;
    }
    try {

        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
        IssuerAlias issuerAlias = new IssuerAlias(issuer, tenantDomain);
        PublicKey publicKey = publicKeyHolder.get(issuerAlias);
        if (publicKey == null) {
            loadTenantRegistry(tenantId);
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                String alias = properties == null ? null : properties.getProperty(issuer);
                if (alias != null && !alias.isEmpty()) {
                    ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
                    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                    String trustStorePath = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_LOCATION);
                    String trustStorePassword = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_PASSWORD);
                    keyStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
                    java.security.cert.Certificate certificate = keyStore.getCertificate(alias);
                    publicKey = certificate == null ? null : certificate.getPublicKey();
                } else {
                    authenticationInfo.setStatus(Status.FAILURE);
                    return authenticationInfo;
                }
            } else {
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                publicKey = keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain).getPublicKey();
            }
            if (publicKey != null) {
                issuerAlias = new IssuerAlias(tenantDomain);
                publicKeyHolder.put(issuerAlias, publicKey);
            }
        }
        //Get the filesystem keystore default primary certificate
        JWSVerifier verifier = null;
        if (publicKey != null) {
            verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
        }
        if (verifier != null && jwsObject.verify(verifier)) {
            username = MultitenantUtils.getTenantAwareUsername(username);
            UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService()
                    .getTenantUserRealm(tenantId).getUserStoreManager();
            if (userStore.isExistingUser(username)) {
                authenticationInfo.setTenantId(tenantId);
                authenticationInfo.setUsername(username);
                authenticationInfo.setTenantDomain(tenantDomain);
                authenticationInfo.setStatus(Status.CONTINUE);
            } else {
                authenticationInfo.setStatus(Status.FAILURE);
            }
        } else {
            authenticationInfo.setStatus(Status.FAILURE);
        }
    } catch (UserStoreException e) {
        log.error("Error occurred while obtaining the user.", e);
        authenticationInfo.setStatus(Status.FAILURE);
    } catch (Exception e) {
        log.error("Error occurred while verifying the JWT header.", e);
        authenticationInfo.setStatus(Status.FAILURE);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return authenticationInfo;
}

From source file:com.netflix.ice.login.saml.Saml.java

public LoginResponse processLogin(HttpServletRequest request) throws LoginMethodException {
    IceSession iceSession = new IceSession(request.getSession());
    iceSession.voidSession(); //a second login request voids anything previous
    logger.info("Saml::processLogin");
    LoginResponse lr = new LoginResponse();
    String assertion = (String) request.getParameter("SAMLResponse");
    if (assertion == null) {
        lr.redirectTo = config.singleSignOnUrl;
        return lr;
    }/*w  ww.  j  a  v a2 s  .c  o  m*/
    logger.trace("Received SAML Assertion: " + assertion);
    try {
        // 1.1 2.0 schemas
        Schema schema = SAMLSchemaBuilder.getSAML11Schema();

        //get parser pool manager
        BasicParserPool parserPoolManager = new BasicParserPool();
        parserPoolManager.setNamespaceAware(true);
        parserPoolManager.setIgnoreElementContentWhitespace(true);
        parserPoolManager.setSchema(schema);

        String data = new String(Base64.decode(assertion));
        logger.info("Decoded SAML Assertion: " + data);

        StringReader reader = new StringReader(data);
        Document document = parserPoolManager.parse(reader);
        Element documentRoot = document.getDocumentElement();

        QName qName = new QName(documentRoot.getNamespaceURI(), documentRoot.getLocalName(),
                documentRoot.getPrefix());

        //get an unmarshaller
        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(documentRoot);

        //unmarshall using the document root element
        XMLObject xmlObj = unmarshaller.unmarshall(documentRoot);
        Response response = (Response) xmlObj;
        for (Assertion myAssertion : response.getAssertions()) {
            if (!myAssertion.isSigned()) {
                logger.error("SAML Assertion not signed");
                throw new LoginMethodException("SAML Assertions must be signed by a trusted provider");
            }

            Signature assertionSignature = myAssertion.getSignature();
            SAMLSignatureProfileValidator profVal = new SAMLSignatureProfileValidator();

            logger.info("Validating SAML Assertion");
            // will throw a ValidationException 
            profVal.validate(assertionSignature);

            //Credential signCred = assertionSignature.getSigningCredential();
            boolean goodSignature = false;
            for (Certificate trustedCert : trustedSigningCerts) {
                BasicCredential cred = new BasicCredential();
                cred.setPublicKey(trustedCert.getPublicKey());
                SignatureValidator validator = new SignatureValidator(cred);
                try {
                    validator.validate(assertionSignature);
                } catch (ValidationException ve) {
                    /* Not a good key! */
                    logger.debug("Not signed by " + trustedCert.toString());
                    continue;
                }
                logger.info("Assertion trusted from " + trustedCert.toString());
                processAssertion(iceSession, myAssertion, lr);
                goodSignature = true;
                break;
            }

            if (goodSignature) {
                lr.loginSuccess = true;
            }

        }
    } catch (org.xml.sax.SAXException saxe) {
        logger.error(saxe.toString());
    } catch (org.opensaml.xml.parse.XMLParserException xmlpe) {
        logger.error(xmlpe.toString());
    } catch (org.opensaml.xml.io.UnmarshallingException uee) {
        logger.error(uee.toString());
    } catch (org.opensaml.xml.validation.ValidationException ve) {
        throw new LoginMethodException("SAML Assertion Signature was not usable: " + ve.toString());
    }
    return lr;
}

From source file:org.apache.juddi.v3.tck.TckBusiness.java

private boolean verifySignedJAXBObject(Object obj) {
    try {//from w  w w . ja  v  a2  s .  c o  m
        DOMResult domResult = new DOMResult();
        JAXB.marshal(obj, domResult);
        Document doc = ((Document) domResult.getNode());
        Element docElement = doc.getDocumentElement();

        KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
        URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
        ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS,
                new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
        PrivateKey privateKey = keyEntry.getPrivateKey();
        Certificate origCert = keyEntry.getCertificate();
        PublicKey validatingKey = origCert.getPublicKey();
        return TckSigningUtil.verifySignature(docElement, validatingKey);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.juddi.v3.tck.TckBusiness.java

private <T> T signJAXBObject(T jaxbObj) {
    DOMResult domResult = new DOMResult();
    JAXB.marshal(jaxbObj, domResult);
    Document doc = ((Document) domResult.getNode());
    Element docElement = doc.getDocumentElement();

    try {/*from w w  w.ja  v  a 2  s  .c o m*/
        KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE);
        URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE);
        ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS,
                new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray()));
        PrivateKey privateKey = keyEntry.getPrivateKey();
        Certificate origCert = keyEntry.getCertificate();
        PublicKey validatingKey = origCert.getPublicKey();
        TckSigningUtil.signDOM(docElement, privateKey, origCert);

        DOMSource domSource = new DOMSource(doc);
        T result = (T) JAXB.unmarshal(domSource, jaxbObj.getClass());
        return result;
    } catch (Exception e) {
        throw new RuntimeException("Signature failure due to: " + e.getMessage(), e);
    }
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

private void initKeyPair() throws SignerException {

    char[] passwordBytes = password.toCharArray();
    Key key;//  ww  w . j  a  v  a  2 s  . c  o m

    try {
        key = keyStore.getKey(alias, passwordBytes);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        throw new SignerException("Failed to retrieve key", ex);
    }

    if (key instanceof PrivateKey) {
        java.security.cert.Certificate cert;

        try {
            cert = keyStore.getCertificate(alias);
        } catch (KeyStoreException ex) {
            throw new SignerException("Failed to certificate with alias -->" + alias + "<---", ex);

        }

        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, (PrivateKey) key);
    }
}

From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

public PublicKey getPublicKey(String alias) {
    PublicKey publicKey = null;/*from   www.  jav  a  2  s  .c  o  m*/

    try {
        if (Util.isNullOrEmpty(alias)) {
            return null;
        }

        java.security.cert.Certificate certificate = keyStore.getCertificate(alias);
        if (certificate == null) {
            return null;
        }
        publicKey = certificate.getPublicKey();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }

    return publicKey;
}