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.ejbca.ui.web.protocol.ScepServlet.java

private void service(String operation, String message, String remoteAddr, HttpServletResponse response,
        String pathInfo) throws IOException {

    String alias = getAlias(pathInfo);
    if (alias == null) {
        log.info("Wrong URL format. The SCEP URL should look like: "
                + "'http://HOST:PORT/ejbca/publicweb/apply/scep/ALIAS/pkiclien.exe' "
                + "but was 'http://HOST:PORT/ejbca/publicweb/apply/scep" + pathInfo + "'");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URL. No alias found.");
        return;/*  w w w  . j ava2s.  com*/
    }
    if (alias.length() > 32) {
        log.info("Unaccepted alias more than 32 characters.");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unaccepted alias more than 32 characters.");
        return;
    }
    ScepConfiguration scepConfig = (ScepConfiguration) this.globalConfigSession
            .getCachedConfiguration(ScepConfiguration.SCEP_CONFIGURATION_ID);
    if (!scepConfig.aliasExists(alias)) {
        String msg = "SCEP alias '" + alias + "' does not exist";
        log.info(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }

    try {
        if (operation == null) {
            String errMsg = intres.getLocalizedMessage("scep.errormissingparam", remoteAddr);
            log.error(errMsg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, errMsg);
            return;
        }

        final AuthenticationToken administrator = new AlwaysAllowLocalAuthenticationToken(
                new UsernamePrincipal("ScepServlet: " + remoteAddr));
        if (log.isDebugEnabled()) {
            log.debug("Got request '" + operation + "'");
            log.debug("Message: " + message);
        }
        String iMsg = intres.getLocalizedMessage("scep.receivedmsg", remoteAddr);
        log.info(iMsg);
        if (operation.equals("PKIOperation")) {
            if (message == null) {
                String errMsg = intres.getLocalizedMessage("scep.errormissingparam", remoteAddr);
                log.error(errMsg);
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, errMsg);
                return;
            }

            byte[] scepmsg = Base64.decode(message.getBytes());

            // Read the message end get the cert, this also checks authorization
            byte[] reply = scepCertRequest(administrator, scepmsg, alias, scepConfig);
            if (reply == null) {
                // This is probably a getCert message?
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request");
                return;
            }
            // Send back Scep response, PKCS#7 which contains the end entity's certificate (or failure)
            RequestHelper.sendBinaryBytes(reply, response, "application/x-pki-message", null);
            iMsg = intres.getLocalizedMessage("scep.sentresponsemsg", "PKIOperation", remoteAddr);
            log.info(iMsg);
        } else if (operation.equals("GetCACert")) {
            // The response has the content type tagged as application/x-x509-ca-cert. 
            // The body of the response is a DER encoded binary X.509 certificate. 
            // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509>

            // CA_IDENT is the message for this request to indicate which CA we are talking about
            final String caname = getCAName(message);
            if (log.isDebugEnabled()) {
                log.debug("Got SCEP cert request for CA '" + caname + "'");
            }
            Collection<Certificate> certs = null;
            CAInfo cainfo = casession.getCAInfoInternal(-1, caname, true);
            if (cainfo != null) {
                certs = cainfo.getCertificateChain();
            }
            if ((certs != null) && (certs.size() > 0)) {
                // CAs certificate is in the first position in the Collection
                X509Certificate cert = (X509Certificate) certs.iterator().next();
                if (log.isDebugEnabled()) {
                    log.debug("Sent certificate for CA '" + caname + "' to SCEP client.");
                }
                RequestHelper.sendNewX509CaCert(cert.getEncoded(), response);
                iMsg = intres.getLocalizedMessage("scep.sentresponsemsg", "GetCACert", remoteAddr);
                log.info(iMsg);
            } else {
                String errMsg = intres.getLocalizedMessage("scep.errorunknownca", "cert");
                log.error(errMsg);
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACertChain")) {
            // The response for GetCACertChain is a certificates-only PKCS#7 
            // SignedDatato carry the certificates to the end entity, with a 
            // Content-Type of application/x-x509-ca-ra-cert-chain.

            // CA_IDENT is the message for this request to indicate which CA we are talking about
            final String caname = getCAName(message);
            log.debug("Got SCEP pkcs7 request for CA '" + caname + "'");

            CAInfo cainfo = casession.getCAInfo(administrator, caname);
            byte[] pkcs7 = signsession.createPKCS7(administrator, cainfo.getCAId(), true);
            if ((pkcs7 != null) && (pkcs7.length > 0)) {
                if (log.isDebugEnabled()) {
                    log.debug("Sent PKCS7 for CA '" + caname + "' to SCEP client.");
                }
                RequestHelper.sendBinaryBytes(pkcs7, response, "application/x-x509-ca-ra-cert-chain", null);
                iMsg = intres.getLocalizedMessage("scep.sentresponsemsg", "GetCACertChain", remoteAddr);
                log.info(iMsg);
            } else {
                String errMsg = intres.getLocalizedMessage("scep.errorunknownca", "pkcs7");
                log.error(errMsg);
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACaps")) {
            // The response for GetCACaps is a <lf> separated list of capabilities

            /*
             "GetNextCACert"       CA Supports the GetNextCACert message.
             "POSTPKIOperation"    PKIOPeration messages may be sent via HTTP POST.
             "SHA-1"               CA Supports the SHA-1 hashing algorithm in 
                               signatures and fingerprints.  If present, the
                               client SHOULD use SHA-1.  If absent, the client
                               MUST use MD5 to maintain backward compatability.
             "Renewal"             Clients may use current certificate and key to
                               authenticate an enrollment request for a new
                               certificate.  
             */
            log.debug("Got SCEP GetCACaps request");
            response.setContentType("text/plain");
            response.getOutputStream().print("POSTPKIOperation\nRenewal\nSHA-1");
        } else {
            log.error("Invalid parameter '" + operation);
            // Send back proper Failure Response
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid parameter: " + HTMLTools.htmlescape(operation));
        }
    } catch (CADoesntExistsException cae) {
        String errMsg = intres.getLocalizedMessage("scep.errorunknownca", "cert");
        log.info(errMsg, cae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_NOT_FOUND, cae.getMessage());
    } catch (DecoderException de) {
        String errMsg = intres.getLocalizedMessage("scep.errorinvalidreq");
        log.info(errMsg, de);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, de.getMessage());
    } catch (AuthorizationDeniedException ae) {
        String errMsg = intres.getLocalizedMessage("scep.errorauth");
        log.info(errMsg, ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ae.getMessage());
    } catch (AuthLoginException ae) {
        String errMsg = intres.getLocalizedMessage("scep.errorauth");
        log.info(errMsg, ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ae.getMessage());
    } catch (AuthStatusException ae) {
        String errMsg = intres.getLocalizedMessage("scep.errorclientstatus");
        log.info(errMsg, ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ae.getMessage());
    } catch (CryptoTokenOfflineException ee) {
        String errMsg = intres.getLocalizedMessage("scep.errorgeneral");
        log.info(errMsg, ee);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ee.getMessage());
    } catch (NoSuchEndEntityException ee) {
        String errMsg = intres.getLocalizedMessage("scep.errorgeneral");
        errMsg += " Registering new EndEntities is only allowed in RA mode.";
        log.info(errMsg, ee);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ee.getMessage());
    } catch (IllegalKeyException e) {
        String errMsg = intres.getLocalizedMessage("scep.errorclientcertificaterenewal");
        errMsg += " Reusing the old keys was attempted, but this action is prohibited by configuration.";
        log.info(errMsg, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (SignatureException e) {
        String errMsg = intres.getLocalizedMessage("scep.errorclientcertificaterenewal");
        errMsg += " Request was not signed with previous certificate's public key.";
        log.info(errMsg, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (ClientCertificateRenewalException e) {
        String errMsg = intres.getLocalizedMessage("scep.errorclientcertificaterenewal");
        log.info(errMsg, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (Exception e) {
        String errMsg = intres.getLocalizedMessage("scep.errorgeneral");
        log.info(errMsg, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:org.openanzo.client.AnzoTrustManager.java

private void handleCertificateException(CertificateException ce, X509Certificate[] chain)
        throws CertificateException {
    if (trustAll) {
        return;/*from w w  w.  j  ava 2s .  c o  m*/
    }

    System.err.println(ce.getMessage());
    System.err.println("Certificate Information: \n");
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(chain[0].getNotBefore().getTime());
    System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " "
            + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR));
    //System.err.println("Entry type: " + chain[0].getType());
    System.err.println("Certificate chain length: " + chain.length);

    // print some information about the certificate(s) that failed
    int i = 1;
    for (X509Certificate cert : chain) {
        System.err.println("Certificate[" + i++ + "]:");
        System.err.println("Owner: " + cert.getSubjectX500Principal().toString());
        System.err.println("Issuer: " + cert.getIssuerX500Principal().toString());

        String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray()));
        System.err.println("Serial Number: " + serialNum);
        System.err.println(
                "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString());
        System.err.println("Certificate fingerprints: ");
        try {
            byte[] sig = cert.getEncoded();
            System.err.println("\tMD5: " + getHash(sig, "MD5"));
            System.err.println("\tSHA1: " + getHash(sig, "SHA1"));
        } catch (NoSuchAlgorithmException e) {
        }
        System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName());
        System.err.println("\tVersion: " + cert.getVersion());
        System.err.println("-----------------------------------------------------");
    }
    System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String line = "";
    try {
        line = in.readLine();
    } catch (IOException e) {
        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
        System.exit(1);
    }
    if (Character.toLowerCase(line.charAt(0)) == 'o') {
        return;
    } else if (Character.toLowerCase(line.charAt(0)) == 'a') {
        try {
            String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
            String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

            String truststorePath = System.getProperty("javax.net.ssl.trustStore");
            if (truststorePath == null) { // there is no trust store location in the user's settings.trig file
                String userHome = System.getProperty("user.home");
                if (userHome == null)
                    throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
                            "User's home directory is not specified");
                File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
                truststorePath = truststoreFile.getCanonicalPath();
                if (!truststoreFile.exists())
                    openTruststore(truststoreType, truststorePath, truststorePassword);
            } else {
                truststorePath = CommandContext.preprocessString(truststorePath);
                File truststoreFile = new File(truststorePath);

                if (!truststoreFile.exists()) {
                    System.err.println("Could not find the specified trust store file at:");
                    System.err.println(truststoreFile.getCanonicalPath());
                    System.err.println(
                            "The trust store file is used for permanently trusting server certificates that");
                    System.err.println("are not trusted by default.");
                    System.err.println(
                            "Would you like to create a new trust store file at the specified location?");
                    System.err.println("(y)es, (n)o");
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
                        System.exit(1);
                    }
                    if (Character.toLowerCase(line.charAt(0)) == 'y')
                        openTruststore(truststoreType, truststorePath, truststorePassword);
                    else
                        System.exit(1);
                }
            }

            KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword,
                    "imported_" + System.currentTimeMillis(), chain[0]);
        } catch (AnzoException ae) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Error importing certificate into truststore: ");
            CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace);
            System.exit(1);
        }
    } else {
        System.exit(1); // if the user does not want to trust the certificate then exit
    }
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.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.device.mgt.mobile.windows.api.common.exceptions.WAPProvisioningException
 *///  w w w  .  j a  v a 2  s .  co  m
private String prepareWapProvisioningXML(String binarySecurityToken, String wapProvisioningFilePath,
        String headerBst)
        throws CertificateGenerationException, WAPProvisioningException, WindowsDeviceEnrolmentException {
    String rootCertEncodedString;
    String signedCertEncodedString;
    X509Certificate signedCertificate;
    String provisioningXmlString;

    CertificateManagementServiceImpl certMgtServiceImpl = CertificateManagementServiceImpl.getInstance();
    Base64 base64Encoder = new Base64();
    try {
        rootCACertificate = (X509Certificate) certMgtServiceImpl.getCACertificate();
        rootCertEncodedString = base64Encoder.encodeAsString(rootCACertificate.getEncoded());

        signedCertificate = certMgtServiceImpl.getSignedCertificateFromCSR(binarySecurityToken);
        signedCertEncodedString = base64Encoder.encodeAsString(signedCertificate.getEncoded());

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        domFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

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

        //Adding SHA1 CA certificate finger print to wap-provisioning xml.
        caCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(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(PluginConstants.CertificateEnrolment.SIGNED_CERTIFICATE_POSITION);

        //Adding SHA1 signed certificate finger print to wap-provisioning xml.
        signedCertificatePosition.getParentNode().getAttributes()
                .getNamedItem(PluginConstants.CertificateEnrolment.TYPE).setTextContent(
                        String.valueOf(DigestUtils.sha1Hex(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 domainName to wap-provisioning xml.
        Node domainPosition = wapParm.item(PluginConstants.CertificateEnrolment.DOMAIN_POSITION);
        NamedNodeMap domainAttribute = domainPosition.getAttributes();
        Node domainNode = domainAttribute.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        domainNode.setTextContent(domain);

        //Adding Next provisioning service URL to wap-provisioning xml.
        Node syncmlServicePosition = wapParm
                .item(PluginConstants.CertificateEnrolment.SYNCML_PROVISIONING_ADDR_POSITION);
        NamedNodeMap syncmlServiceAttribute = syncmlServicePosition.getAttributes();
        Node syncmlServiceNode = syncmlServiceAttribute
                .getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        syncmlServiceNode.setTextContent(provisioningURL);

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

        // Get device polling frequency from the tenant Configurations.
        Node numberOfFirstRetries = wapParm
                .item(PluginConstants.CertificateEnrolment.POLLING_FREQUENCY_POSITION);
        NamedNodeMap pollingAttributes = numberOfFirstRetries.getAttributes();
        Node pollValue = pollingAttributes.getNamedItem(PluginConstants.CertificateEnrolment.VALUE);
        pollValue.setTextContent(pollingFrequency);
        provisioningXmlString = convertDocumentToString(document);

    } catch (ParserConfigurationException e) {
        throw new WAPProvisioningException("Problem occurred while creating configuration request", e);
    } catch (CertificateEncodingException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while encoding certificates.", e);
    } catch (SAXException e) {
        throw new WAPProvisioningException("Error occurred while parsing wap-provisioning.xml file.", e);
    } catch (TransformerException e) {
        throw new WAPProvisioningException("Error occurred while transforming wap-provisioning.xml file.", e);
    } catch (IOException e) {
        throw new WAPProvisioningException("Error occurred while getting wap-provisioning.xml file.", e);
    } catch (SyncmlMessageFormatException e) {
        throw new WindowsDeviceEnrolmentException("Error occurred while generating password hash value.", e);
    } catch (KeystoreException e) {
        throw new CertificateGenerationException("CA certificate cannot be generated.", e);
    }
    return base64Encoder.encodeAsString(provisioningXmlString.getBytes());
}

From source file:org.strongswan.android.logic.CharonVpnService.java

/**
 * Function called via JNI to generate a list of DER encoded CA certificates
 * as byte array.//from   w w w . j  a  v  a  2 s .c  o m
 *
 * @return a list of DER encoded CA certificates
 */
private byte[][] getTrustedCertificates() {
    ArrayList<byte[]> certs = new ArrayList<byte[]>();
    TrustedCertificateManager certman = TrustedCertificateManager.getInstance().load();
    try {
        String alias = this.mCurrentCertificateAlias;
        if (alias != null) {
            X509Certificate cert = certman.getCACertificateFromAlias(alias);
            if (cert == null) {
                return null;
            }
            certs.add(cert.getEncoded());
        } else {
            for (X509Certificate cert : certman.getAllCACertificates().values()) {
                certs.add(cert.getEncoded());
            }
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
    return certs.toArray(new byte[certs.size()][]);
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void exportSPMetaData(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException,
        CertificateEncodingException, MarshallingException {
    logger.info("Finding mechanism...");
    String mechanismName = loadOption(cmd, "mechanismName", options);
    MechanismType saml2Mech = loadMechanismType(mechanismName, tt);
    logger.info("...found");

    logger.info("Finding chain...");
    String chainName = loadOption(cmd, "chainName", options);

    AuthChainType act = loadChainType(chainName, tt);

    logger.info("Looking for correct mechanism on the chain...");
    AuthMechType currentMechanism = null;
    for (AuthMechType amt : act.getAuthMech()) {
        if (amt.getName().equalsIgnoreCase(mechanismName)) {
            currentMechanism = amt;/*from   w  ww. jav  a 2 s .  c om*/
            break;
        }
    }

    if (currentMechanism == null) {
        System.err.println("Unknown chain on mechanism");
        System.exit(1);
    }

    InitializationService.initialize();

    logger.info("loading url base");

    String urlBase = loadOption(cmd, "urlBase", options);

    String url = urlBase + saml2Mech.getUri();

    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);

    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptorImpl ed = (EntityDescriptorImpl) edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);

    SPSSODescriptorBuilder spb = new SPSSODescriptorBuilder();
    SPSSODescriptorImpl sp = (SPSSODescriptorImpl) spb.buildObject();
    ed.getRoleDescriptors().add(sp);

    HashMap<String, ParamType> params = new HashMap<String, ParamType>();
    for (ParamType pt : currentMechanism.getParams().getParam()) {
        params.put(pt.getName(), pt);
    }

    boolean assertionsSigned = params.get("assertionsSigned") != null
            && params.get("assertionsSigned").getValue().equalsIgnoreCase("true");
    sp.setWantAssertionsSigned(assertionsSigned);
    sp.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");

    SingleLogoutServiceBuilder slsb = new SingleLogoutServiceBuilder();
    SingleLogoutService sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sp.getSingleLogoutServices().add(sls);

    sls = slsb.buildObject();
    sls.setLocation(url);
    sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sp.getSingleLogoutServices().add(sls);

    AssertionConsumerServiceBuilder acsb = new AssertionConsumerServiceBuilder();
    AssertionConsumerService acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    acs.setIndex(0);
    acs.setIsDefault(true);
    sp.getAssertionConsumerServices().add(acs);

    acs = acsb.buildObject();
    acs.setLocation(url);
    acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    acs.setIndex(1);
    sp.getAssertionConsumerServices().add(acs);

    if (params.get("spSigKey") != null && !params.get("spSigKey").getValue().isEmpty()) {
        String alias = params.get("spSigKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);

        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spSigKey").getValue() + "' not found");
        }

        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);

    }

    if (params.get("spEncKey") != null && !params.get("spEncKey").getValue().isEmpty()) {
        String alias = params.get("spEncKey").getValue();
        X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias);

        if (certFromKS == null) {
            throw new Exception("Certificate '" + params.get("spEncKey").getValue() + "' not found");
        }

        PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
        KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(new String(Base64.encode(certFromKS.getEncoded())));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sp.getKeyDescriptors().add(kd);

    }

    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);

    String xml = net.shibboleth.utilities.java.support.xml.SerializeSupport.prettyPrintXML(assertionElement);

    logger.info(xml);
}

From source file:org.texai.x509.X509Utils.java

/** Creates the Texai root X.509 certificate keystore on the trusted development system.  This
 * keystore also includes a jar-signing certificate.
 *//*from w ww. java 2 s  .c  o  m*/
protected static synchronized void createTexaiRootKeyStore() {
    //Preconditions
    assert !isTrustedDevelopmentSystem() || X509Utils.isJCEUnlimitedStrengthPolicy();

    if (!isTrustedDevelopmentSystem()) {
        return;
    }
    final char[] keyStorePassword = getRootKeyStorePassword();
    assert keyStorePassword != null;
    final String filePath = System.getenv("SECURITY_DIR") + "/texai-keystore.jceks";
    final File serverKeyStoreFile = new File(filePath);
    if (serverKeyStoreFile.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating Texai root key pair");
        final KeyPair rootKeyPair = generateRSAKeyPair3072();
        LOGGER.info("creating Texai root X.509 certificate");
        final X509Certificate rootX509Certificate = generateRootX509Certificate(rootKeyPair);
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        final StringBuilder stringBuilder = new StringBuilder();
        for (final byte b : rootX509Certificate.getEncoded()) {
            stringBuilder.append(Byte.toString(b));
            stringBuilder.append(", ");
        }
        LOGGER.info("root certificate...\n" + rootX509Certificate);
        LOGGER.info("\nroot certificate bytes...\n" + stringBuilder.toString());
        LOGGER.info("creating Texai root X.509 certificate keystore");
        final KeyStore rootKeyStore = X509Utils.findOrCreateJceksKeyStore(filePath, keyStorePassword);
        rootKeyStore.setKeyEntry(ROOT_ALIAS, rootKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { rootX509Certificate });

        // create and store the jar-signer certificate
        LOGGER.info("creating jar-signer key pair");
        final KeyPair jarSignerKeyPair = generateRSAKeyPair2048();
        LOGGER.info("creating jar-signer X.509 certificate");
        final UUID jarSignerUUID = UUID.randomUUID();
        LOGGER.info("jar-signer UUID: " + jarSignerUUID);
        final X509Certificate jarSignerX509Certificate = generateX509Certificate(jarSignerKeyPair.getPublic(),
                rootKeyPair.getPrivate(), rootX509Certificate, jarSignerUUID, "RootCertificate"); // domainComponent
        LOGGER.info("jar-signer certificate:\n" + jarSignerX509Certificate);
        rootKeyStore.setKeyEntry(JAR_SIGNER_ALIAS, jarSignerKeyPair.getPrivate(), keyStorePassword,
                new Certificate[] { jarSignerX509Certificate, rootX509Certificate });
        rootKeyStore.store(new FileOutputStream(filePath), keyStorePassword);

        //Postconditions
        final PrivateKey privateKey = (PrivateKey) rootKeyStore.getKey(ROOT_ALIAS, keyStorePassword);
        assert privateKey != null;

    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException
            | UnrecoverableKeyException ex) {
        throw new TexaiException(ex);
    }
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test conversion to byte array and back.
 *//* ww w.j a v  a2s.c o m*/
@Test
public void testTestRoundtrip() throws GeneralSecurityException {
    populate(builder);
    X509Certificate expected = builder.build(keyPair.getPrivate());

    X509Certificate actual = certUtil.getCertificate(expected.getEncoded());
    assertEquals(actual.getSerialNumber(), expected.getSerialNumber());
    assertEquals(actual.getIssuerDN().toString(), expected.getIssuerDN().toString());
    assertEquals(actual.getSubjectDN().toString(), expected.getSubjectDN().toString());
    assertEquals(actual.getNotBefore(), expected.getNotBefore());
    assertEquals(actual.getNotAfter(), expected.getNotAfter());
}

From source file:ca.psiphon.PsiphonTunnel.java

private String setupTrustedCertificates(Context context) throws Exception {

    // Copy the Android system CA store to a local, private cert bundle file.
    ///*from  w  w  w  . j  a v a 2  s.  c o  m*/
    // This results in a file that can be passed to SSL_CTX_load_verify_locations
    // for use with OpenSSL modes in tunnel-core.
    // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
    //
    // TODO: to use the path mode of load_verify_locations would require emulating
    // the filename scheme used by c_rehash:
    // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
    // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs

    File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);

    final String errorMessage = "copy AndroidCAStore failed";
    try {

        File file = new File(directory, "certs.dat");

        // Pave a fresh copy on every run, which ensures we're not using old certs.
        // Note: assumes KeyStore doesn't return revoked certs.
        //
        // TODO: this takes under 1 second, but should we avoid repaving every time?
        file.delete();

        PrintStream output = null;
        try {
            output = new PrintStream(new FileOutputStream(file));

            KeyStore keyStore;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                keyStore = KeyStore.getInstance("AndroidCAStore");
                keyStore.load(null, null);
            } else {
                keyStore = KeyStore.getInstance("BKS");
                FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
                try {
                    keyStore.load(inputStream, "changeit".toCharArray());
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }

            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);

                output.println("-----BEGIN CERTIFICATE-----");
                String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
                // OpenSSL appears to reject the default linebreaking done by Base64.encode,
                // so we manually linebreak every 64 characters
                for (int i = 0; i < pemCert.length(); i += 64) {
                    output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
                }
                output.println("-----END CERTIFICATE-----");
            }

            mHostService.onDiagnosticMessage("prepared PsiphonCAStore");

            return file.getAbsolutePath();

        } finally {
            if (output != null) {
                output.close();
            }
        }

    } catch (KeyStoreException e) {
        throw new Exception(errorMessage, e);
    } catch (NoSuchAlgorithmException e) {
        throw new Exception(errorMessage, e);
    } catch (CertificateException e) {
        throw new Exception(errorMessage, e);
    } catch (IOException e) {
        throw new Exception(errorMessage, e);
    }
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test search criteria. There's no easy way to check the subject key id and
 * authority key id - we can get the extension's bytes but still need to
 * parse them./*from  w w w.  j a  va 2 s . c  om*/
 */
@Test
public void testTestSearchCriteria() throws GeneralSecurityException {

    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setBasicConstraints(true);
    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);
    X509Certificate cert = builder.build(keyPair.getPrivate());

    assertEquals(certUtil.getFingerprint(cert), toHex(DigestUtils.sha(cert.getEncoded())));
    assertEquals(certUtil.getCertificateHash(cert), rfc4387(cert.getEncoded()));
    assertEquals(certUtil.getIHash(cert), rfc4387(cert.getIssuerX500Principal().getEncoded()));
    assertEquals(certUtil.getSHash(cert), rfc4387(cert.getSubjectX500Principal().getEncoded()));
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

protected SAMLAssertion createHoKAssertion(SAMLTokenIssuerConfig config, Document doc, Crypto crypto,
        Date creationTime, Date expirationTime, RahasData data) throws TrustException {

    String keyType = data.getKeyType();
    if (StringUtils.isBlank(keyType)) {
        keyType = data.getRstElement().getNamespace().getNamespaceURI() + RahasConstants.KEY_TYPE_SYMM_KEY;
    }/*from w  w w. j  a v  a2 s . com*/

    if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
        Element encryptedKeyElem;
        SAMLNameIdentifier nameId = null;
        X509Certificate serviceCert = null;
        try {
            if (data.getPrincipal() != null) {
                String subjectNameId = data.getPrincipal().getName();
                nameId = new SAMLNameIdentifier(subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL);
            }

            // Get ApliesTo to figure out which service to issue the token
            // for
            serviceCert = getServiceCert(config, crypto, data.getAppliesToAddress());

            // Create the encrypted key
            WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();

            // Use thumbprint id
            encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);

            // SEt the encryption cert
            encrKeyBuilder.setUseThisCert(serviceCert);

            // set keysize
            int keysize = data.getKeysize();
            keysize = (keysize != -1) ? keysize : config.keySize;
            encrKeyBuilder.setKeySize(keysize);

            encrKeyBuilder
                    .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize));

            // Set key encryption algo
            encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);

            // Build
            encrKeyBuilder.prepare(doc, crypto);

            // Extract the base64 encoded secret value
            byte[] tempKey = new byte[keysize / 8];
            System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8);

            data.setEphmeralKey(tempKey);

            // Extract the Encryptedkey DOM element
            encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
        } catch (Exception e) {
            throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal",
                    new String[] { serviceCert.getSubjectDN().getName() }, e);
        }
        return this.createAttributeAssertion(doc, data, encryptedKeyElem, nameId, config, crypto, creationTime,
                expirationTime);
    } else {
        try {
            String subjectNameId = data.getPrincipal().getName();

            SAMLNameIdentifier nameId = new SAMLNameIdentifier(subjectNameId, null,
                    SAMLNameIdentifier.FORMAT_EMAIL);

            // Create the ds:KeyValue element with the ds:X509Data
            X509Certificate clientCert = data.getClientCert();

            if (clientCert == null) {
                X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName());
                clientCert = certs[0];
            }

            byte[] clientCertBytes = clientCert.getEncoded();

            String base64Cert = Base64.encode(clientCertBytes);

            Text base64CertText = doc.createTextNode(base64Cert);
            Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "X509Certificate");
            x509CertElem.appendChild(base64CertText);
            Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "X509Data");
            x509DataElem.appendChild(x509CertElem);

            return this.createAuthAssertion(doc, SAMLSubject.CONF_HOLDER_KEY, nameId, x509DataElem, config,
                    crypto, creationTime, expirationTime, data);
        } catch (Exception e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }
}