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.impl.handler.SignCertificatesDataMessageHandler.java

public Object handleMessage(SignCertificatesDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    SignatureService signatureService = this.signatureServiceLocator.locateService();

    List<X509Certificate> signingCertificateChain = message.certificateChain;
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("missing non-repudiation certificate");
    }/*from   ww w .j av a 2s  .c  o m*/
    LOG.debug("signing certificate: " + signingCertificateChain.get(0).getSubjectX500Principal());

    RequestContext requestContext = new RequestContext(session);
    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includePhoto = requestContext.includePhoto();

    Identity identity = null;
    Address address = null;
    if (includeIdentity || includeAddress || includePhoto) {
        /*
         * Pre-sign phase including identity data.
         */
        if (includeIdentity) {
            if (null == message.identityData) {
                throw new ServletException("identity data missing");
            }
            identity = TlvParser.parse(message.identityData, Identity.class);
        }

        if (includeAddress) {
            if (null == message.addressData) {
                throw new ServletException("address data missing");
            }
            address = TlvParser.parse(message.addressData, Address.class);
        }

        if (includePhoto) {
            if (null == message.photoData) {
                throw new ServletException("photo data missing");
            }
            if (null != identity) {
                byte[] expectedPhotoDigest = identity.photoDigest;
                byte[] actualPhotoDigest;

                try {
                    actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                            message.photoData);
                } catch (NoSuchAlgorithmException e) {
                    throw new ServletException("photo signed with unsupported algorithm");
                }

                if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                    throw new ServletException("photo digest incorrect");
                }
            }
        }

        IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                .locateService();
        if (null != identityIntegrityService) {
            if (null == message.rrnCertificate) {
                throw new ServletException("national registry certificate not included while requested");
            }
            PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
            if (null != message.identityData) {
                if (null == message.identitySignatureData) {
                    throw new ServletException("missing identity data signature");
                }
                verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData,
                        rrnPublicKey, request, message.identityData);
                if (null != message.addressData) {
                    if (null == message.addressSignatureData) {
                        throw new ServletException("missing address data signature");
                    }
                    byte[] addressFile = trimRight(message.addressData);
                    verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData,
                            rrnPublicKey, request, addressFile, message.identitySignatureData);
                }
            }

            LOG.debug("checking national registration certificate: "
                    + message.rrnCertificate.getSubjectX500Principal());
            List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
            rrnCertificateChain.add(message.rrnCertificate);
            //rrnCertificateChain.add(message.rootCertificate);
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        }
    }

    signingCertificateChain.add(message.rrnCertificate); //Sabemos con certeza que el rmCert contiene el CA RAIZ
    for (X509Certificate certificate : signingCertificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    DigestInfo digestInfo;
    LOG.debug("signature service class: " + signatureService.getClass().getName());
    if (SignatureServiceEx.class.isAssignableFrom(signatureService.getClass())) {
        LOG.debug("SignatureServiceEx SPI implementation detected");
        /*
         * The SignatureServiceEx SPI can also receive the identity during
         * the pre-sign phase.
         */
        SignatureServiceEx signatureServiceEx = (SignatureServiceEx) signatureService;
        DTOMapper dtoMapper = new DTOMapper();
        IdentityDTO identityDTO = dtoMapper.map(identity, IdentityDTO.class);
        AddressDTO addressDTO = dtoMapper.map(address, AddressDTO.class);
        try {
            digestInfo = signatureServiceEx.preSign(null, signingCertificateChain, identityDTO, addressDTO,
                    message.photoData);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("no such algo: " + e.getMessage(), e);
        }
    } else {
        LOG.debug("regular SignatureService SPI implementation");
        try {
            signatureService.setHttpSessionObject(request.getSession());
            digestInfo = signatureService.preSign(null, signingCertificateChain);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("no such algo: " + e.getMessage(), e);
        }
    }

    // also save it in the session for later verification
    SignatureDataMessageHandler.setDigestValue(digestInfo.digestValue, digestInfo.digestAlgo, session);

    IdentityService identityService = this.identityServiceLocator.locateService();
    boolean removeCard;
    if (null != identityService) {
        IdentityRequest identityRequest = identityService.getIdentityRequest();
        removeCard = identityRequest.removeCard();
    } else {
        removeCard = this.removeCard;
    }

    SignRequestMessage signRequestMessage = new SignRequestMessage(digestInfo.digestValue,
            digestInfo.digestAlgo, digestInfo.description, this.logoff, removeCard, this.requireSecureReader);
    return signRequestMessage;
}

From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java

@Test
public void testSign() throws Exception {
    // setup/*from  w ww  .  j  a  v a 2 s.  c  om*/
    KeyPair caKeyPair = generateKeyPair();
    KeyPair entityKeyPair = generateKeyPair();
    X500Principal subject = new X500Principal("CN=Test");
    PublicKey pubKey = entityKeyPair.getPublic();
    X500Principal issuer = new X500Principal("CN=CA");
    PublicKey caPubKey = caKeyPair.getPublic();
    PrivateKey caKey = caKeyPair.getPrivate();
    Date begin = new Date();
    Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30);
    BigInteger serialNo = BigInteger.valueOf(1234);
    JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();

    // operate
    X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends,
            serialNo, null);

    // verify
    assertNotNull(resultCert);
    LOG.debug("result certificate: " + resultCert);
    resultCert.verify(caPubKey);
    assertEquals(subject, resultCert.getSubjectX500Principal());
    assertEquals(issuer, resultCert.getIssuerX500Principal());
    assertEquals(serialNo, resultCert.getSerialNumber());
    assertEquals(pubKey, resultCert.getPublicKey());
    LOG.debug("expected begin: " + begin.getTime());
    LOG.debug("actual begin: " + resultCert.getNotBefore().getTime());
    /*
     * BouncyCastle drops the milliseconds.
     */
    assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000);
    assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000);

    byte[] subjectKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.subjectKeyIdentifier.getId());
    assertNotNull(subjectKeyIdentifierExtValue);
    ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(subjectKeyIdentifierExtValue);
    ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive();
    assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded());

    byte[] authorityKeyIdentifierExtValue = resultCert
            .getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
    ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils
            .parseExtensionValue(authorityKeyIdentifierExtValue);
    ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive();
    assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded());

    assertEquals(-1, resultCert.getBasicConstraints());

    byte[] netscapeCertTypeExtValue = resultCert
            .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId());
    assertNotNull(netscapeCertTypeExtValue);
    DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil
            .fromExtensionValue(netscapeCertTypeExtValue);
    NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt);
    assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient);
    assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer);

    assertTrue(resultCert.getKeyUsage()[0]);
    assertTrue(resultCert.getKeyUsage()[2]);

    byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId());
    assertNotNull(extendedKeyUsageExtValue);
    ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage
            .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth));
}

From source file:se.inera.axel.shs.broker.validation.certificate.CertificateExtractorImpl.java

private String extractSenderFromCertificate(X509Certificate x509Certificate) throws CertificateException {
    log.debug("Extracting sender id from certificate.");

    if (x509Certificate == null) {
        log.error("Cannot extract any sender because the certificate was null");
        throw new IllegalArgumentException("Cannot extract any sender because the certificate was null");
    }//ww  w. j  a v  a2s  .c  o  m

    final String principalName = x509Certificate.getSubjectX500Principal().getName();
    return extractSenderFromPrincipal(principalName);
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

private byte[] getCmsData(byte[] cms) throws Exception {
    CMSSignedData cmsSignedData = new CMSSignedData(cms);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);

    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    // we trust SSL here, no need for explicit verification of CMS signing
    // certificate

    LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal());

    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);//from w ww . java2s.  co m
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] responseData = (byte[]) signedContent.getContent();

    return responseData;
}

From source file:org.apache.ws.security.validate.SignatureTrustValidator.java

/**
 * Evaluate whether a given certificate should be trusted.
 * /*from  ww  w  . j  av a 2  s  .c  o m*/
 * Policy used in this implementation:
 * 1. Search the keystore for the transmitted certificate
 * 2. Search the keystore for a connection to the transmitted certificate
 * (that is, search for certificate(s) of the issuer of the transmitted certificate
 * 3. Verify the trust path for those certificates found because the search for the issuer 
 * might be fooled by a phony DN (String!)
 *
 * @param cert the certificate that should be validated against the keystore
 * @param crypto A crypto instance to use for trust validation
 * @param data A RequestData instance
 * @param enableRevocation Whether revocation is enabled or not
 * @return true if the certificate is trusted, false if not
 * @throws WSSecurityException
 */
protected boolean verifyTrustInCert(X509Certificate cert, Crypto crypto, RequestData data,
        boolean enableRevocation) throws WSSecurityException {
    String subjectString = cert.getSubjectX500Principal().getName();
    String issuerString = cert.getIssuerX500Principal().getName();
    BigInteger issuerSerial = cert.getSerialNumber();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Transmitted certificate has subject " + subjectString);
        LOG.debug("Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial + ")");
    }

    //
    // FIRST step - Search the keystore for the transmitted certificate
    //
    if (!enableRevocation && isCertificateInKeyStore(crypto, cert)) {
        return true;
    }

    //
    // SECOND step - Search for the issuer cert (chain) of the transmitted certificate in the 
    // keystore or the truststore
    //
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.SUBJECT_DN);
    cryptoType.setSubjectDN(issuerString);
    X509Certificate[] foundCerts = crypto.getX509Certificates(cryptoType);

    // If the certs have not been found, the issuer is not in the keystore/truststore
    // As a direct result, do not trust the transmitted certificate
    if (foundCerts == null || foundCerts.length < 1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No certs found in keystore for issuer " + issuerString + " of certificate for "
                    + subjectString);
        }
        return false;
    }

    //
    // THIRD step
    // Check the certificate trust path for the issuer cert chain
    //
    if (LOG.isDebugEnabled()) {
        LOG.debug("Preparing to validate certificate path for issuer " + issuerString);
    }
    //
    // Form a certificate chain from the transmitted certificate
    // and the certificate(s) of the issuer from the keystore/truststore
    //
    X509Certificate[] x509certs = new X509Certificate[foundCerts.length + 1];
    x509certs[0] = cert;
    for (int j = 0; j < foundCerts.length; j++) {
        x509certs[j + 1] = (X509Certificate) foundCerts[j];
    }

    //
    // Use the validation method from the crypto to check whether the subjects' 
    // certificate was really signed by the issuer stated in the certificate
    //
    if (crypto.verifyTrust(x509certs, enableRevocation)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Certificate path has been verified for certificate with subject " + subjectString);
        }
        Collection<Pattern> subjectCertConstraints = data.getSubjectCertConstraints();
        if (matches(cert, subjectCertConstraints)) {
            return true;
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate path could not be verified for certificate with subject " + subjectString);
    }
    return false;
}

From source file:be.fedict.trust.TrustValidator.java

/**
 * Validates whether the certificate path was valid at the given validation
 * date./*from  w  w  w  .j av a2 s . c o m*/
 * 
 * @param certificatePath
 *            the X509 certificate path to be validated.
 * @param validationDate
 *            the date at which the certificate path validation should be
 *            verified.
 * @throws CertPathValidatorException
 *             in case of an invalid certificate path.
 * @see #isTrusted(List)
 */
public void isTrusted(List<X509Certificate> certificatePath, Date validationDate)
        throws CertPathValidatorException {
    if (certificatePath.isEmpty()) {
        this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "certificate path is empty");
        throw new CertPathValidatorException(this.result.getMessage());
    }

    int certIdx = certificatePath.size() - 1;
    X509Certificate certificate = certificatePath.get(certIdx);
    LOG.debug("verifying root certificate: " + certificate.getSubjectX500Principal());
    this.result = getSelfSignedResult(certificate);
    if (!this.result.isValid()) {
        LOG.debug("result: " + this.result.getMessage());
        throw new CertPathValidatorException(this.result.getMessage());
    }
    // check certificate signature
    this.result = checkSignatureAlgorithm(certificate.getSigAlgName());
    if (!this.result.isValid()) {
        LOG.debug("result: " + this.result.getMessage());
        throw new CertPathValidatorException(this.result.getMessage());
    }
    checkSelfSignedTrust(certificate, validationDate);

    certIdx--;

    while (certIdx >= 0) {
        X509Certificate childCertificate = certificatePath.get(certIdx);
        LOG.debug("verifying certificate: " + childCertificate.getSubjectX500Principal());
        certIdx--;
        checkTrustLink(childCertificate, certificate, validationDate);
        certificate = childCertificate;
    }

    for (CertificateConstraint certificateConstraint : this.certificateConstraints) {
        String certificateConstraintName = certificateConstraint.getClass().getSimpleName();
        LOG.debug("certificate constraint check: " + certificateConstraintName);
        if (false == certificateConstraint.check(certificate)) {
            this.result = new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                    "certificate constraint failure: " + certificateConstraintName);
            throw new CertPathValidatorException(this.result.getMessage());
        }
    }

    this.result = new TrustLinkerResult(true);
}

From source file:co.runrightfast.core.security.cert.CAIssuedX509V3CertRequest.java

/**
 *
 * @param caCert/*from   w  w  w.  j a v  a2 s  .com*/
 * <ol>
 * <li>supplies the issuer principal
 * <li>used to add the Authority Key Identifier extension
 * </ol>
 * @param serialNumber
 * @param notBefore
 * @param notAfter
 * @param subjectPrincipal
 * @param subjectPublicKey
 * @param extensions
 */
public CAIssuedX509V3CertRequest(@NonNull final X509Certificate caCert, @NonNull final BigInteger serialNumber,
        @NonNull final Instant notBefore, @NonNull final Instant notAfter,
        @NonNull final X500Principal subjectPrincipal, @NonNull final PublicKey subjectPublicKey,
        @NonNull final Collection<X509CertExtension> extensions) {
    checkArgs(caCert, extensions);
    this.x509V3CertRequest = new X509V3CertRequest(caCert.getSubjectX500Principal(), serialNumber, notBefore,
            notAfter, subjectPrincipal, subjectPublicKey, augmentExtensions(extensions, caCert));
}

From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java

@Override
public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    byte[] signatureValue = message.signatureValue;
    List<X509Certificate> certificateChain = message.certificateChain;
    if (certificateChain.isEmpty()) {
        throw new ServletException("certificate chain is empty");
    }// w w  w.j  a v a  2 s.co m
    X509Certificate signingCertificate = certificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("non-repudiation certificate missing");
    }
    LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal());
    PublicKey signingPublicKey = signingCertificate.getPublicKey();

    BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request);

    /*
     * Verify the signature.
     */
    String digestAlgo = this.signatureState.getDigestAlgo();
    byte[] expectedDigestValue = this.signatureState.getDigestValue();
    if (digestAlgo.endsWith("-PSS")) {
        LOG.debug("verifying RSA/PSS signature");
        try {
            Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME);
            if ("SHA-256-PSS".equals(digestAlgo)) {
                LOG.debug("RSA/PSS SHA256");
                signature.setParameter(
                        new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
            }
            signature.initVerify(signingPublicKey);
            signature.update(expectedDigestValue);
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage(), e);
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    } else {
        try {
            Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME);
            signature.initVerify(signingPublicKey);
            ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
            if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) {
                digestInfo.write(SHA1_DIGEST_INFO_PREFIX);
            } else if ("SHA-224".equals(digestAlgo)) {
                digestInfo.write(SHA224_DIGEST_INFO_PREFIX);
            } else if ("SHA-256".equals(digestAlgo)) {
                digestInfo.write(SHA256_DIGEST_INFO_PREFIX);
            } else if ("SHA-384".equals(digestAlgo)) {
                digestInfo.write(SHA384_DIGEST_INFO_PREFIX);
            } else if ("SHA-512".equals(digestAlgo)) {
                digestInfo.write(SHA512_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD160".equals(digestAlgo)) {
                digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD128".equals(digestAlgo)) {
                digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX);
            } else if ("RIPEMD256".equals(digestAlgo)) {
                digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX);
            }
            digestInfo.write(expectedDigestValue);
            signature.update(digestInfo.toByteArray());
            boolean result = signature.verify(signatureValue);
            if (false == result) {
                SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                        signingCertificate, signatureValue);
                this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
                throw new SecurityException("signature incorrect");
            }
        } catch (Exception e) {
            LOG.debug("signature verification error: " + e.getMessage());
            SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE,
                    signingCertificate, signatureValue);
            this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
            throw new ServletException("signature verification error: " + e.getMessage(), e);
        }
    }

    SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain);
    try {
        this.signatureEvent.select(contextQualifier).fire(signatureEvent);
    } catch (ExpiredCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED);
    } catch (RevokedCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED);
    } catch (TrustCertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED);
    } catch (CertificateSecurityException e) {
        return new FinishedMessage(ErrorCode.CERTIFICATE);
    }

    if (null != signatureEvent.getError()) {
        SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate);
        this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent);
        return new FinishedMessage(signatureEvent.getError());
    }
    return new FinishedMessage();
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public static String[] getCNs(final X509Certificate cert) {
    final LinkedList<String> cnList = new LinkedList<String>();
    /*/*from www.j  a  v  a  2s .c o  m*/
      Sebastian Hauer's original StrictSSLProtocolSocketFactory used
      getName() and had the following comment:
            
        Parses a X.500 distinguished name for the value of the
        "Common Name" field.  This is done a bit sloppy right
         now and should probably be done a bit more according to
        <code>RFC 2253</code>.
            
       I've noticed that toString() seems to do a better job than
       getName() on these X500Principal objects, so I'm hoping that
       addresses Sebastian's concern.
            
       For example, getName() gives me this:
       1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
            
       whereas toString() gives me this:
       EMAILADDRESS=juliusdavies@cucbc.com
            
       Looks like toString() even works with non-ascii domain names!
       I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
    */

    final String subjectPrincipal = cert.getSubjectX500Principal().toString();
    final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+");
    while (st.hasMoreTokens()) {
        final String tok = st.nextToken().trim();
        if (tok.length() > 3) {
            if (tok.substring(0, 3).equalsIgnoreCase("CN=")) {
                cnList.add(tok.substring(3));
            }
        }
    }
    if (!cnList.isEmpty()) {
        final String[] cns = new String[cnList.size()];
        cnList.toArray(cns);
        return cns;
    } else {
        return null;
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 *//*from   w  w  w .  ja v a2s . c  om*/
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}