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.qpark.eip.core.spring.security.https.EipX509TrustManager.java

/**
 * <pre>/*from w w w  .  jav  a 2  s  . c o m*/
 * http://docs.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#HostnameVerifier
 * </pre>
 * 
 * If the SSL/TLS implementation's standard hostname verification logic
 * fails, the implementation will call the verify method of the class which
 * implements this interface and is assigned to this HttpsURLConnection
 * instance. If the callback class can determine that the hostname is
 * acceptable given the parameters, it should report that the connection
 * should be allowed. An unacceptable response will cause the connection to
 * be terminated.
 * 
 * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
 *      javax.net.ssl.SSLSession)
 */
@Override
public boolean verify(final String hostname, final SSLSession session) {
    try {
        this.logger.debug("verify hostname={}", hostname);
        if (hostname != null && session != null && session.getPeerCertificateChain() != null
                && session.getPeerCertificateChain().length > 0 && session.getPeerCertificateChain()[0] != null
                && session.getPeerCertificateChain()[0].getPublicKey() != null) {
            Certificate cert = this.ks.getCertificate(hostname);
            if (cert != null && cert.getPublicKey() != null) {
                String ksPublicKey = cert.getPublicKey().toString();
                String serverPublicKey = session.getPeerCertificateChain()[0].getPublicKey().toString();
                if (ksPublicKey.equals(serverPublicKey)) {
                    return true;
                } else {
                    this.logger.debug("verify not matching public keys!");
                    this.logger.debug("verify public key from keystore={}", ksPublicKey);
                    this.logger.debug("verify public key from server  ={}", serverPublicKey);
                }
            } else {
                this.logger.debug("verify no cert({}) with PublicKey found.", cert);
            }
        } else {
            this.logger.debug("verify no hostname({}) or session with PeerCertificateChain and PublicKey.",
                    hostname);
        }
    } catch (KeyStoreException e) {
        this.logger.debug("verify {}", e.getMessage());
    } catch (SSLPeerUnverifiedException e) {
        this.logger.debug("verify {}", e.getMessage());
    }
    return false;
}

From source file:org.cesecore.keys.token.CachingKeyStoreWrapperTest.java

private void testUse(final CachingKeyStoreWrapper cachingKeyStoreWrapper, final String alias) throws Exception {
    final Key key = cachingKeyStoreWrapper.getKey(alias, null);
    final Certificate certificate = cachingKeyStoreWrapper.getCertificate(alias);
    // Verify that key pair from the key store is usable
    KeyTools.testKey((PrivateKey) key, certificate.getPublicKey(),
            cachingKeyStoreWrapper.getProvider().getName());
}

From source file:org.wso2.carbon.identity.user.store.ws.util.FileUtil.java

/**
 * Copy Public key to temporary location
 *
 * This method throws General Exception since current keyStoreManager.getDefaultPublicKey() throws Exception
 * @param publicKeyPath//w  ww  .j  a v  a  2s  .c o  m
 * @throws Exception
 */
public void copyPublicKey(String publicKeyPath) throws Exception {
    int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantID);
    DataOutputStream dos = null;
    KeyStore keyStore;
    PublicKey publicKey;

    try {
        File file = new File(publicKeyPath);
        FileOutputStream fos = new FileOutputStream(file);
        dos = new DataOutputStream(fos);

        if (tenantID != MultitenantConstants.SUPER_TENANT_ID) {
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            Certificate publicCert = keyStore.getCertificate(tenantDomain); //Default keystore alias = tenantDomain name
            publicKey = publicCert.getPublicKey();
        } else {
            publicKey = keyStoreManager.getDefaultPublicKey();

        }

        byte[] keyBytes = publicKey.getEncoded();
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encodeBuffer(keyBytes);
        dos.writeBytes(encoded);
        dos.flush();
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
            log.error("Error occurred while closing data stream", e);
        }
    }
}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

@Test
public void testGetPublicCertificates() throws Exception {
    Collection<PublicCertificate> certs = appIdentity.getPublicCertificatesForApp();
    Assert.assertTrue("No certificates returned.", !certs.isEmpty());

    for (PublicCertificate publicCert : certs) {
        Assert.assertTrue("No name for certificate.", !publicCert.getCertificateName().trim().isEmpty());

        String pemFormat = publicCert.getX509CertificateInPemFormat();
        String errMsg = "getX509CertificateInPemFormat():" + pemFormat;
        // TODO better check?
        Assert.assertTrue(errMsg, pemFormat.startsWith("-----BEGIN"));
        Assert.assertTrue(errMsg, pemFormat.contains("-----END"));

        InputStream stream = new ByteArrayInputStream(
                publicCert.getX509CertificateInPemFormat().getBytes("UTF-8"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(stream);

        PublicKey pk = cert.getPublicKey();
        Assert.assertNotNull(pk.getEncoded());
    }/*from w  w  w  . j a va2  s .  c  o  m*/
}

From source file:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java

private boolean validateCertificate(KeyStore keyStore, X509Certificate certificate, Date date)
        throws KeyStoreException {
    try {//from   w w w .ja  va2 s  .co  m
        certificate.checkValidity(date);
    } catch (Exception e) {
        return false;
    }
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        try {
            Certificate c = keyStore.getCertificate(aliases.nextElement());
            certificate.verify(c.getPublicKey());
            return true;
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception e) {
            logger.debug("", e);
        }
    }
    return false;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Get the RSA Public key from a X.509 certificate
        //from   ww w  .  jav a 2 s  .  c om
 * @param cert Certificate
 * @return PEM encoded public key
 */
public String getPublicKeyPem(Certificate cert) {
    PublicKey pubKey = cert.getPublicKey();
    return CryptoUtil.pemEncode(pubKey);
}

From source file:org.carewebframework.api.security.DigitalSignature.java

/**
 * @see org.carewebframework.api.security.IDigitalSignature#verify(java.lang.String,
 *      java.lang.String, java.lang.String, java.lang.String)
 *//*from w  ww . j  ava 2  s . c  o m*/
@Override
public boolean verify(String base64Signature, String content, String timestamp, String keyName)
        throws Exception {
    Certificate cert = keystore.getCertificate(keyName);

    if (cert == null) {
        log.error(("Missing public key certificate: " + keyName));
        return false;
    }

    return CipherUtil.verify(cert.getPublicKey(), base64Signature, content, timestamp, duration);
}

From source file:org.wso2.carbon.identity.oauth.endpoint.jwks.JwksEndpoint.java

@GET
@Path(value = "/jwks")
@Produces(MediaType.APPLICATION_JSON)//from   ww w  .j  a  v  a  2s . co m
public String jwks() {

    String tenantDomain = null;
    int tenantId = -1;
    Object tenantObj = IdentityUtil.threadLocalProperties.get().get(OAuthConstants.TENANT_NAME_FROM_CONTEXT);
    if (tenantObj != null) {
        tenantDomain = (String) tenantObj;
    }
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    RSAPublicKey publicKey = null;
    JSONObject jwksJson = new JSONObject();
    FileInputStream file = null;
    try {
        tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            file = new FileInputStream(
                    CarbonUtils.getServerConfiguration().getFirstProperty("Security.KeyStore.Location"));
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            String password = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.Password");
            keystore.load(file, password.toCharArray());
            String alias = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.KeyAlias");
            // Get certificate of public key
            Certificate cert = keystore.getCertificate(alias);
            // Get public key
            publicKey = (RSAPublicKey) cert.getPublicKey();
        } else {

            if (tenantId < 1 && tenantId != -1234) {
                String errorMesage = "The tenant is not existing";
                log.error(errorMesage);
                return errorMesage;
            }
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            KeyStore keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            // Get certificate of public key
            Certificate cert = keyStore.getCertificate(tenantDomain);
            publicKey = (RSAPublicKey) cert.getPublicKey();

        }
        String modulus = base64EncodeUint(publicKey.getModulus());
        String exponent = base64EncodeUint(publicKey.getPublicExponent());
        String kty = publicKey.getAlgorithm();
        JSONArray jwksKeyArray = new JSONArray();
        JSONObject jwksKeys = new JSONObject();
        jwksKeys.put("kty", kty);
        jwksKeys.put("alg", alg);
        jwksKeys.put("use", use);
        jwksKeys.put("kid", OAuth2Util.getThumbPrint(tenantDomain, tenantId));
        jwksKeys.put("n", modulus);
        jwksKeys.put("e", exponent);
        jwksKeyArray.put(jwksKeys);
        jwksJson.put("keys", jwksKeyArray);
    } catch (Exception e) {
        String errorMesage = "Error while generating the keyset for " + tenantDomain + " tenant domain.";
        log.error(errorMesage, e);
        return errorMesage;
    } finally {
        IdentityIOStreamUtils.closeInputStream(file);
    }

    return jwksJson.toString();
}

From source file:edu.ucsb.eucalyptus.keys.AbstractKeyStore.java

public KeyPair getKeyPair(String alias, String password) throws GeneralSecurityException {
    Certificate cert = this.keyStore.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) this.keyStore.getKey(alias, password.toCharArray());
    KeyPair kp = new KeyPair(cert.getPublicKey(), privateKey);
    return kp;//  w  ww . j  ava 2 s. c  o m
}

From source file:org.obiba.opal.core.security.OpalKeyStore.java

@Override
public PublicKey getPublicKey(Datasource datasource) throws NoSuchKeyException {
    try {//w w  w. j  a  v a  2  s  .  c o m
        Certificate cert = getKeyStore().getCertificate(datasource.getName());
        if (cert == null) {
            throw new NoSuchKeyException(datasource.getName(),
                    "No PublicKey for Datasource '" + datasource.getName() + "'");
        }
        return cert.getPublicKey();
    } catch (KeyStoreException e) {
        throw new MagmaCryptRuntimeException(e);
    }
}