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:test.be.fedict.eid.applet.PdfSpikeTest.java

@Test
public void testSignPDF() throws Exception {
    // create a sample PDF file
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();//from   w ww.j  a  v  a 2  s  .com

    Paragraph titleParagraph = new Paragraph("This is a test.");
    titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(titleParagraph);

    document.newPage();
    Paragraph textParagraph = new Paragraph("Hello world.");
    document.add(textParagraph);

    document.close();

    File tmpFile = File.createTempFile("test-", ".pdf");
    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(tmpFile, baos.toByteArray());

    // eID
    PcscEid pcscEid = new PcscEid(new TestView(), new Messages(Locale.getDefault()));
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();
    }

    List<X509Certificate> signCertificateChain = pcscEid.getSignCertificateChain();
    Certificate[] certs = new Certificate[signCertificateChain.size()];
    for (int idx = 0; idx < certs.length; idx++) {
        certs[idx] = signCertificateChain.get(idx);
    }

    // open the pdf
    FileInputStream pdfInputStream = new FileInputStream(tmpFile);
    File signedTmpFile = File.createTempFile("test-signed-", ".pdf");
    PdfReader reader = new PdfReader(pdfInputStream);
    FileOutputStream pdfOutputStream = new FileOutputStream(signedTmpFile);
    PdfStamper stamper = PdfStamper.createSignature(reader, pdfOutputStream, '\0', null, true);

    // add extra page
    Rectangle pageSize = reader.getPageSize(1);
    int pageCount = reader.getNumberOfPages();
    int extraPageIndex = pageCount + 1;
    stamper.insertPage(extraPageIndex, pageSize);

    // calculate unique signature field name
    int signatureNameIndex = 1;
    String signatureName;
    AcroFields existingAcroFields = reader.getAcroFields();
    List<String> existingSignatureNames = existingAcroFields.getSignatureNames();
    do {
        signatureName = "Signature" + signatureNameIndex;
        signatureNameIndex++;
    } while (existingSignatureNames.contains(signatureName));
    LOG.debug("new unique signature name: " + signatureName);

    PdfSignatureAppearance signatureAppearance = stamper.getSignatureAppearance();
    signatureAppearance.setCrypto(null, certs, null, PdfSignatureAppearance.SELF_SIGNED);
    signatureAppearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    signatureAppearance.setReason("PDF Signature Test");
    signatureAppearance.setLocation("Belgium");
    signatureAppearance.setVisibleSignature(new Rectangle(54, 440, 234, 566), extraPageIndex, signatureName);
    signatureAppearance.setExternalDigest(new byte[128], new byte[20], "RSA");
    signatureAppearance.preClose();

    byte[] content = IOUtils.toByteArray(signatureAppearance.getRangeStream());
    byte[] hash = MessageDigest.getInstance("SHA-1").digest(content);
    byte[] signatureBytes = pcscEid.sign(hash, "SHA-1");
    pcscEid.close();

    PdfSigGenericPKCS sigStandard = signatureAppearance.getSigStandard();
    PdfPKCS7 signature = sigStandard.getSigner();
    signature.setExternalDigest(signatureBytes, hash, "RSA");
    PdfDictionary dictionary = new PdfDictionary();
    dictionary.put(PdfName.CONTENTS, new PdfString(signature.getEncodedPKCS1()).setHexWriting(true));
    signatureAppearance.close(dictionary);

    LOG.debug("signed tmp file: " + signedTmpFile.getAbsolutePath());

    // verify the signature
    reader = new PdfReader(new FileInputStream(signedTmpFile));
    AcroFields acroFields = reader.getAcroFields();
    ArrayList<String> signatureNames = acroFields.getSignatureNames();
    for (String signName : signatureNames) {
        LOG.debug("signature name: " + signName);
        LOG.debug("signature covers whole document: " + acroFields.signatureCoversWholeDocument(signName));
        LOG.debug("document revision " + acroFields.getRevision(signName) + " of "
                + acroFields.getTotalRevisions());
        PdfPKCS7 pkcs7 = acroFields.verifySignature(signName);
        Calendar signDate = pkcs7.getSignDate();
        LOG.debug("signing date: " + signDate.getTime());
        LOG.debug("Subject: " + PdfPKCS7.getSubjectFields(pkcs7.getSigningCertificate()));
        LOG.debug("Document modified: " + !pkcs7.verify());
        Certificate[] verifyCerts = pkcs7.getCertificates();
        for (Certificate certificate : verifyCerts) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            LOG.debug("cert subject: " + x509Certificate.getSubjectX500Principal());
        }
    }

    /*
     * Reading the signature using Apache PDFBox.
     */
    PDDocument pdDocument = PDDocument.load(signedTmpFile);
    COSDictionary trailer = pdDocument.getDocument().getTrailer();
    /*
     * PDF Reference - third edition - Adobe Portable Document Format -
     * Version 1.4 - 3.6.1 Document Catalog
     */
    COSDictionary documentCatalog = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);

    /*
     * 8.6.1 Interactive Form Dictionary
     */
    COSDictionary acroForm = (COSDictionary) documentCatalog.getDictionaryObject(COSName.ACRO_FORM);

    COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
    for (int fieldIdx = 0; fieldIdx < fields.size(); fieldIdx++) {
        COSDictionary field = (COSDictionary) fields.getObject(fieldIdx);
        String fieldType = field.getNameAsString("FT");
        if ("Sig".equals(fieldType)) {
            COSDictionary signatureDictionary = (COSDictionary) field.getDictionaryObject(COSName.V);
            /*
             * TABLE 8.60 Entries in a signature dictionary
             */
            COSString signatoryName = (COSString) signatureDictionary.getDictionaryObject(COSName.NAME);
            if (null != signatoryName) {
                LOG.debug("signatory name: " + signatoryName.getString());
            }
            COSString reason = (COSString) signatureDictionary.getDictionaryObject(COSName.REASON);
            if (null != reason) {
                LOG.debug("reason: " + reason.getString());
            }
            COSString location = (COSString) signatureDictionary.getDictionaryObject(COSName.LOCATION);
            if (null != location) {
                LOG.debug("location: " + location.getString());
            }
            Calendar signingTime = signatureDictionary.getDate(COSName.M);
            if (null != signingTime) {
                LOG.debug("signing time: " + signingTime.getTime());
            }
            String signatureHandler = signatureDictionary.getNameAsString(COSName.FILTER);
            LOG.debug("signature handler: " + signatureHandler);
        }
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*from ww w .  ja v  a 2 s  .c  om*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:be.fedict.hsm.ws.impl.WSSecuritySOAPHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    Crypto crypto = new WSSecurityCrypto();
    WSSConfig wssConfig = new WSSConfig();
    wssConfig.setWsiBSPCompliant(true);//from ww  w  .  ja  v  a2 s  .c  o  m
    secEngine.setWssConfig(wssConfig);
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, crypto);
    if (null == results) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security results");
    }

    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == timeStampActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
    String timeStampIdRef = "#" + receivedTimestamp.getID();

    WSSecurityEngineResult bstActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
    if (null == bstActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security BinarySecurityToken");
    }
    BinarySecurity binarySecurityToken = (BinarySecurity) bstActionResult
            .get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);

    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    if (null == signActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no valid XML signature");
    }
    String signatureMethod = (String) signActionResult.get(WSSecurityEngineResult.TAG_SIGNATURE_METHOD);
    LOG.debug("signature method: " + signatureMethod);
    if (false == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(signatureMethod)) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("signature algo should be RSA-SHA256");
    }
    X509Certificate certificate = (X509Certificate) signActionResult
            .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    List<WSDataRef> wsDataRefs = (List<WSDataRef>) signActionResult
            .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    String bodyIdRef = "#" + soapBody.getAttributeNS(WSU_NAMESPACE, "Id");
    String bstIdRef = "#" + binarySecurityToken.getID();

    boolean timestampDigested = false;
    boolean bodyDigested = false;
    boolean tokenDigested = false;
    for (WSDataRef wsDataRef : wsDataRefs) {
        String wsuId = wsDataRef.getWsuId();
        LOG.debug("signed wsu:Id: " + wsuId);
        LOG.debug("digest algorithm: " + wsDataRef.getDigestAlgorithm());
        if (false == "http://www.w3.org/2001/04/xmlenc#sha256".equals(wsDataRef.getDigestAlgorithm())) {
            this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
            throw new SecurityException("digest algorithm should be SHA256");
        }
        if (timeStampIdRef.equals(wsuId)) {
            timestampDigested = true;
        } else if (bodyIdRef.equals(wsuId)) {
            bodyDigested = true;
        } else if (bstIdRef.equals(wsuId)) {
            tokenDigested = true;
        }
    }
    if (false == timestampDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("timestamp not digested");
    }
    if (false == bodyDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("SOAP Body not digested");
    }
    if (false == tokenDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("BinarySecurityToken not digested");
    }

    context.put(X509_ATTRIBUTE, certificate);
}

From source file:be.fedict.trust.service.bean.TrustServiceTrustLinker.java

public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData) {

    LOG.debug("certificate: " + childCertificate.getSubjectX500Principal());
    LOG.debug("certificate Issuer: " + childCertificate.getIssuerX500Principal().toString());

    LOG.debug("Issuer: " + certificate.getSubjectX500Principal());

    BigInteger issuerSerialNumber = certificate.getSerialNumber();
    String key = new String();
    key += certificate.getSubjectX500Principal().toString() + "|" + issuerSerialNumber.toString();

    String issuerName = childCertificate.getIssuerX500Principal().toString();

    CertificateAuthorityEntity certificateAuthority = this.entityManager
            //.find(CertificateAuthorityEntity.class, issuerName);
            .find(CertificateAuthorityEntity.class, key);
    if (null == certificateAuthority) {
        LOG.debug("no data cache entry for CA: " + issuerName + " - Serial Number: "
                + issuerSerialNumber.toString());
        /*/*  w  ww.j a va 2  s . com*/
         * Cache Miss
         */
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);

        /*
         * Lookup Root CA's trust point via parent certificates' CA entity.
         */
        String parentIssuerName = certificate.getIssuerX500Principal().toString();
        CertificateAuthorityEntity parentCertificateAuthority = this.entityManager
                .find(CertificateAuthorityEntity.class, parentIssuerName);
        if (null == parentCertificateAuthority) {
            logAudit("CA not found for " + parentIssuerName);
            LOG.error("CA not found for " + parentIssuerName + " ?!");
            return null;
        }

        // create new CA
        try {
            certificateAuthority = new CertificateAuthorityEntity(getCrlUrl(childCertificate), certificate);
            certificateAuthority.setTrustPoint(parentCertificateAuthority.getTrustPoint());
        } catch (CertificateEncodingException e) {
            LOG.error("certificate encoding error: " + e.getMessage(), e);
            return null;
        }
        this.entityManager.persist(certificateAuthority);
        return null;
    }
    if (Status.ACTIVE != certificateAuthority.getStatus()) {
        LOG.debug("CA revocation data cache not yet active: " + issuerName);
        /*
         * Harvester is still busy processing the first CRL.
         */
        if (null == certificateAuthority.getCrlUrl()) {
            certificateAuthority.setCrlUrl(getCrlUrl(childCertificate));
        }

        if (Status.NONE != certificateAuthority.getStatus()) {
            // none means no CRL is available so not really a cache miss
            SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        }
        return null;
    }
    /*
     * Let's use the cached revocation data
     */
    Date thisUpdate = certificateAuthority.getThisUpdate();
    if (null == thisUpdate) {
        LOG.warn("no thisUpdate value: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    Date nextUpdate = certificateAuthority.getNextUpdate();
    if (null == nextUpdate) {
        LOG.warn("no nextUpdate value: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    /*
     * First check whether the cached revocation data is up-to-date.
     */
    if (thisUpdate.after(validationDate)) {
        LOG.warn("cached CRL data too recent: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    if (validationDate.after(nextUpdate)) {
        LOG.warn("cached CRL data too old: " + certificateAuthority.getName());
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
        return null;
    }
    LOG.debug("using cached CRL data");
    /*
     * Cache Hit
     */
    SNMPInterceptor.increment(SnmpConstants.CACHE_HITS, SnmpConstants.SNMP_SERVICE, 1L);

    BigInteger serialNumber = childCertificate.getSerialNumber();
    RevokedCertificateEntity revokedCertificate = findRevokedCertificate(issuerName, serialNumber);
    if (null == revokedCertificate) {
        LOG.debug("certificate valid: " + childCertificate.getSubjectX500Principal());
        return new TrustLinkerResult(true);
    }
    if (revokedCertificate.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        return new TrustLinkerResult(true);
    }
    LOG.debug("certificate invalid: " + childCertificate.getSubjectX500Principal());
    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by cached CRL");
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest,
        String signatureRequestId, String contentType, String language, String relayState,
        byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    LOG.debug("verifying service signature");
    X509Certificate serviceCertificate = serviceCertificateChain.get(0);
    LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal());
    Signature serviceSignature = Signature.getInstance("SHA1withRSA");
    serviceSignature.initVerify(serviceCertificate);

    StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ",");
    while (serviceSignedStringTokenizer.hasMoreTokens()) {
        String serviceSignedElement = serviceSignedStringTokenizer.nextToken();
        LOG.debug("service signed: " + serviceSignedElement);
        byte[] data;
        if ("target".equals(serviceSignedElement)) {
            data = target.getBytes();/*  w w w .  j av  a 2  s . c o  m*/
        } else if ("SignatureRequest".equals(serviceSignedElement)) {
            data = signatureRequest.getBytes();
        } else if ("SignatureRequestId".equals(serviceSignedElement)) {
            data = signatureRequestId.getBytes();
        } else if ("ContentType".equals(serviceSignedElement)) {
            data = contentType.getBytes();
        } else if ("language".equals(serviceSignedElement)) {
            data = language.getBytes();
        } else if ("RelayState".equals(serviceSignedElement)) {
            data = relayState.getBytes();
        } else {
            throw new SecurityException("service signed unknown element: " + serviceSignedElement);
        }
        serviceSignature.update(data);
    }

    boolean valid = serviceSignature.verify(serviceSignatureValue);
    if (!valid) {
        throw new SecurityException("service signature not valid");
    }
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate,
        Date validationDate) {/*ww w .  j ava  2s .  com*/
    Principal subjectX500Principal = certificate.getSubjectX500Principal();

    if (x509crl == null) {
        log.error("No CRL found for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (log.isTraceEnabled()) {
        try {
            log.trace("CRL number: " + getCrlNumber(x509crl));
        } catch (IOException ex) {
            log.error("Failed to get CRL number", ex);
        }
    }

    if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        log.error("The CRL must be signed by the issuer '" + subjectX500Principal
                + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'");
        return false;
    }

    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception ex) {
        log.error("The signature verification for CRL cannot be performed", ex);
        return false;
    }

    log.debug("CRL validationDate: " + validationDate);
    log.debug("CRL nextUpdate: " + x509crl.getThisUpdate());
    log.debug("CRL thisUpdate: " + x509crl.getNextUpdate());

    if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) {
        log.error("CRL is too old");
        return false;
    }

    if (issuerCertificate.getKeyUsage() == null) {
        log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'");
        return false;
    }

    if (!issuerCertificate.getKeyUsage()[6]) {
        log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'");
        return false;
    }

    return true;

}

From source file:be.fedict.hsm.ws.impl.WSSecurityCrypto.java

public X509Certificate loadCertificate(InputStream in) throws WSSecurityException {
    LOG.debug("loadCertificate");
    X509Certificate certificate;
    try {// w  w w .  ja  v a2s . co  m
        certificate = (X509Certificate) this.certificateFactory.generateCertificate(in);
    } catch (CertificateException e) {
        throw new WSSecurityException("error loading certificate: " + e.getMessage(), e);
    }
    LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    /*
     * JAX-WS is not supposed to be used in a multi-threaded fashion, so
     * this should be OK to do.
     */
    this.certificate = certificate;
    return certificate;
}

From source file:org.globus.gsi.stores.ResourceSigningPolicyStoreTest.java

public void testGetSigningPolicyWithOutDNPrincipal() throws Exception {

    String sigPolPattern = caCertsLocation + "/*.signing_policy";
    ResourceSigningPolicyStore sigPolStore = new ResourceSigningPolicyStore(
            new ResourceSigningPolicyStoreParameters(sigPolPattern));

    String certPath1 = caCertsLocation + "/ffc3d59b.0";

    X509Certificate crt1 = readCertificate(certPath1);
    Assert.assertNotNull("Unable to read certificate in " + certPath1, crt1);

    // According to https://github.com/jglobus/JGlobus/issues/102 the second attempt is failing.
    // Therefore we query twice.
    SigningPolicy signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal());

    Assert.assertNotNull(signingPolicy);

    signingPolicy = sigPolStore.getSigningPolicy(crt1.getSubjectX500Principal());

    Assert.assertNotNull(signingPolicy);

}

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

private void doTest(Connection dbConn) throws Exception {

    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    final String unid;
    {//w w w.  java 2  s  . c o m
        // In this test SUBJECT_DN contains special, escaped characters to verify
        // that that works with CMP RA as well
        final PKIMessage one = genCertReq(this.issuerDN, SUBJECT_DN, this.keys, this.cacert, nonce, transid,
                true, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, CPNAME, 567);
        assertNotNull(req);

        reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200);
        checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false,
                PBEPASSWORD);
        final X509Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqId);
        unid = (String) new X509Principal(cert.getSubjectX500Principal().getEncoded()).getValues(X509Name.SN)
                .get(0);
        log.debug("Unid: " + unid);
    }
    {
        final PreparedStatement ps = dbConn.prepareStatement("select fnr from UnidFnrMapping where unid=?");
        ps.setString(1, unid);
        final ResultSet result = ps.executeQuery();
        assertTrue("Unid '" + unid + "' not found in DB.", result.next());
        final String fnr = result.getString(1);
        log.debug("FNR read from DB: " + fnr);
        assertEquals("Right FNR not found in DB.", FNR, fnr);
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage confirm = genCertConfirm(SUBJECT_DN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        final PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req1);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200);
        checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false,
                PBEPASSWORD);
        checkCmpPKIConfirmMessage(SUBJECT_DN, this.cacert, resp);
    }
}

From source file:be.e_contract.mycarenet.etee.Unsealer.java

private byte[] getVerifiedContent(byte[] cmsData)
        throws CertificateException, CMSException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(cmsData);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    if (null == this.senderCertificate) {
        if (certificateCollection.isEmpty()) {
            throw new SecurityException("no sender certificate present");
        }//from   ww  w  .j ava2s . com
        X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

        this.senderCertificate = certificate;
        LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal());
    }

    /*
     * By reusing the sender certificate we have the guarantee that the
     * outer signature and inner signature share the same origin.
     */
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(this.senderCertificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    return data;
}