Example usage for java.security.cert X509Certificate getEncoded

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

Introduction

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

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Gets the OCSP status for the specified subject and issuer certificates.
 *
 * @param ocspStatusKey status key//from  w ww  .j  a va  2  s .  c om
 * @return ocsp status
 */
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
    final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
    final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();

    // initialize the default status
    final OcspStatus ocspStatus = new OcspStatus();
    ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
    ocspStatus.setValidationStatus(ValidationStatus.Unknown);

    try {
        // prepare the request
        final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
        final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build();
        final CertificateID certificateId = new CertificateID(
                calculatorProviderBuilder.get(CertificateID.HASH_SHA1),
                new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);

        // generate the request
        final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
        requestGenerator.addRequest(certificateId);

        // Create a nonce to avoid replay attack
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
                new DEROctetString(nonce.toByteArray()));
        requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));

        final OCSPReq ocspRequest = requestGenerator.build();

        // perform the request
        final ClientResponse response = getClientResponse(ocspRequest);

        // ensure the request was completed successfully
        if (ClientResponse.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
            return ocspStatus;
        }

        // interpret the response
        OCSPResp ocspResponse = new OCSPResp(response.getEntityInputStream());

        // verify the response status
        switch (ocspResponse.getStatus()) {
        case OCSPRespBuilder.SUCCESSFUL:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
            break;
        case OCSPRespBuilder.INTERNAL_ERROR:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
            break;
        case OCSPRespBuilder.MALFORMED_REQUEST:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
            break;
        case OCSPRespBuilder.SIG_REQUIRED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
            break;
        case OCSPRespBuilder.TRY_LATER:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
            break;
        case OCSPRespBuilder.UNAUTHORIZED:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
            break;
        default:
            ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
            break;
        }

        // only proceed if the response was successful
        if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            logger.warn(String.format("OCSP request was unsuccessful (%s).",
                    ocspStatus.getResponseStatus().toString()));
            return ocspStatus;
        }

        // ensure the appropriate response object
        final Object ocspResponseObject = ocspResponse.getResponseObject();
        if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
            logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
            return ocspStatus;
        }

        // get the response object
        final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        // attempt to locate the responder certificate
        final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
        if (responderCertificates.length != 1) {
            logger.warn(String.format("Unexpected number of OCSP responder certificates: %s",
                    responderCertificates.length));
            return ocspStatus;
        }

        // get the responder certificate
        final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(
                responderCertificates[0], issuerCertificate);
        if (trustedResponderCertificate != null) {
            // verify the response
            if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC")
                    .build(trustedResponderCertificate.getPublicKey()))) {
                ocspStatus.setVerificationStatus(VerificationStatus.Verified);
            } else {
                ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
            }
        } else {
            ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
        }

        // validate the response
        final SingleResp[] responses = basicOcspResponse.getResponses();
        for (SingleResp singleResponse : responses) {
            final CertificateID responseCertificateId = singleResponse.getCertID();
            final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();

            if (responseSerialNumber.equals(subjectSerialNumber)) {
                Object certStatus = singleResponse.getCertStatus();

                // interpret the certificate status
                if (CertificateStatus.GOOD == certStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Good);
                } else if (certStatus instanceof RevokedStatus) {
                    ocspStatus.setValidationStatus(ValidationStatus.Revoked);
                } else {
                    ocspStatus.setValidationStatus(ValidationStatus.Unknown);
                }
            }
        }
    } catch (final OCSPException | IOException | UniformInterfaceException | ClientHandlerException
            | OperatorCreationException e) {
        logger.error(e.getMessage(), e);
    } catch (CertificateException e) {
        e.printStackTrace();
    }

    return ocspStatus;
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore//  w ww.ja v a  2  s.c o  m
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(byte[] thumbprint, KeyStore store, MessageDigest sha)
        throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                try {
                    sha.update(x509cert.getEncoded());
                } catch (CertificateEncodingException ex) {
                    throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError",
                            null, ex);
                }
                byte[] data = sha.digest();

                if (Arrays.equals(data, thumbprint)) {
                    return certs;
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testPassiveLoginPkiFail()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    SecurityManager securityManager = mock(SecurityManager.class);
    when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test"));
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert/*from   w  ww . j  av  a 2s .c  o m*/
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);
    String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse=",
            "&RelayState");
    responseStr = URLDecoder.decode(responseStr, "UTF-8");
    responseStr = RestSecurity.inflateBase64(responseStr);

    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:AuthnFailed"));
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * This method prepares the wap-provisioning file by including relevant certificates etc
 *
 * @param binarySecurityToken     - CSR from device
 * @param wapProvisioningFilePath - File path of wap-provisioning file
 * @return - base64 encoded final wap-provisioning file as a String
 * @throws CertificateGenerationException
 * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions.WAPProvisioningException
 *//*from   w  w w. j a v  a  2s  .c o m*/
public String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {

    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;

    CertificateManagementServiceImpl impl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        rootCACertificate = (X509Certificate) impl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeToString(rootCACertificate.getEncoded());
    } catch (KeystoreException e) {
        String msg = "CA certificate cannot be generated";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    } catch (CertificateEncodingException e) {
        String msg = "CA certificate cannot be encoded.";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    }

    try {
        signedCertificate = impl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeToString(signedCertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        String msg = "Singed certificate cannot be encoded.";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    } catch (KeystoreException e) {
        String msg = "CA certificate cannot be generated";
        log.error(msg, e);
        throw new CertificateGenerationException(msg, e);
    }
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    String wapProvisioningString = null;
    try {
        builder = domFactory.newDocumentBuilder();

        Document document = builder.parse(wapProvisioningFilePath);
        NodeList wapParm = document.getElementsByTagName(PluginConstants.CertificateEnrolment.PARM);
        Node caCertificatePosition = wapParm.item(CA_CERTIFICATE_POSITION);

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha512Hex(rootCACertificate.getEncoded())).toUpperCase());
        //Adding encoded CA certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap rootCertAttributes = caCertificatePosition.getAttributes();
        Node rootCertNode = rootCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        rootCertEncodedString = rootCertEncodedString.replaceAll("\n", "");
        rootCertNode.setTextContent(rootCertEncodedString);

        if (log.isDebugEnabled()) {
            log.debug("Root certificate: " + rootCertEncodedString);
        }

        Node signedCertificatePosition = wapParm.item(SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha512Hex(signedCertificate.getEncoded())).toUpperCase());

        //Adding encoded signed certificate to wap-provisioning file after removing new line
        // characters.
        NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes();
        Node clientEncodedNode = clientCertAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        signedCertEncodedString = signedCertEncodedString.replaceAll("\n", "");

        clientEncodedNode.setTextContent(signedCertEncodedString);
        if (log.isDebugEnabled()) {
            log.debug("Signed certificate: " + signedCertEncodedString);
        }

        // Adding user name auth token to wap-provisioning xml
        Node userNameAuthPosition = wapParm.item(APPAUTH_USERNAME_POSITION);
        NamedNodeMap appServerAttribute = userNameAuthPosition.getAttributes();
        Node authNameNode = appServerAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        CacheEntry cacheEntry = (CacheEntry) DeviceUtil.getCacheEntry(headerBst);
        String userName = cacheEntry.getUsername();
        authNameNode.setTextContent(cacheEntry.getUsername());
        DeviceUtil.removeToken(headerBst);
        String password = DeviceUtil.generateRandomToken();
        Node passwordAuthPosition = wapParm.item(APPAUTH_PASSWORD_POSITION);
        NamedNodeMap appSrvPasswordAttribute = passwordAuthPosition.getAttributes();
        Node authPasswordNode = appSrvPasswordAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        authPasswordNode.setTextContent(password);
        String requestSecurityTokenResponse = new SyncmlCredentials().generateRST(userName, password);
        DeviceUtil.persistChallengeToken(requestSecurityTokenResponse, null, userName);

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm.item(POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        if (log.isDebugEnabled()) {
            log.debug("Username: " + userName + "Password: " + requestSecurityTokenResponse);
        }
        wapProvisioningString = convertDocumentToString(document);
    } catch (ParserConfigurationException e) {
        String msg = "Problem occurred in parsing wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (DeviceManagementException e) {
        String msg = "Error occurred in while getting CA and Root certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (CertificateEncodingException e) {
        String msg = "Error occurred in while encoding certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (UnsupportedEncodingException e) {
        String msg = "Error occurred in while encoding wap-provisioning file.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    } catch (SAXException e) {
        String msg = "Error occurred in while parsing wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (TransformerException e) {
        String msg = "Error occurred in while transforming wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (IOException e) {
        String msg = "Error occurred in while getting wap-provisioning.xml file.";
        log.error(msg, e);
        throw new WAPProvisioningException(msg, e);
    } catch (SyncmlMessageFormatException e) {
        String msg = "Error occurred in while getting CA and Root certificates.";
        log.error(msg, e);
        throw new WindowsDeviceEnrolmentException(msg, e);
    }
    return base64Encoder.encodeToString(wapProvisioningString.getBytes());
}

From source file:com.tremolosecurity.unison.google.u2f.U2FServerUnison.java

@Override
public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse,
        long currentTimeInMillis) throws U2FException {
    log.debug(">> processRegistrationResponse");

    String sessionId = registrationResponse.getSessionId();
    String clientDataBase64 = registrationResponse.getClientData();
    String rawRegistrationDataBase64 = registrationResponse.getRegistrationData();

    log.debug(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64);
    EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId);

    if (sessionData == null) {
        throw new U2FException("Unknown session_id");
    }//from  ww  w . ja va 2  s. com

    String appId = sessionData.getAppId();
    String clientData = new String(Base64.decodeBase64(clientDataBase64));
    byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64);
    if (log.isDebugEnabled()) {
        log.debug("-- Input --");
        log.debug("  sessionId: " + sessionId);
        log.debug("  challenge: " + Hex.encodeHexString(sessionData.getChallenge()));
        log.debug("  accountName: " + sessionData.getAccountName());
        log.debug("  clientData: " + clientData);
        log.debug("  rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData));
    }
    RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData);

    byte[] userPublicKey = registerResponse.getUserPublicKey();
    byte[] keyHandle = registerResponse.getKeyHandle();
    X509Certificate attestationCertificate = registerResponse.getAttestationCertificate();
    byte[] signature = registerResponse.getSignature();
    List<Transports> transports = null;
    try {
        transports = U2fAttestation.Parse(attestationCertificate).getTransports();
    } catch (CertificateParsingException e) {
        log.warn("Could not parse transports extension " + e.getMessage());
    }

    if (log.isDebugEnabled()) {
        log.debug("-- Parsed rawRegistrationResponse --");
        log.debug("  userPublicKey: " + Hex.encodeHexString(userPublicKey));
        log.debug("  keyHandle: " + Hex.encodeHexString(keyHandle));
        log.debug("  attestationCertificate: " + attestationCertificate.toString());
        log.debug("  transports: " + transports);
        try {
            log.debug("  attestationCertificate bytes: "
                    + Hex.encodeHexString(attestationCertificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw new U2FException("Cannot encode certificate", e);
        }
        log.debug("  signature: " + Hex.encodeHexString(signature));
    }

    byte[] appIdSha256 = crypto.computeSha256(appId.getBytes());
    byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes());
    byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle,
            userPublicKey);

    Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates();
    boolean found = false;
    for (X509Certificate trusted : trustedCertificates) {
        try {
            attestationCertificate.verify(trusted.getPublicKey());
            found = true;
        } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                | SignatureException e) {

        }
    }

    if (!found) {
        if (!this.requireAttestation) {
            log.warn("attestion cert is not trusted");
        } else {
            throw new U2FException("Attestation certificate is not trusted");
        }
    }

    verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData);
    if (log.isDebugEnabled()) {
        log.debug("Verifying signature of bytes " + Hex.encodeHexString(signedBytes));
    }

    if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) {
        throw new U2FException("Signature is invalid");
    }

    // The first time we create the SecurityKeyData, we set the counter value to 0.
    // We don't actually know what the counter value of the real device is - but it will
    // be something bigger (or equal) to 0, so subsequent signatures will check out ok.
    SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle,
            userPublicKey, attestationCertificate, /* initial counter value */ 0);
    dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData);

    if (log.isDebugEnabled()) {
        log.debug("<< processRegistrationResponse");
    }

    return securityKeyData;
}

From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {//ww  w.j  a  va 2 s .co  m
            X509Certificate caCert = (X509Certificate) sslKeyStore
                    .getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            LOG.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

/**
 * Gives back the JAXB CertID data structure.
 * /*w w w  .  j a va  2  s  . c o m*/
 * @param certificate
 * @param xadesObjectFactory
 * @param xmldsigObjectFactory
 * @param digestAlgorithm
 * @return
 */
private CertIDType getCertID(X509Certificate certificate) {

    CertIDType certId = xades13ObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = getDsObjectFactory().createX509IssuerSerialType();
    certId.setIssuerSerial(issuerSerial);
    String issuerName = certificate.getIssuerX500Principal().toString();
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());

    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, DigestAlgorithm.SHA1);
    certId.setCertDigest(certDigest);

    return certId;
}

From source file:iracing.webapi.IracingWebApi.java

private void installCerts() throws Exception {
    String host = "members.iracing.com";
    int port = 443;

    char[] password = CERT_STORE_PASSWORD.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char seperator = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }/*from w w  w.  j ava 2s .  c  o  m*/
    }
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(in, password);
    } catch (Exception e) {
    }
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    SSLSocket socket = null;
    try {
        socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        socket.startHandshake();
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (socket != null)
            socket.close();
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null)
        return;

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
    }

    for (int count = 0; count < chain.length; count++) {
        X509Certificate cert = chain[count];
        String alias = host + "-" + (count + 1);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream("jssecacerts");
        try {
            ks.store(out, password);
        } finally {
            out.close();
        }
    }
}

From source file:org.ejbca.core.model.era.RaMasterApiSessionBean.java

@Override
public byte[] createCertificate(AuthenticationToken authenticationToken,
        EndEntityInformation endEntityInformation) throws AuthorizationDeniedException, EjbcaException {
    if (endEntityInformation.getExtendedinformation() == null
            || endEntityInformation.getExtendedinformation().getCertificateRequest() == null) {
        throw new IllegalArgumentException(
                "CSR MUST be set under endEntityInformation.extendedInformation.certificateRequest");
    }/*from  www  . j  a  v  a 2s.c  o m*/

    PKCS10RequestMessage req = null;
    req = RequestMessageUtils
            .genPKCS10RequestMessage(endEntityInformation.getExtendedinformation().getCertificateRequest());
    req.setUsername(endEntityInformation.getUsername());
    req.setPassword(endEntityInformation.getPassword());
    try {
        ResponseMessage resp = signSessionLocal.createCertificate(authenticationToken, req,
                X509ResponseMessage.class, null);
        X509Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage(), X509Certificate.class);
        return cert.getEncoded();
    } catch (NoSuchEndEntityException | CustomCertificateSerialNumberException | CryptoTokenOfflineException
            | IllegalKeyException | CADoesntExistsException | SignRequestException
            | SignRequestSignatureException | IllegalNameException | CertificateCreateException
            | CertificateRevokeException | CertificateSerialNumberException | IllegalValidityException
            | CAOfflineException | InvalidAlgorithmException | CertificateExtensionException e) {
        throw new EjbcaException(e);
    } catch (CertificateParsingException | CertificateEncodingException e) {
        throw new IllegalStateException(
                "Internal error with creating X509Certificate from CertificateResponseMessage");
    }
}

From source file:org.signserver.server.log.SystemLoggingTest.java

@Test
public void test01LogCertInstalled() throws Exception {
    LOG.info(">test01LogCertInstalled");
    int linesBefore = readEntriesCount(auditLogFile);

    // Test with uploadSignerCertificate method (global scope)
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(new CertBuilder().build());
    workerSession.uploadSignerCertificate(signerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);

    List<String> lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);/*from ww  w. j a  va2  s.  c o  m*/
    String line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    String certLine = new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n");
    assertTrue("Contains certificate", line.contains(certLine));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Test removeProperty
    workerSession.removeWorkerProperty(signerId, "SIGNERCERT");
    lines = readEntries(auditLogFile, linesBefore + 2, 2);
    LOG.info(lines);

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains empty certificate", line.contains("CERTIFICATE: ;"));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    // Test with uploadSignerCertificate method (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.uploadSignerCertificate(signerId, cert.getEncoded(), GlobalConfiguration.SCOPE_NODE);

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: " + WorkerConfig.getNodeId()));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, WorkerConfig.getNodeId() + ".SIGNERCERT");

    // Test when setting the property manually (global scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "SIGNERCERT",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "SIGNERCERT");

    // Test when setting the property manually (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "NODE47.SIGNERCERT",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: NODE47"));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "NODE47.SIGNERCERT");
}