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:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");
    for (X509Certificate xCert : signingCertificateChain) {
        LOG.debug("Cert chain: " + xCert.getSubjectX500Principal());
    }/* w w w  . ja v a2s  . c  om*/

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

public static BasicOCSPResp generateBasicOCSPResp(OCSPCAServiceRequest serviceReq, String sigAlg,
        X509Certificate signerCert, PrivateKey signerKey, String provider, X509Certificate[] chain,
        int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, IllegalArgumentException {
    BasicOCSPResp returnval = null;/* w ww .  j a  v a 2s.co  m*/
    BasicOCSPRespGenerator basicRes = null;
    basicRes = OCSPUtil.createOCSPResponse(serviceReq.getOCSPrequest(), signerCert, respIdType);
    ArrayList responses = serviceReq.getResponseList();
    if (responses != null) {
        Iterator iter = responses.iterator();
        while (iter.hasNext()) {
            OCSPResponseItem item = (OCSPResponseItem) iter.next();
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    X509Extensions exts = serviceReq.getExtensions();
    if (exts != null) {
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    returnval = basicRes.generate(sigAlg, signerKey, chain, new Date(), provider);
    if (m_log.isDebugEnabled()) {
        m_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)) {
            m_log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            m_log.debug("The OCSP response is verifying.");
        } else {
            m_log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

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

/** Gets the UUID from the subject name contained in the given X.509 certificate.
 *
 * @param x509Certificate the given X.509 certificate
 * @return the UUID/*from   w ww.  java 2  s .c  o  m*/
 */
public static UUID getUUID(final X509Certificate x509Certificate) {
    //Preconditions
    assert x509Certificate != null : "x509Certificate must not be null";

    final String subjectString = x509Certificate.getSubjectX500Principal().toString();
    assert !subjectString.isEmpty() : "subject DN must not be empty";
    final int index = subjectString.indexOf("UID=");
    assert index > -1 : "UID not found in the subject DN";
    final String uuidString = subjectString.substring(index + 4, index + 40);
    return UUID.fromString(uuidString);
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
    // digest the message
    MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo);
    byte[] digest = messageDigest.digest(data);

    // generate the TSP request
    BigInteger nonce = new BigInteger(128, new SecureRandom());
    TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator();
    requestGenerator.setCertReq(true);//from   w  ww .  jav  a 2  s . c om
    if (null != this.requestPolicy) {
        requestGenerator.setReqPolicy(this.requestPolicy);
    }
    TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce);
    byte[] encodedRequest = request.getEncoded();

    // create the HTTP client
    HttpClient httpClient = new HttpClient();
    if (null != this.username) {
        Credentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (null != this.proxyHost) {
        httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort);
    }

    // create the HTTP POST request
    PostMethod postMethod = new PostMethod(this.tspServiceUrl);
    RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query");
    postMethod.addRequestHeader("User-Agent", this.userAgent);
    postMethod.setRequestEntity(requestEntity);

    // invoke TSP service
    int statusCode = httpClient.executeMethod(postMethod);
    if (HttpStatus.SC_OK != statusCode) {
        LOG.error("Error contacting TSP server " + this.tspServiceUrl);
        throw new Exception("Error contacting TSP server " + this.tspServiceUrl);
    }

    // HTTP input validation
    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        throw new RuntimeException("missing Content-Type header");
    }
    String contentType = responseContentTypeHeader.getValue();
    if (!contentType.startsWith("application/timestamp-reply")) {
        LOG.debug("response content: " + postMethod.getResponseBodyAsString());
        throw new RuntimeException("invalid Content-Type: " + contentType);
    }
    if (0 == postMethod.getResponseContentLength()) {
        throw new RuntimeException("Content-Length is zero");
    }

    // TSP response parsing and validation
    InputStream inputStream = postMethod.getResponseBodyAsStream();
    TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream);
    timeStampResponse.validate(request);

    if (0 != timeStampResponse.getStatus()) {
        LOG.debug("status: " + timeStampResponse.getStatus());
        LOG.debug("status string: " + timeStampResponse.getStatusString());
        PKIFailureInfo failInfo = timeStampResponse.getFailInfo();
        if (null != failInfo) {
            LOG.debug("fail info int value: " + failInfo.intValue());
            if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) {
                LOG.debug("unaccepted policy");
            }
        }
        throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus());
    }
    TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken();
    SignerId signerId = timeStampToken.getSID();
    BigInteger signerCertSerialNumber = signerId.getSerialNumber();
    X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded());
    LOG.debug("signer cert serial number: " + signerCertSerialNumber);
    LOG.debug("signer cert issuer: " + signerCertIssuer);

    // TSP signer certificates retrieval
    CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection",
            BouncyCastleProvider.PROVIDER_NAME);
    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    X509Certificate signerCert = null;
    Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>();
    for (Certificate certificate : certificates) {
        X509Certificate x509Certificate = (X509Certificate) certificate;
        if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal())
                && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) {
            signerCert = x509Certificate;
        }
        String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate));
        certificateMap.put(ski, x509Certificate);
        LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski);
    }

    // TSP signer cert path building
    if (null == signerCert) {
        throw new RuntimeException("TSP response token has no signer certificate");
    }
    List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>();

    X509Certificate tsaIssuer = loadCertificate(
            "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt");
    X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer");
    LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal());
    tspCertificateChain.add(signerCert);
    LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal());
    tspCertificateChain.add(tsaIssuer);
    LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal());
    tspCertificateChain.add(rootCA);

    // verify TSP signer signature
    timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME);

    // verify TSP signer certificate
    this.validator.validate(tspCertificateChain, revocationData);

    LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime());

    byte[] timestamp = timeStampToken.getEncoded();
    return timestamp;
}

From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java

/**
 * Generate an X509 cert for use as the keystore cert chain
 * /*from  w  w  w  . j  a v  a2s . c o  m*/
 * @param keyPair
 * @return
 */
private X509Certificate generateCertificate(KeyPair keyPair, NodeRef person) {

    X509Certificate cert = null;
    int validDuration = Integer
            .parseInt(config.getProperty(RepositoryManagedSignatureProviderFactory.VALID_DURATION));

    // get user's first and last name
    Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(person);
    String firstName = String.valueOf(props.get(ContentModel.PROP_FIRSTNAME));
    String lastName = String.valueOf(props.get(ContentModel.PROP_LASTNAME));

    // backdate the start date by a day
    Calendar start = Calendar.getInstance();
    start.add(Calendar.DATE, -1);
    java.util.Date startDate = start.getTime();

    // what is the end date for this cert's validity?
    Calendar end = Calendar.getInstance();
    end.add(Calendar.DATE, validDuration);
    java.util.Date endDate = end.getTime();

    try {
        // This code works with newer versions of the BouncyCastle libraries, but not
        // the (severely outdated) version that ships with Alfresco
        /*X509v1CertificateBuilder certBuilder = new JcaX509v1CertificateBuilder(
            new X500Principal("CN=" + firstName + " " + lastName), 
            BigInteger.ONE, 
            startDate, cal.getTime(), 
            new X500Principal("CN=" + firstName + " " + lastName), 
            keyPair.getPublic());
                
         AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
         AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
         AsymmetricKeyParameter keyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParam);
        X509CertificateHolder certHolder = certBuilder.build(sigGen);
                
        // now lets convert this thing back to a regular old java cert
        CertificateFactory cf = CertificateFactory.getInstance("X.509");  
         InputStream certIs = new ByteArrayInputStream(certHolder.getEncoded()); 
         cert = (X509Certificate) cf.generateCertificate(certIs); 
         certIs.close();*/

        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        X500Principal subjectName = new X500Principal("CN=" + firstName + " " + lastName);

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setNotBefore(startDate);
        certGen.setNotAfter(endDate);
        certGen.setSubjectDN(subjectName);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

        // if we are actually generating a trusted cert, the action is a little different
        boolean generateTrusted = Boolean.parseBoolean(
                config.getProperty(RepositoryManagedSignatureProviderFactory.ENABLE_TRUSTED_CERTS));
        if (generateTrusted) {
            KeyStore trustedKs = getTrustedKeyStore();

            PrivateKey caKey = getCaKey(trustedKs);
            X509Certificate caCert = getCaCert(trustedKs);

            // set the issuer of the generated cert to the subject of the ca cert
            X500Principal caSubject = caCert.getSubjectX500Principal();
            certGen.setIssuerDN(caSubject);

            //add the required extensions for the new cert
            certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                    new AuthorityKeyIdentifierStructure(caCert));
            certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                    new SubjectKeyIdentifierStructure(keyPair.getPublic()));

            cert = certGen.generate(caKey, "BC");

            //verify the cert
            cert.verify(caCert.getPublicKey());
        } else {
            certGen.setIssuerDN(subjectName);
            cert = certGen.generate(keyPair.getPrivate(), "BC");
        }
    } catch (CertificateException ce) {
        logger.error("CertificateException creating or validating X509 certificate for user: " + ce);
        throw new AlfrescoRuntimeException(ce.getMessage());
    } catch (Exception ex) {
        logger.error("Unknown exception creating or validating X509 certificate for user : " + ex);
        ex.printStackTrace();
    }

    return cert;
}

From source file:eu.peppol.outbound.HttpPostTestIT.java

@Test
public void testPost() throws Exception {

    InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader()
            .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML);
    assertNotNull(resourceAsStream,/*  ww w . j a  va  2s . c o  m*/
            "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path");

    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream,
            new MimeType("application/xml"));

    signedMimeMessage.writeTo(System.out);

    CloseableHttpClient httpClient = createCloseableHttpClient();

    HttpPost httpPost = new HttpPost(OXALIS_AS2_URL);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    signedMimeMessage.writeTo(byteArrayOutputStream);

    X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal();
    CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal);
    PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender);

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString());
    httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(),
            new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST")
                    .toString());
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE");
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted
    httpPost.setEntity(
            new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed")));

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL);
    }

    HttpEntity entity = postResponse.getEntity(); // Any results?
    Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200);
    String contents = EntityUtils.toString(entity);

    assertNotNull(contents);
    if (log.isDebugEnabled()) {
        log.debug("Received: \n");
        Header[] allHeaders = postResponse.getAllHeaders();
        for (Header header : allHeaders) {
            log.debug("" + header.getName() + ": " + header.getValue());
        }
        log.debug("\n" + contents);
        log.debug("---------------------------");
    }

    try {

        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents);
        System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType());

        // Make sure we set content type header for the multipart message (should be multipart/signed)
        String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one
        mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse);
        Enumeration<String> headerlines = mimeMessage.getAllHeaderLines();
        while (headerlines.hasMoreElements()) {
            // Content-Type: multipart/signed;
            // protocol="application/pkcs7-signature";
            // micalg=sha-1;
            // boundary="----=_Part_3_520186210.1399207766925"
            System.out.println("HeaderLine : " + headerlines.nextElement());
        }

        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        System.out.println(msg);

    } finally {
        postResponse.close();
    }
}

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

/**
 * Validates the specified certificate using OCSP if configured.
 *
 * @param certificates the client certificates
 * @throws CertificateStatusException ex
 *//*from   w ww  .j  a  v  a 2s .  c om*/
public void validate(final X509Certificate[] certificates) throws CertificateStatusException {
    // only validate if configured to do so
    if (client != null && certificates != null && certificates.length > 0) {
        final X509Certificate subjectCertificate = getSubjectCertificate(certificates);
        final X509Certificate issuerCertificate = getIssuerCertificate(certificates);
        if (issuerCertificate == null) {
            throw new IllegalArgumentException(String.format(
                    "Unable to obtain certificate of issuer <%s> for the specified subject certificate <%s>.",
                    subjectCertificate.getIssuerX500Principal().getName(),
                    subjectCertificate.getSubjectX500Principal().getName()));
        }

        // create the ocsp status key
        final OcspRequest ocspRequest = new OcspRequest(subjectCertificate, issuerCertificate);

        try {
            // determine the status and ensure it isn't verified as revoked
            final OcspStatus ocspStatus = ocspCache.getUnchecked(ocspRequest);

            // we only disallow when we have a verified response that states the certificate is revoked
            if (VerificationStatus.Verified.equals(ocspStatus.getVerificationStatus())
                    && ValidationStatus.Revoked.equals(ocspStatus.getValidationStatus())) {
                throw new CertificateStatusException(String.format(
                        "Client certificate for <%s> is revoked according to the certificate authority.",
                        subjectCertificate.getSubjectX500Principal().getName()));
            }
        } catch (final UncheckedExecutionException uee) {
            logger.warn(String.format("Unable to validate client certificate via OCSP: <%s>",
                    subjectCertificate.getSubjectX500Principal().getName()), uee.getCause());
        }
    }
}

From source file:net.sf.dsig.DSApplet.java

private Map<String, X509Certificate[]> createAliasX509CertificateChainPair(KeyStoreProxy ksh)
        throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    Map<String, X509Certificate[]> aliasX509CertificateChainPair = new HashMap<String, X509Certificate[]>();

    Set<String> aliases = ksh.aliases();
    for (String alias : aliases) {
        X509Certificate[] certificateChain = ksh.getX509CertificateChain(alias);
        if (certificateChain == null || certificateChain.length == 0) {
            logger.warn("Null certificate chain returned; alias=" + alias);

            continue;
        }/*from w  w  w  .ja  v a 2 s. c o m*/

        X509Certificate certificate = certificateChain[0];

        String subjectName = certificate.getSubjectX500Principal().getName();
        String issuerName = certificate.getIssuerX500Principal().getName();
        BigInteger serialNumber = certificate.getSerialNumber();

        // Filter by subject

        if (getSubjectMatchingPattern() != null
                && !getSubjectMatchingPattern().matcher(subjectName).matches()) {
            logger.info("Subject does not match; skipping" + ": certificate.subject=" + subjectName);
            continue;
        }

        // Filter by issuer

        if (getIssuerMatchingPattern() != null && !getIssuerMatchingPattern().matcher(issuerName).matches()) {
            logger.info("Issuer does not match; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.issuer=" + issuerName);
            continue;
        }

        // Filter by serial number

        if (getSerialNumbersAllowedSet() != null && !getSerialNumbersAllowedSet().contains(serialNumber)) {
            logger.info("Serial number is not allowed; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.serialNumber=" + serialNumber);
            continue;
        }

        // Filter by key usage

        if (keyUsageRestrictions != null
                && !KeyUsageHelper.validateKeyUsage(certificate, keyUsageRestrictions)) {
            logger.info("Key usage restrictions not met; skipping" + ": certificate.subject=" + subjectName
                    + ", certificate.keyUsage=" + KeyUsageHelper.printKeyUsage(certificate));
            continue;
        }

        // Filter by private key

        if (!ksh.isKeyEntry(alias)) {
            logger.info("Private key not found; skipping" + ": certificate.subject=" + subjectName);
            continue;
        }

        logger.debug("Accepting certificate" + "; certificate.alias=" + alias + ", certificate.subject="
                + subjectName + ", certificate.serialNumber=" + serialNumber);

        aliasX509CertificateChainPair.put(alias, ksh.getX509CertificateChain(alias));
    }

    return aliasX509CertificateChainPair;
}

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

private void loadCert(X509Certificate cert) {
    if (cert != null) {
        String issuerDN = cert.getIssuerX500Principal().getName();
        String[] values = issuerDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            issuer.put(keyValue[0], keyValue[1]);
        }/*from  www  .j a va2  s.c o m*/
        String subjectDN = cert.getSubjectX500Principal().getName();
        values = subjectDN.split("(?<!\\\\),");
        for (String value : values) {
            String[] keyValue = value.split("=");
            subject.put(keyValue[0], keyValue[1]);
        }
        subject.put("validUntil", StringHelper.toString(cert.getNotAfter()));
        subject.put("validAfter", StringHelper.toString(cert.getNotBefore()));
    }
}