Example usage for java.security.cert X509Certificate getSubjectX500Principal

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

Introduction

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

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

private BasicOCSPResp generateBasicOcspResp(OCSPReq ocspRequest, X509Extensions exts,
        List<OCSPResponseItem> responses, String sigAlg, X509Certificate signerCert, PrivateKey signerKey,
        String provider, X509Certificate[] chain, int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, CryptoTokenOfflineException {
    BasicOCSPResp returnval = null;//w w w.j  av  a  2  s.c  o  m
    BasicOCSPRespGenerator basicRes = null;
    basicRes = createOcspResponseGenerator(ocspRequest, signerCert, respIdType);
    if (responses != null) {
        for (OCSPResponseItem item : responses) {
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    if (exts != null) {
        @SuppressWarnings("rawtypes")
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    /*
     * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread 
     * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since 
     * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. 
     * 
     * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by 
     * competing with its own thread pool, since these operations have no database impact.
     */

    final ExecutorService service = Executors.newFixedThreadPool(1);
    final Future<BasicOCSPResp> task = service
            .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider));

    try {
        returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e);
    } catch (ExecutionException e) {
        throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e);
    } catch (TimeoutException e) {
        throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
        RespID respId = null;
        if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
            respId = new RespID(signerCert.getSubjectX500Principal());
        } else {
            respId = new RespID(signerCert.getPublicKey());
        }
        if (!returnval.getResponderId().equals(respId)) {
            log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            log.debug("The OCSP response is verifying.");
        } else {
            log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Get user UID attribute for the given certificate.
 *
 * @param lookupValue value used for credentials lookup
 * @param certificate user certificate//from   w  ww  . j av  a2s .  c  om
 * @param cp credential provider
 * @return user UID
 * @throws NamingException LDAP error obtaining user UID.
 * @throws IOException 
 */
protected String loadUID(String lookupValue, X509Certificate certificate, CredentialProvider cp)
        throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String certificateAttrName = this.getUserCertificateAtrributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN,
                "(&(" + principalLookupAttrName + "={0})(" + certificateAttrName + "={1}))",
                new Object[] { lookupValue, certificate.getEncoded() }, getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Found user " + principalUidAttrName + "=" + uidValue);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for certificate '"
                            + certificate.getSubjectX500Principal().getName() + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } catch (CertificateEncodingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Certificate encoding exception", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                return null;
            }//from  w  ww .  j  a va  2 s. c  om
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();

    // If there was no certificate input, create a self signed
    String dn = "C=SE,O=Test,CN=Test"; // default
    // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
    {
        final Set<Principal> principals = subject.getPrincipals();
        if ((principals != null) && (principals.size() > 0)) {
            final Principal p = principals.iterator().next();
            if (p instanceof X500Principal) {
                X500Principal xp = (X500Principal) p;
                dn = xp.getName();
            }
        }
    }

    try {
        createUser(adminName, dn, "foo123", this.caid);
    } catch (AuthorizationDeniedException e1) {
        throw new CertificateCreationException("Error encountered when creating this.admin user", e1);
    } catch (UserDoesntFullfillEndEntityProfile e1) {
        throw new CertificateCreationException("Error encountered when creating this.admin user", e1);
    } catch (WaitingForApprovalException e1) {
        throw new CertificateCreationException("Error encountered when creating this.admin user", e1);
    } catch (EjbcaException e1) {
        throw new CertificateCreationException("Error encountered when creating this.admin user", e1);
    } catch (Exception e1) {
        throw new CertificateCreationException("Error encountered when creating this.admin user", e1);
    }

    try {
        certificate = (X509Certificate) this.signSession.createCertificate(this.admin, adminName, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (javax.ejb.ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }

    // Add the credentials and new principal
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials);
    return result;
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java

private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                return null;
            }/*from ww w.  j a v a 2 s.c om*/
        }
    }

    final X509Certificate certificate;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();

    // If there was no certificate input, create a self signed
    String dn = "C=SE,O=Test,CN=Test"; // default
    // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
    {
        final Set<Principal> principals = subject.getPrincipals();
        if ((principals != null) && (principals.size() > 0)) {
            Principal p = principals.iterator().next();
            if (p instanceof X500Principal) {
                X500Principal xp = (X500Principal) p;
                dn = xp.getName();
            }
        }
    }

    try {
        createUser(adminName, dn, "foo123");
    } catch (AuthorizationDeniedException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (UserDoesntFullfillEndEntityProfile e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (WaitingForApprovalException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (EjbcaException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (Exception e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    }

    try {
        certificate = (X509Certificate) this.signSession.createCertificate(ADMIN, adminName, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }

    // Add the credentials and new principal
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials);
    return result;
}

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  w ww . ja  v  a  2 s.com
 * 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.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

private AuthenticationToken createTokenWithCert(String adminName, AuthenticationSubject subject, KeyPair keys,
        int _caid, int eepid, int cpid) {

    // A small check if we have added a "fail" credential to the subject.
    // If we have we will return null, so we can test authentication failure.
    Set<?> usercredentials = subject.getCredentials();
    if ((usercredentials != null) && (usercredentials.size() > 0)) {
        Object o = usercredentials.iterator().next();
        if (o instanceof String) {
            String str = (String) o;
            if (StringUtils.equals("fail", str)) {
                return null;
            }/*  w w w .  ja v  a  2  s.c om*/
        }
    }

    X509Certificate certificate = null;
    // If we have a certificate as input, use that, otherwise generate a self signed certificate
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();

    // If there was no certificate input, create a self signed
    String dn = "C=SE,O=Test,CN=Test"; // default
    // If we have created a subject with an X500Principal we will use this DN to create the dummy certificate.
    {
        Set<Principal> principals = subject.getPrincipals();
        if ((principals != null) && (principals.size() > 0)) {
            Principal p = principals.iterator().next();
            if (p instanceof X500Principal) {
                X500Principal xp = (X500Principal) p;
                dn = xp.getName();
            }
        }
    }

    try {
        createUser(adminName, dn, "foo123", true, _caid, eepid, cpid);
    } catch (AuthorizationDeniedException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (UserDoesntFullfillEndEntityProfile e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (WaitingForApprovalException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (EjbcaException e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    } catch (Exception e1) {
        throw new CertificateCreationException("Error encountered when creating admin user", e1);
    }

    try {
        certificate = (X509Certificate) this.signSession.createCertificate(ADMIN, adminName, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
    } catch (ObjectNotFoundException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CADoesntExistsException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (EjbcaException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (AuthorizationDeniedException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    } catch (CesecoreException e) {
        throw new CertificateCreationException("Error encountered when creating certificate", e);
    }

    assertNotNull(certificate);

    // Add the credentials and new principal
    credentials.add(certificate);
    Set<X500Principal> principals = new HashSet<X500Principal>();
    principals.add(certificate.getSubjectX500Principal());

    // We cannot use the X509CertificateAuthenticationToken here, since it can only be used internally in a JVM.
    AuthenticationToken result = new TestX509CertificateAuthenticationToken(principals, credentials);
    assertNotNull(result);
    return result;
}

From source file:be.fedict.eid.dss.ws.DSSUtil.java

/**
 * Adds a DSS Verification Report to specified optional output element from
 * the specified list of {@link SignatureInfo}'s
 * //  www  .j  a  va  2  s.  c  o m
 * @param optionalOutput
 *            optional output to add verification report to
 * @param signatureInfos
 *            signature infos to use in verification report.
 */
public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) {

    LOG.debug("return verification report");
    VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType();
    List<IndividualReportType> individualReports = verificationReport.getIndividualReport();
    for (SignatureInfo signatureInfo : signatureInfos) {
        X509Certificate signerCertificate = signatureInfo.getSigner();
        IndividualReportType individualReport = vrObjectFactory.createIndividualReportType();
        individualReports.add(individualReport);

        SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType();
        individualReport.setSignedObjectIdentifier(signedObjectIdentifier);
        SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType();
        signedObjectIdentifier.setSignedProperties(signedProperties);
        SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory
                .createSignedSignaturePropertiesType();
        signedProperties.setSignedSignatureProperties(signedSignatureProperties);
        GregorianCalendar calendar = new GregorianCalendar();
        calendar.setTime(signatureInfo.getSigningTime());
        signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar));

        be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult();
        individualReport.setResult(individualResult);
        individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS);
        individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE);

        be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType();
        individualReport.setDetails(details);

        DetailedSignatureReportType detailedSignatureReport = vrObjectFactory
                .createDetailedSignatureReportType();
        details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport));
        VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType();
        formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
        detailedSignatureReport.setFormatOK(formatOKVerificationResult);

        SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType();
        detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity);
        VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType();
        signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult);
        sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        if (null != signatureInfo.getRole()) {
            PropertiesType properties = vrObjectFactory.createPropertiesType();
            detailedSignatureReport.setProperties(properties);
            SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType();
            properties.setSignedProperties(vrSignedProperties);
            SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory
                    .createSignedSignaturePropertiesType();
            vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties);
            vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar));
            SignerRoleType signerRole = vrObjectFactory.createSignerRoleType();
            vrSignedSignatureProperties.setSignerRole(signerRole);
            ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType();
            signerRole.setClaimedRoles(claimedRolesList);
            be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory
                    .createAnyType();
            claimedRolesList.getClaimedRole().add(claimedRoleAny);
            claimedRoleAny.getContent().add(signatureInfo.getRole());
        }

        CertificatePathValidityType certificatePathValidity = vrObjectFactory
                .createCertificatePathValidityType();
        detailedSignatureReport.setCertificatePathValidity(certificatePathValidity);

        VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType();
        certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
        certificatePathValidity.setPathValiditySummary(certPathVerificationResult);

        X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType();
        certificatePathValidity.setCertificateIdentifier(certificateIdentifier);
        certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString());
        certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber());

        CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory
                .createCertificatePathValidityVerificationDetailType();
        certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail);
        CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType();
        certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity);
        certificateValidity.setCertificateIdentifier(certificateIdentifier);
        certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString());

        VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateValidity.setChainingOK(chainingOkVerificationResult);
        chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory
                .createVerificationResultType();
        certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult);
        validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateValidity.setExtensionsOK(extensionsOkVerificationResult);
        extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);

        try {
            certificateValidity.setCertificateValue(signerCertificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }

        certificateValidity.setSignatureOK(signatureOkSignatureValidity);

        CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType();
        certificateValidity.setCertificateStatus(certificateStatus);
        VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType();
        certificateStatus.setCertStatusOK(certStatusOkVerificationResult);
        certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID);
    }

    Document newDocument = documentBuilder.newDocument();
    Element newElement = newDocument.createElement("newNode");
    try {
        vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
    Element verificationReportElement = (Element) newElement.getFirstChild();
    optionalOutput.getAny().add(verificationReportElement);
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void generatePkcs12() throws Exception {
    log.trace(">generatePkcs12");
    boolean exceptionThrown = false;
    try {/*from w  ww  .  j av a  2s.  c  o m*/
        ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown);// Should fail

    // Change token to P12
    UserMatch usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue(CA1_WSTESTUSER1);
    List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch);
    assertNotNull(userdatas);
    assertEquals(1, userdatas.size());
    userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    userdatas.get(0).setSubjectDN(getDN(CA1_WSTESTUSER1));
    ejbcaraws.editUser(userdatas.get(0));

    exceptionThrown = false;
    try {
        ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, PASSWORD, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        exceptionThrown = true;
    }
    assertTrue(exceptionThrown); // Should fail

    // Change password to foo456 and status to NEW
    userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW);
    userdatas.get(0).setPassword("foo456");
    userdatas.get(0).setClearPwd(true);
    ejbcaraws.editUser(userdatas.get(0));

    KeyStore ksenv = null;
    try {
        ksenv = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024",
                AlgorithmConstants.KEYALGORITHM_RSA);
    } catch (EjbcaException_Exception e) {
        assertTrue(e.getMessage(), false);
    }

    assertNotNull(ksenv);

    java.security.KeyStore ks = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", "foo456");

    assertNotNull(ks);
    Enumeration<String> en = ks.aliases();
    String alias = en.nextElement();
    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
    assertEquals(cert.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    PrivateKey privK1 = (PrivateKey) ks.getKey(alias, "foo456".toCharArray());
    log.info("test04GeneratePkcs12() Certificate " + cert.getSubjectDN().toString() + " equals "
            + getDN(CA1_WSTESTUSER1));

    // Generate a new one and make sure it is a new one and that key
    // recovery does not kick in by mistake
    // Set status to new
    usermatch = new UserMatch();
    usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    usermatch.setMatchvalue(CA1_WSTESTUSER1);
    userdatas = ejbcaraws.findUser(usermatch);
    assertTrue(userdatas != null);
    assertTrue(userdatas.size() == 1);
    userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW);
    userdatas.get(0).setPassword("foo456");
    userdatas.get(0).setClearPwd(true);
    ejbcaraws.editUser(userdatas.get(0));
    // A new PK12 request now should return the same key and certificate
    KeyStore ksenv2 = ejbcaraws.pkcs12Req(CA1_WSTESTUSER1, "foo456", null, "1024",
            AlgorithmConstants.KEYALGORITHM_RSA);
    java.security.KeyStore ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    X509Certificate cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    PrivateKey privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

    // Compare certificates, must not be the same
    assertFalse(cert.getSerialNumber().toString(16).equals(cert2.getSerialNumber().toString(16)));
    // Compare keys, must not be the same
    String key1 = new String(Hex.encode(privK1.getEncoded()));
    String key2 = new String(Hex.encode(privK2.getEncoded()));
    assertFalse(key1.equals(key2));

    // Test the method for adding/editing and requesting a PKCS#12 KeyStore
    // in a single transaction
    ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "PKCS12", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectDN().toString(), getDN(CA1_WSTESTUSER1));
    privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());

    // Test the method for adding/editing and requesting a JKS KeyStore in a
    // single transaction
    userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_JKS);
    ksenv2 = ejbcaraws.softTokenRequest(userdatas.get(0), null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    ks2 = KeyStoreHelper.getKeyStore(ksenv2.getKeystoreData(), "JKS", "foo456");
    assertNotNull(ks2);
    en = ks2.aliases();
    alias = (String) en.nextElement();
    cert2 = (X509Certificate) ks2.getCertificate(alias);
    assertEquals(cert2.getSubjectX500Principal().getName(), getReversedDN(CA1_WSTESTUSER1));
    privK2 = (PrivateKey) ks2.getKey(alias, "foo456".toCharArray());
    log.trace("<generatePkcs12");
}

From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java

private PrincipalId updateServicePrincipalDetailInContainer(String userName, SolutionDetail detail,
        String containerDn) throws Exception {
    ILdapConnectionEx connection = getConnection();
    ArrayList<LdapMod> attributeList = new ArrayList<LdapMod>();
    ILdapMessage message = null;/*  w  w w.ja  v  a 2s  .c o  m*/
    String userDn = null;

    try {
        ValidateUtil.validateNotEmpty(containerDn, "container Dn");
        String domainName = getDomain();

        String[] attrNames = { ATTR_NAME_ACCOUNT };

        String filter = buildQueryBySrvFilter(new PrincipalId(userName, this.getDomain()));

        message = connection.search(containerDn, LdapScope.SCOPE_SUBTREE, filter, attrNames, false);

        ILdapEntry[] entries = message.getEntries();

        if (entries != null && entries.length == 1) {
            // found the user
            userDn = entries[0].getDN();
        } else {
            // The user doesn't exist.
            // There shouldn't be the case that there will be two users
            // with same account name in lotus, this should be prevented
            // when adding a user.
            throw new InvalidPrincipalException(String.format("user %s already exists", userName),
                    String.format("%s@%s", userName, getDomain()));
        }

        // We might need to delete that attribute for such case?
        // For now just use REPLACE.
        String desc = detail.getDescription();
        if (null != desc && !desc.isEmpty()) {
            LdapMod attrDescription = new LdapMod(LdapModOperation.REPLACE, ATTR_SVC_DESCRIPTION,
                    new LdapValue[] { LdapValue.fromString(desc) });
            attributeList.add(attrDescription);
        }

        X509Certificate cert = detail.getCertificate();

        if (cert != null) {
            Principal subjectDN = cert.getSubjectX500Principal();

            // vmwSTSSubjectDn is a MUST attribute
            ValidateUtil.validateNotNull(subjectDN, "Solution userCertificate subjectDn");
            ValidateUtil.validateNotEmpty(subjectDN.getName(), "Solution userCertificate subjectDn");

            LdapMod attrSubjectDN = new LdapMod(LdapModOperation.REPLACE, ATTR_NAME_SUBJECTDN,
                    new LdapValue[] { LdapValue.fromString(subjectDN.getName()) });
            attributeList.add(attrSubjectDN);

            byte[] certBytes = cert.getEncoded();

            assert (certBytes != null);

            LdapMod attrCert = new LdapMod(LdapModOperation.REPLACE, ATTR_NAME_CERT,
                    new LdapValue[] { new LdapValue(certBytes) });
            attributeList.add(attrCert);
        } else {
            throw new InvalidArgumentException(String.format(
                    "updateServicePrincipal for user %s fails: solution must have certificate", userName));
        }

        if (attributeList.size() > 0) {
            // Only update when necessary
            connection.modifyObject(userDn, attributeList.toArray(new LdapMod[attributeList.size()]));
        }

        return new PrincipalId(userName, domainName);
    } finally {
        if (null != message) {
            message.close();
        }
        connection.close();
    }
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@TestOrderAnnotation(order = 44)
@Test//  w  w  w. j a  va 2  s.  co  m
public void findSolutionUserByCertDN() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    String tenantName = props.getProperty(CFG_KEY_IDM_TENANT_1_NAME);

    Assert.assertNotNull(tenantName);

    Tenant tenant = IdmClientTestUtil.ensureTenantExists(idmClient, tenantName);

    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);

    X509Certificate cert = (X509Certificate) ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS));

    SolutionUser user = idmClient.findSolutionUserByCertDn(tenant.getName(),
            cert.getSubjectX500Principal().getName());

    Assert.assertNotNull(user);
}