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:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

public void setEnrollmentStatus() {
    KeyStore keyStore;/*from  www .ja v a  2s .com*/
    try {
        keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);

        this.isEnrolled = (keyStore.containsAlias(AgentConstants.DEVICE_CERT_ALIAS)
                && keyStore.containsAlias(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS)
                && keyStore.containsAlias(AgentConstants.SERVER_CA_CERT_ALIAS));

    } catch (KeyStoreException e) {
        log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '"
                + AgentConstants.DEVICE_KEYSTORE + "' with keystore type ["
                + AgentConstants.DEVICE_KEYSTORE_TYPE + "] to ensure enrollment status.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
        return;
    }
    try {
        if (this.isEnrolled) {
            this.SCEPCertificate = (X509Certificate) keyStore.getCertificate(AgentConstants.DEVICE_CERT_ALIAS);
            this.privateKey = (PrivateKey) keyStore.getKey(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS,
                    AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
            this.publicKey = SCEPCertificate.getPublicKey();

            X509Certificate serverCACert = (X509Certificate) keyStore
                    .getCertificate(AgentConstants.SERVER_CA_CERT_ALIAS);
            this.serverPublicKey = serverCACert.getPublicKey();
            log.info(AgentConstants.LOG_APPENDER
                    + "Device has already been enrolled. Hence, loaded certificate information from device"
                    + " trust-store.");
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '"
                + AgentConstants.DEVICE_KEYSTORE + "' to ensure enrollment status.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
        this.isEnrolled = false;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *///from w  ww  .ja v  a  2  s  .  c om
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate);
    storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate);

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER
                + "SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore ["
                + AgentConstants.DEVICE_KEYSTORE + "]");
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFireAlarmUtils.java

public static PublicKey getDevicePublicKey(String alias) throws VirtualFirealarmDeviceMgtPluginException {
    PublicKey clientPublicKey;//from  www.ja v a  2 s.c o  m
    try {
        CertificateManagementService certificateManagementService = VirtualFirealarmManagementDataHolder
                .getInstance().getCertificateManagementService();
        X509Certificate clientCertificate = (X509Certificate) certificateManagementService
                .getCertificateByAlias(alias);
        clientPublicKey = clientCertificate.getPublicKey();
    } catch (KeystoreException e) {
        String errorMsg;
        if (e.getMessage().contains("NULL_CERT")) {
            errorMsg = "The Device-View page might have been accessed prior to the device being started.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg);
            }
            throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
        } else {
            errorMsg = "An error occurred whilst trying to retrieve certificate for alias [" + alias
                    + "] with alias: [" + alias + "]";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg);
            }
            throw new VirtualFirealarmDeviceMgtPluginException(errorMsg, e);
        }
    }
    return clientPublicKey;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.scep.service.impl.util.VirtualFireAlarmServiceUtils.java

/**
 *
 * @param deviceId//  w  w  w  .  j  av a2s  .  c o m
 * @return
 * @throws VirtualFireAlarmException
 */
public static PublicKey getDevicePublicKey(String deviceId) throws VirtualFireAlarmException {
    PublicKey clientPublicKey;
    String alias = "";

    try {
        alias += deviceId.hashCode();

        CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils
                .getCertificateManagementService();
        X509Certificate clientCertificate = (X509Certificate) certificateManagementService
                .getCertificateByAlias(alias);
        clientPublicKey = clientCertificate.getPublicKey();

    } catch (VirtualFireAlarmException e) {
        String errorMsg = "Could not retrieve CertificateManagementService from the runtime.";
        if (log.isDebugEnabled()) {
            log.debug(errorMsg);
        }
        throw new VirtualFireAlarmException(errorMsg, e);
    } catch (KeystoreException e) {
        String errorMsg;
        if (e.getMessage().contains("NULL_CERT")) {
            errorMsg = "The Device-View page might have been accessed prior to the device being started.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg);
            }
            throw new VirtualFireAlarmException(errorMsg, e);
        } else {
            errorMsg = "An error occurred whilst trying to retrieve certificate for deviceId [" + deviceId
                    + "] with alias: [" + alias + "]";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg);
            }
            throw new VirtualFireAlarmException(errorMsg, e);
        }
    }
    return clientPublicKey;
}

From source file:org.wso2.carbon.identity.application.authenticator.passive.sts.manager.STSAgentKeyStoreCredential.java

private static void readX509Credentials(ExternalIdPConfig externalIdPConfig) throws PassiveSTSException {
    externalIdPConfig.getIdPName();//w w w  . jav a  2  s  .c om
    IdentityProvider identityProvider = externalIdPConfig.getIdentityProvider();
    X509Certificate x509Certificate = null;
    try {
        x509Certificate = (X509Certificate) IdentityApplicationManagementUtil
                .decodeCertificate(identityProvider.getCertificate());
        entityCertificate = x509Certificate;
        publicKey = x509Certificate.getPublicKey();
    } catch (CertificateException e) {
        log.error(e.getMessage(), e);
        throw new PassiveSTSException("Error occurred while decoding public certificate of Identity Provider "
                + identityProvider.getIdentityProviderName());
    }

}

From source file:org.wso2.carbon.identity.application.authenticator.samlsso.manager.X509CredentialImpl.java

/**
 * Instantiates X509Credential.//from   w w w.  j  a v a2  s .c o m
 * If the IDP cert passed is not null the instantiated credential object will hold the passed
 * cert and the public key of the cert.
 * Otherwise the object will hold the private key, public key and the cert for the respective
 * tenant domain.
 *
 * @param tenantDomain tenant domain
 * @param idpCert      certificate of the IDP
 * @throws SAMLSSOException
 */
public X509CredentialImpl(String tenantDomain, String idpCert) throws SAMLSSOException {

    X509Certificate cert;

    /**
     * If IDP cert is passed as a parameter set the cert to the IDP cert.
     * IDP cert should be passed when used with response validation.
     */
    if (idpCert != null && !idpCert.isEmpty()) {
        try {
            cert = (X509Certificate) IdentityApplicationManagementUtil.decodeCertificate(idpCert);
        } catch (CertificateException e) {
            throw new SAMLSSOException("Error retrieving the certificate for alias " + idpCert, e);
        }
    } else {
        int tenantId;

        try {
            tenantId = SAMLSSOAuthenticatorServiceComponent.getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
        } catch (UserStoreException e) {
            throw new SAMLSSOException(
                    "Exception occurred while retrieving Tenant ID from tenant domain " + tenantDomain, e);
        }

        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
        PrivateKey key;

        try {
            /**
             * Get the private key and the cert for the respective tenant domain.
             */
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                // derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                // derive JKS name
                String jksName = ksName + ".jks";
                key = (PrivateKey) keyStoreManager.getPrivateKey(jksName, tenantDomain);
                cert = (X509Certificate) keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain);
            } else {
                key = keyStoreManager.getDefaultPrivateKey();
                cert = keyStoreManager.getDefaultPrimaryCertificate();

            }
        } catch (Exception e) {
            throw new SAMLSSOException(
                    "Error retrieving private key and the certificate for tenant " + tenantDomain, e);
        }

        if (key == null) {
            throw new SAMLSSOException("Cannot find the private key for tenant " + tenantDomain);
        }

        this.privateKey = key;
    }

    if (cert == null) {
        throw new SAMLSSOException("Cannot find the certificate.");
    }

    entityCertificate = cert;
    publicKey = cert.getPublicKey();
}

From source file:org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil.java

/**
 * @param cert/* w  w  w.  j a v a  2s .c  o  m*/
 * @param formatter
 * @return
 * @throws CertificateEncodingException
 */
private static CertData fillCertData(X509Certificate cert, Format formatter)
        throws CertificateEncodingException {

    CertData certData = new CertData();
    certData.setSubjectDN(cert.getSubjectDN().getName());
    certData.setIssuerDN(cert.getIssuerDN().getName());
    certData.setSerialNumber(cert.getSerialNumber());
    certData.setVersion(cert.getVersion());
    certData.setNotAfter(formatter.format(cert.getNotAfter()));
    certData.setNotBefore(formatter.format(cert.getNotBefore()));
    certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded()));
    return certData;
}

From source file:org.wso2.carbon.identity.auth.saml2.common.X509CredentialImpl.java

public X509CredentialImpl(X509Certificate certificate) {

    entityCertificate = certificate;
    publicKey = certificate.getPublicKey();
}

From source file:org.wso2.carbon.identity.auth.saml2.common.X509CredentialImpl.java

public X509CredentialImpl(X509Certificate certificate, PrivateKey privateKey) {

    this.entityCertificate = certificate;
    this.publicKey = certificate.getPublicKey();
    this.privateKey = privateKey;
}

From source file:org.wso2.carbon.identity.oauth2.grant.jwt.JWTBearerGrantHandler.java

/**
 * Method to validate the signature of the JWT
 *
 * @param signedJWT signed JWT whose signature is to be verified
 * @param idp       Identity provider who issued the signed JWT
 * @return whether signature is valid, true if valid else false
 * @throws com.nimbusds.jose.JOSEException
 * @throws org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception
 *//*from   w  w  w .j av a2s . c  o m*/
private boolean validateSignature(SignedJWT signedJWT, IdentityProvider idp)
        throws JOSEException, IdentityOAuth2Exception {

    JWSVerifier verifier = null;
    ReadOnlyJWSHeader header = signedJWT.getHeader();
    X509Certificate x509Certificate = resolveSignerCertificate(header, idp);
    if (x509Certificate == null) {
        handleException("Unable to locate certificate for Identity Provider " + idp.getDisplayName() + "; JWT "
                + header.toString());
    }

    String alg = signedJWT.getHeader().getAlgorithm().getName();
    if (StringUtils.isEmpty(alg)) {
        handleException("Algorithm must not be null.");
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Signature Algorithm found in the JWT Header: " + alg);
        }
        if (alg.indexOf("RS") == 0) {
            RSAPublicKey publicKey = null;
            if (x509Certificate != null) {
                publicKey = (RSAPublicKey) x509Certificate.getPublicKey();
            } else {
                handleException("Unable to get certificate");
            }
            if (publicKey != null) {
                verifier = new RSASSAVerifier(publicKey);
            } else {
                handleException("Public key is null");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Signature Algorithm not supported yet : " + alg);
            }
        }
        if (verifier == null) {
            handleException("Could not create a signature verifier for algorithm type: " + alg);
        }
    }
    return verifier != null && signedJWT.verify(verifier);
}