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.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

/**
 * Sets the input for this composite. //from  ww w  . j a va  2s  .c om
 *
 * @param certificateChain certificate chain input
 */
public void setInput(X509Certificate[] certificateChain) {
    X509Certificate certificate = certificateChain[0];

    X500Principal issuedToPrincipal = certificate.getSubjectX500Principal();
    Map<String, String> issuedToAttributes = getAttributeMap(issuedToPrincipal);
    issuedToCN.setText(issuedToAttributes.get("CN")); //$NON-NLS-1$
    issuedToO.setText(issuedToAttributes.get("O")); //$NON-NLS-1$
    issuedToOU.setText(issuedToAttributes.get("OU")); //$NON-NLS-1$
    serialNumber.setText(certificate.getSerialNumber().toString(16));

    X500Principal issuedFromPrincipal = certificate.getIssuerX500Principal();
    Map<String, String> issuedFromAttributes = getAttributeMap(issuedFromPrincipal);
    issuedByCN.setText(issuedFromAttributes.get("CN")); //$NON-NLS-1$
    issuedByO.setText(issuedFromAttributes.get("O")); //$NON-NLS-1$
    issuedByOU.setText(issuedFromAttributes.get("OU")); //$NON-NLS-1$

    issuesOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotBefore()));
    expiresOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotAfter()));

    byte[] encoded2 = null;

    try {
        encoded2 = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
    }

    byte[] md5 = DigestUtils.md5(encoded2);
    String md5HexString = getHexString(md5);
    fingerprintMD5.setText(md5HexString);
    byte[] sha = DigestUtils.sha(encoded2);
    String shaHexString = getHexString(sha);
    fingerprintSHA1.setText(shaHexString);

    // Details: certificate chain
    CertificateChainItem parentItem = null;
    CertificateChainItem certificateItem = null;

    for (X509Certificate cert : certificateChain) {
        CertificateChainItem item = new CertificateChainItem(cert);

        if (parentItem != null) {
            item.child = parentItem;
            parentItem.parent = item;
        }

        if (certificateItem == null) {
            certificateItem = item;
        }

        parentItem = item;
    }

    hierarchyTreeViewer.setInput(new CertificateChainItem[] { parentItem });
    hierarchyTreeViewer.expandAll();
    hierarchyTreeViewer.setSelection(new StructuredSelection(certificateItem), true);

    // Details: 
    certificateTree.removeAll();
    populateCertificateTree();
    valueText.setText(StringUtils.EMPTY);
}

From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java

private Map<String, Attribute> getAttributes(String userId, Identity identity, Address address,
        X509Certificate authnCertificate, byte[] photo) {

    Map<String, Attribute> attributes = new HashMap<String, Attribute>();

    String givenName;/*  w  ww. j  a  v  a2  s  . com*/
    String surName;
    if (null != identity) {
        givenName = identity.getFirstName();
        surName = identity.getName();
    } else {
        givenName = getGivenName(authnCertificate);
        surName = getSurName(authnCertificate);
    }

    attributes.put(DefaultAttribute.LAST_NAME.getUri(), getAttribute(DefaultAttribute.LAST_NAME, surName));

    attributes.put(DefaultAttribute.FIRST_NAME.getUri(), getAttribute(DefaultAttribute.FIRST_NAME, givenName));

    attributes.put(DefaultAttribute.NAME.getUri(),
            getAttribute(DefaultAttribute.NAME, givenName + " " + surName));

    attributes.put(DefaultAttribute.IDENTIFIER.getUri(), getAttribute(DefaultAttribute.IDENTIFIER, userId));

    if (null != authnCertificate) {
        /*
         * authnCertificate can be null for recent eID cards that can have
         * no certificates embedded at all.
         */
        try {
            attributes.put(DefaultAttribute.AUTHN_CERT.getUri(),
                    getAttribute(DefaultAttribute.AUTHN_CERT, authnCertificate.getEncoded()));
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }
    }

    if (null != address) {

        attributes.put(DefaultAttribute.ADDRESS.getUri(),
                getAttribute(DefaultAttribute.ADDRESS, address.getStreetAndNumber()));
        attributes.put(DefaultAttribute.LOCALITY.getUri(),
                getAttribute(DefaultAttribute.LOCALITY, address.getMunicipality()));
        attributes.put(DefaultAttribute.POSTAL_CODE.getUri(),
                getAttribute(DefaultAttribute.POSTAL_CODE, address.getZip()));
    }

    if (null != identity) {

        attributes.put(DefaultAttribute.GENDER.getUri(),
                getAttribute(DefaultAttribute.GENDER, IdpUtil.getGenderValue(identity)));
        attributes.put(DefaultAttribute.DATE_OF_BIRTH.getUri(),
                getAttribute(DefaultAttribute.DATE_OF_BIRTH, identity.getDateOfBirth()));
        attributes.put(DefaultAttribute.NATIONALITY.getUri(),
                getAttribute(DefaultAttribute.NATIONALITY, identity.getNationality()));
        attributes.put(DefaultAttribute.PLACE_OF_BIRTH.getUri(),
                getAttribute(DefaultAttribute.PLACE_OF_BIRTH, identity.getPlaceOfBirth()));

        attributes.put(DefaultAttribute.CARD_NUMBER.getUri(),
                getAttribute(DefaultAttribute.CARD_NUMBER, identity.cardNumber));

        attributes.put(DefaultAttribute.CARD_VALIDITY_BEGIN.getUri(),
                getAttribute(DefaultAttribute.CARD_VALIDITY_BEGIN, identity.cardValidityDateBegin));

        attributes.put(DefaultAttribute.CARD_VALIDITY_END.getUri(),
                getAttribute(DefaultAttribute.CARD_VALIDITY_END, identity.cardValidityDateEnd));
    }

    if (null != photo) {

        attributes.put(DefaultAttribute.PHOTO.getUri(), getAttribute(DefaultAttribute.PHOTO, photo));
    }

    return attributes;
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void addCertificate(X509Certificate cert, Element signedCertificate, Document doc, int index,
        Input input) throws CertificateEncodingException, NoSuchAlgorithmException, XmlSignatureException {
    Element elCert = createElement("Cert", doc, input);
    signedCertificate.appendChild(elCert);

    String algorithm = getMessageDigestAlgorithm(getDigestAlgorithmForSigningCertificate(),
            "The digest algorithm '%s' for the signing certificate is invalid");
    String digest = calculateDigest(algorithm, cert.getEncoded());
    Element certDigest = createElement("CertDigest", doc, input);
    elCert.appendChild(certDigest);//from w w w .j  ava 2s.co  m
    Element digestMethod = createDigSigElement("DigestMethod", doc, input.getPrefixForXmlSignatureNamespace());
    certDigest.appendChild(digestMethod);
    setAttribute(digestMethod, "Algorithm", getDigestAlgorithmForSigningCertificate());
    Element digestValue = createDigSigElement("DigestValue", doc, input.getPrefixForXmlSignatureNamespace());
    certDigest.appendChild(digestValue);
    digestValue.setTextContent(digest);

    Element issuerSerial = createElement("IssuerSerial", doc, input);
    elCert.appendChild(issuerSerial);
    Element x509IssuerName = createDigSigElement("X509IssuerName", doc,
            input.getPrefixForXmlSignatureNamespace());
    issuerSerial.appendChild(x509IssuerName);
    x509IssuerName.setTextContent(cert.getIssuerX500Principal().getName(X500Principal.RFC2253));
    Element x509SerialNumber = createDigSigElement("X509SerialNumber", doc,
            input.getPrefixForXmlSignatureNamespace());
    issuerSerial.appendChild(x509SerialNumber);
    x509SerialNumber.setTextContent(cert.getSerialNumber().toString());

    List<String> uris = getSigningCertificateURIs();
    if (!uris.isEmpty() && uris.size() > index) {
        String uri = uris.get(index);
        if (uri != null && !uri.isEmpty()) {
            setAttribute(elCert, "URI", uri);
        }
    }
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * Saves and accepts a x509 certificate.
 * @param cert/*from  w w  w  . j a v  a 2  s  . c o m*/
 */
private void saveAndAcceptCert(X509Certificate cert) {
    String certificate = null;
    try {
        certificate = Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
    connection.setSshHostKey(certificate);
    connection.save(database.getWritableDatabase());
    database.close();
    // Indicate the certificate was accepted.
    certificateAccepted = true;
    synchronized (RemoteCanvas.this) {
        RemoteCanvas.this.notifyAll();
    }
}

From source file:ru.codeinside.gses.webui.supervisor.SupervisorWorkplace.java

private void buildListPanel() {
    controlledTasksTable.setHeight("255px");
    controlledTasksTable.setWidth("100%");
    controlledTasksTable.setImmediate(true);
    controlledTasksTable.setSelectable(true);
    controlledTasksTable.setSortDisabled(true);
    controlledTasksTable.addContainerProperty("id", Component.class, null);
    controlledTasksTable.addContainerProperty("dateCreated", String.class, null);
    controlledTasksTable.addContainerProperty("task", String.class, null);
    controlledTasksTable.addContainerProperty("procedure", String.class, null);
    controlledTasksTable.addContainerProperty("declarant", String.class, null);
    controlledTasksTable.addContainerProperty("version", String.class, null);
    controlledTasksTable.addContainerProperty("status", String.class, null);
    controlledTasksTable.addContainerProperty("employee", String.class, null);
    controlledTasksTable.addContainerProperty("priority", String.class, null);
    controlledTasksTable.addContainerProperty("bidDays", String.class, null);
    controlledTasksTable.addContainerProperty("taskDays", String.class, null);
    controlledTasksTable.setVisibleColumns(new Object[] { "id", "dateCreated", "task", "procedure", "declarant",
            "version", "status", "employee", "bidDays", "taskDays" });
    controlledTasksTable.setColumnHeaders(new String[] { "?", "  ?",
            "", "", "?", "??", "?",
            "?", "..", ".?." });
    controlledTasksTable.setColumnExpandRatio("id", 0.05f);
    controlledTasksTable.setColumnExpandRatio("dateCreated", 0.15f);
    controlledTasksTable.setColumnExpandRatio("task", 0.2f);
    controlledTasksTable.setColumnExpandRatio("procedure", 0.25f);
    controlledTasksTable.setColumnExpandRatio("declarant", 0.1f);
    controlledTasksTable.setColumnExpandRatio("version", 0.05f);
    controlledTasksTable.setColumnExpandRatio("status", 0.1f);
    controlledTasksTable.setColumnExpandRatio("employee", 0.1f);
    controlledTasksTable.setCellStyleGenerator(new TaskStylist(controlledTasksTable));
    listPanel.addComponent(controlledTasksTable);
    final Button assignButton = new Button("? ??");
    controlledTasksTable.addListener(new Property.ValueChangeListener() {
        @Override//from  w ww .ja v  a2s  . c om
        public void valueChange(Property.ValueChangeEvent event) {
            Table table = (Table) event.getProperty();
            Item item = table.getItem(table.getValue());

            if (item != null && item.getItemProperty("id") != null) {
                final String taskId = item.getItemProperty("taskId").getValue().toString();
                final Component procedureHistoryPanel = new ProcedureHistoryPanel(taskId);
                procedureHistoryPanel.addListener(new Listener() {
                    @Override
                    public void componentEvent(Event event) {
                        HistoricTaskInstance historicTaskInstance = ((ProcedureHistoryPanel.HistoryStepClickedEvent) event)
                                .getHistoricTaskInstance();
                        Date endDateTime = historicTaskInstance.getEndTime();
                        if (endDateTime == null) {
                            taskIdToAssign = findTaskByHistoricInstance(historicTaskInstance);
                            if (taskIdToAssign == null) {
                                alreadyGone();
                                return;
                            }
                            assignButton.setVisible(true);
                        } else {
                            assignButton.setVisible(false);
                        }
                    }
                });
                ((VerticalLayout) item1).removeAllComponents();
                Task task = Flash.flash().getProcessEngine().getTaskService().createTaskQuery().taskId(taskId)
                        .singleResult();
                Bid bid = Flash.flash().getAdminService().getBidByTask(taskId);
                String executionId = task.getExecutionId();
                final ProcessDefinition def = ActivitiBean.get()
                        .getProcessDefinition(task.getProcessDefinitionId(), Flash.login());
                final ShowDiagramComponentParameterObject param = new ShowDiagramComponentParameterObject();
                param.changer = bidChanger;
                param.processDefinitionId = def.getId();
                param.executionId = executionId;
                param.height = "300px";
                param.width = null;
                param.windowHeader = bid == null ? ""
                        : bid.getProcedure().getName() + " v. " + bid.getVersion();
                Button showDiagram = new Button("");
                showDiagram.addListener(new Button.ClickListener() {
                    @Override
                    public void buttonClick(Button.ClickEvent event) {
                        Execution execution = Flash.flash().getProcessEngine().getRuntimeService()
                                .createExecutionQuery().executionId(param.executionId).singleResult();
                        if (execution == null) {
                            alreadyGone();
                            return;
                        }
                        ShowDiagramComponent showDiagramComponent = new ShowDiagramComponent(param);
                        VerticalLayout layout = new VerticalLayout();
                        Button back = new Button("?");
                        back.addListener(new Button.ClickListener() {
                            private static final long serialVersionUID = 4154712522487297925L;

                            @Override
                            public void buttonClick(com.vaadin.ui.Button.ClickEvent event) {
                                bidChanger.back();
                            }
                        });
                        layout.addComponent(back);
                        layout.setSpacing(true);
                        layout.addComponent(showDiagramComponent);
                        bidChanger.set(layout, "showDiagram");
                        bidChanger.change(layout);
                    }
                });

                Button deleteBidButton = new Button(" ?");
                deleteBidButton.addListener(new Button.ClickListener() {
                    @Override
                    public void buttonClick(Button.ClickEvent event) {
                        final Window mainWindow = getWindow();
                        final Window rejectWindow = new Window();
                        rejectWindow.setWidth("38%");
                        rejectWindow.center();
                        rejectWindow.setCaption("!");
                        final VerticalLayout verticalLayout = new VerticalLayout();
                        verticalLayout.setSpacing(true);
                        verticalLayout.setMargin(true);
                        final Label messageLabel = new Label(
                                "  ? ?");
                        messageLabel.setStyleName("h2");
                        final TextArea textArea = new TextArea();
                        textArea.setSizeFull();
                        HorizontalLayout buttons = new HorizontalLayout();
                        buttons.setSpacing(true);
                        buttons.setSizeFull();
                        final Button ok = new Button("Ok");
                        Button cancel = new Button("Cancel");

                        buttons.addComponent(ok);
                        buttons.addComponent(cancel);
                        buttons.setExpandRatio(ok, 0.99f);
                        verticalLayout.addComponent(messageLabel);
                        verticalLayout.addComponent(textArea);
                        verticalLayout.addComponent(buttons);
                        verticalLayout.setExpandRatio(textArea, 0.99f);
                        rejectWindow.setContent(verticalLayout);
                        mainWindow.addWindow(rejectWindow);

                        Button.ClickListener ok1 = new Button.ClickListener() {
                            @Override
                            public void buttonClick(Button.ClickEvent event) {
                                ok.setEnabled(false);
                                verticalLayout.removeComponent(messageLabel);
                                verticalLayout.removeComponent(textArea);
                                final byte[] block;
                                final String textAreaValue = (String) textArea.getValue();
                                if (textAreaValue != null) {
                                    block = textAreaValue.getBytes();
                                } else {
                                    block = null;
                                }
                                Label reason = new Label(textAreaValue);
                                reason.setCaption(" :");
                                verticalLayout.addComponent(reason, 0);
                                event.getButton().removeListener(this);

                                SignApplet signApplet = new SignApplet(new SignAppletListener() {

                                    @Override
                                    public void onLoading(SignApplet signApplet) {

                                    }

                                    @Override
                                    public void onNoJcp(SignApplet signApplet) {
                                        verticalLayout.removeComponent(signApplet);
                                        ReadOnly field = new ReadOnly(
                                                "   ?? ?? ?  JCP",
                                                false);
                                        verticalLayout.addComponent(field);

                                    }

                                    @Override
                                    public void onCert(SignApplet signApplet, X509Certificate certificate) {
                                        boolean ok = false;
                                        String errorClause = null;
                                        try {
                                            boolean link = AdminServiceProvider
                                                    .getBoolProperty(CertificateVerifier.LINK_CERTIFICATE);
                                            if (link) {
                                                byte[] x509 = AdminServiceProvider.get()
                                                        .withEmployee(Flash.login(), new CertificateReader());
                                                ok = Arrays.equals(x509, certificate.getEncoded());
                                            } else {
                                                ok = true;
                                            }
                                            CertificateVerifyClientProvider.getInstance()
                                                    .verifyCertificate(certificate);
                                        } catch (CertificateEncodingException e) {
                                        } catch (CertificateInvalid err) {
                                            errorClause = err.getMessage();
                                            ok = false;
                                        }
                                        if (ok) {
                                            signApplet.block(1, 1);
                                        } else {
                                            NameParts subject = X509.getSubjectParts(certificate);
                                            String fieldValue = (errorClause == null)
                                                    ? " " + subject.getShortName()
                                                            + " "
                                                    : errorClause;
                                            ReadOnly field = new ReadOnly(fieldValue, false);
                                            verticalLayout.addComponent(field, 0);
                                        }
                                    }

                                    @Override
                                    public void onBlockAck(SignApplet signApplet, int i) {
                                        logger().fine("AckBlock:" + i);
                                        signApplet.chunk(1, 1, block);
                                    }

                                    @Override
                                    public void onChunkAck(SignApplet signApplet, int i) {
                                        logger().fine("AckChunk:" + i);
                                    }

                                    @Override
                                    public void onSign(SignApplet signApplet, byte[] sign) {
                                        final int i = signApplet.getBlockAck();
                                        logger().fine("done block:" + i);
                                        if (i < 1) {
                                            signApplet.block(i + 1, 1);
                                        } else {
                                            verticalLayout.removeComponent(signApplet);
                                            NameParts subjectParts = X509
                                                    .getSubjectParts(signApplet.getCertificate());
                                            Label field2 = new Label(subjectParts.getShortName());
                                            field2.setCaption("? ?:");
                                            verticalLayout.addComponent(field2, 0);
                                            ok.setEnabled(true);
                                        }
                                    }

                                    private Logger logger() {
                                        return Logger.getLogger(getClass().getName());
                                    }
                                });
                                byte[] x509 = AdminServiceProvider.get().withEmployee(Flash.login(),
                                        new CertificateReader());
                                if (x509 != null) {
                                    signApplet.setSignMode(x509);
                                } else {
                                    signApplet.setUnboundSignMode();
                                }
                                verticalLayout.addComponent(signApplet, 0);

                                ok.addListener(new Button.ClickListener() {
                                    @Override
                                    public void buttonClick(Button.ClickEvent event) {
                                        Task result = Flash.flash().getProcessEngine().getTaskService()
                                                .createTaskQuery().taskId(taskId).singleResult();
                                        if (result == null) {
                                            alreadyGone();
                                            return;
                                        }
                                        ActivitiBean.get().deleteProcessInstance(taskId, textAreaValue);
                                        AdminServiceProvider.get().createLog(Flash.getActor(), "activiti.task",
                                                taskId, "remove", " ?", true);
                                        fireTaskChangedEvent(taskId, SupervisorWorkplace.this);
                                        infoChanger.change(infoComponent);
                                        controlledTasksTable.setValue(null);
                                        controlledTasksTable.refresh();
                                        mainWindow.removeWindow(rejectWindow);
                                    }
                                });
                            }
                        };
                        ok.addListener(ok1);

                        cancel.addListener(new Button.ClickListener() {
                            @Override
                            public void buttonClick(Button.ClickEvent event) {

                                controlledTasksTable.refresh();
                                mainWindow.removeWindow(rejectWindow);
                            }
                        });
                    }
                });

                HorizontalLayout hl = new HorizontalLayout();
                hl.setSizeFull();
                hl.setSpacing(true);
                hl.addComponent(showDiagram);
                hl.addComponent(deleteBidButton);
                hl.setExpandRatio(showDiagram, 0.99f);
                hl.setExpandRatio(deleteBidButton, 0.01f);

                ((VerticalLayout) item1).addComponent(hl);
                ((VerticalLayout) item1).addComponent(procedureHistoryPanel);
                assignButton.setVisible(false);
                assignButton.addListener(new Button.ClickListener() {
                    @Override
                    public void buttonClick(Button.ClickEvent event) {
                        ((Layout) item3).removeAllComponents();
                        if (taskIdToAssign != null) {
                            ((Layout) item3).addComponent(createAssignerToTaskComponent(taskIdToAssign,
                                    (ProcedureHistoryPanel) procedureHistoryPanel, controlledTasksTable));
                            bidChanger.change(item3);
                        } else {
                            alreadyGone();
                        }
                    }
                });
                ((VerticalLayout) item1).addComponent(assignButton);
                infoChanger.change(bidComponent);
                bidChanger.change(item1);
            } else {
                ((VerticalLayout) item1).removeAllComponents();
            }
        }
    });
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * /*from   ww  w.  j  a va 2 s  . c o  m*/
 * The saved data must always win over any passed-in URI data
 * 
 * @param cert the given cert.
 */
private void validateX509Cert(final X509Certificate cert) {

    boolean certMismatch = false;

    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }

    // If there is no saved cert, then if a signature was provided,
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
        // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }

    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };

    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel),
                certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(),
                cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");

        // Actually display the message
        Utils.showYesNoPrompt(getContext(),
                getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?",
                certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}

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

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain./*ww w.  j  av  a 2s  .c  o m*/
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

From source file:jproxy.ProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {/*from   w ww  .  j av a 2s .c om*/
            X509Certificate caCert = (X509Certificate) keyStore.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:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception {

    KeyPairGenerator keyGen = null;

    if (signatureAlgorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {/*  ww w .j  a  v  a 2  s  .  c o  m*/
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }

    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();

    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(),
            expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;

    String alias = UUID.randomUUID().toString();

    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());

    PublicKey publicKey = keyPair.getPublic();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, Use.SIGNATURE);
    jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);

    return jsonObject;
}