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.unit.be.fedict.eid.dss.document.ooxml.OOXMLDSSDocumentServiceTest.java

/**
 * When you register the root-signed Belgium Root CA2 within Windows Trust
 * Store, Office 2010 SP1 will use a certificate chain up to GlobalSign Root
 * CA instead of the self-signed Belgium Root CA2.
 * //from  w ww  .j a va2 s  . c  o m
 * @throws Exception
 */
@Test
public void testVerifySignaturesTest123Office() throws Exception {
    // setup
    OOXMLDSSDocumentService testedInstance = new OOXMLDSSDocumentService();
    byte[] document = IOUtils.toByteArray(
            OOXMLDSSDocumentServiceTest.class.getResourceAsStream("/Office2010-SP1-GlobalSign.docx"));

    DSSDocumentContext mockContext = EasyMock.createMock(DSSDocumentContext.class);
    Capture<List<X509Certificate>> certificateChainCapture = new Capture<List<X509Certificate>>();
    Capture<Date> validationDateCapture = new Capture<Date>();
    Capture<List<OCSPResp>> ocspResponsesCapture = new Capture<List<OCSPResp>>();
    Capture<List<X509CRL>> crlsCapture = new Capture<List<X509CRL>>();
    Capture<TimeStampToken> timeStampTokenCapture = new Capture<TimeStampToken>();
    mockContext.validate(EasyMock.capture(certificateChainCapture), EasyMock.capture(validationDateCapture),
            EasyMock.capture(ocspResponsesCapture), EasyMock.capture(crlsCapture));
    mockContext.validate(EasyMock.capture(timeStampTokenCapture));
    mockContext.validate(EasyMock.capture(timeStampTokenCapture));
    expect(mockContext.getTimestampMaxOffset()).andReturn(33 * 1000L);
    expect(mockContext.getMaxGracePeriod()).andReturn(1000L * 60 * 60 * 24 * 7);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    testedInstance.init(mockContext, "mime-type");
    List<SignatureInfo> signatureInfos = testedInstance.verifySignatures(document, null);

    // verify
    EasyMock.verify(mockContext);
    assertNotNull(signatureInfos);
    assertEquals(1, signatureInfos.size());
    SignatureInfo signatureInfo = signatureInfos.get(0);
    assertNotNull(signatureInfo.getSigner());
    assertNotNull(signatureInfo.getSigningTime());
    LOG.debug("signing time: " + signatureInfo.getSigningTime());
    assertEquals(signatureInfo.getSigningTime(), validationDateCapture.getValue());
    assertEquals(signatureInfo.getSigner(), certificateChainCapture.getValue().get(0));
    assertEquals(1, ocspResponsesCapture.getValue().size());
    assertEquals(2, crlsCapture.getValue().size());
    List<X509CRL> crls = crlsCapture.getValue();
    for (X509CRL crl : crls) {
        LOG.debug("CRL: " + crl.getIssuerX500Principal());
    }
    assertEquals(4, certificateChainCapture.getValue().size());
    for (X509Certificate certificate : certificateChainCapture.getValue()) {
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
    }
}

From source file:org.waveprotocol.wave.crypto.WaveSignatureVerifier.java

/**
 * Verifies that the given certificate was issued to the given authority.
 * @param authority the authority to which the certificate was issued,
 *   e.g., a domain name.//w  ww . j  a  va 2s  .  c o m
 * @param certificate the {@link X509Certificate}
 * @throws SignatureException if the authority doesn't match the certificate.
 */
private void verifyMatchingAuthority(String authority, X509Certificate certificate) throws SignatureException {

    String cn = getCommonNameFromDistinguishedName(certificate.getSubjectX500Principal().getName());

    if (cn == null) {
        throw new SignatureException(
                "no common name found in signer " + "certificate " + certificate.getSubjectDN().toString());
    }

    if (cn.equals(authority)) {
        return;
    }

    if (authorityMatchesSubjectAlternativeNames(authority, certificate)) {
        return;
    }

    if (authorityMatchesWildcardCN(authority, cn)) {
        return;
    }

    throw new SignatureException(
            "expected " + authority + " as CN or alternative name in cert, but didn't find it");

}

From source file:pl.psnc.synat.wrdz.ru.registries.RemoteRegistryManagerBean.java

@Override
public RemoteRegistry createRemoteRegistry(RemoteRegistry added, String certificate)
        throws EntryCreationException {
    RemoteRegistryFilterFactory filterFactory = remoteRegistryDao.createQueryModifier().getQueryFilterFactory();
    List<RemoteRegistry> list = remoteRegistryDao.findBy(filterFactory.byLocationUrl(added.getLocationUrl()),
            false);/* w w  w . j a v  a2s.  c o m*/
    if (list != null && list.size() > 0) {
        throw new EntryCreationException("Registry with given location already extists, try to modify it.");
    }

    X509Certificate x509Certificate = loadCertificate(certificate);
    CertificateInformation information = CertificateInformation
            .parseNameString(x509Certificate.getSubjectX500Principal().getName());

    String username = information.getDisplayName().replaceAll(" ", "");
    userManager.createSystemUser(username, certificate, information.getDisplayName(),
            information.getOrganizationName());

    added.setUsername(username);

    remoteRegistryDao.persist(added);
    return added;
}

From source file:test.integ.be.e_contract.mycarenet.etk.EtkDepotClientTest.java

@Test
public void testClient() throws Exception {
    EtkDepotClient etkDepotClient = new EtkDepotClient(
            "https://wwwacc.ehealth.fgov.be/etkdepot_1_0/EtkDepotService");

    BeIDCards beIDCards = new BeIDCards();
    BeIDCard beIDCard = beIDCards.getOneBeIDCard();
    byte[] identityData = beIDCard.readFile(FileType.Identity);
    Identity identity = TlvParser.parse(identityData, Identity.class);

    String inss = identity.getNationalNumber();
    byte[] etk = etkDepotClient.getEtk("SSIN", inss);

    assertNotNull(etk);//  ww  w  .j av  a  2 s  .c  o m

    File tmpFile = File.createTempFile("etk-", ".der");
    FileUtils.writeByteArrayToFile(tmpFile, etk);
    LOG.debug("ETK file: " + tmpFile.getAbsolutePath());

    EncryptionToken encryptionToken = new EncryptionToken(etk);

    X509Certificate encryptionCertificate = encryptionToken.getEncryptionCertificate();
    LOG.debug("encryption certificate issuer: " + encryptionCertificate.getIssuerX500Principal());
    LOG.debug("encryption certificate subject: " + encryptionCertificate.getSubjectX500Principal());

    X509Certificate authenticationCertificate = encryptionToken.getAuthenticationCertificate();
    LOG.debug("authentication certificate issuer: " + authenticationCertificate.getIssuerX500Principal());
    LOG.debug("authentication certificate subject: " + authenticationCertificate.getSubjectX500Principal());
}

From source file:net.sf.dsig.verify.XmldsigVerifier.java

public boolean isValid() throws VerificationException, NetworkAccessException {
    X509Certificate certificate = getCertificateChain()[0];
    String subjectName = certificate.getSubjectX500Principal().getName();

    try {/*from w w  w.j  a  v a2 s .c om*/
        certificate.checkValidity();
    } catch (CertificateExpiredException ignored) {
        return false;
    } catch (CertificateNotYetValidException ignored) {
        return false;
    }

    if (getSubjectMatchingPattern() != null && !getSubjectMatchingPattern().matcher(subjectName).matches()) {
        return false;
    }

    if (keyUsageRestrictions != null && !KeyUsageHelper.validateKeyUsage(certificate, keyUsageRestrictions)) {
        return false;
    }

    if (crlHelper != null && !crlHelper.isValid(certificate)) {
        logger.warn("CRL validation failed");

        return false;
    }

    if (ocspHelper != null && !ocspHelper.isValid(certificate)) {
        logger.warn("OCSP validation failed");

        return false;
    }

    return true;
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);/*from w ww  . j a va  2  s  .com*/
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:org.dcache.ftp.client.extended.GridFTPControlChannel.java

/**
 * Performs authentication with specified user credentials and
 * a specific username (assuming the user dn maps to the passed username).
 *
 * @throws IOException     on i/o error/* w w  w  .  j ava  2 s . c o m*/
 * @throws ServerException on server refusal or faulty server behavior
 */
private DssContext authenticate(DssContextFactory factory, String expectedHostName)
        throws IOException, ServerException {
    DssContext context;
    try {
        try {
            Reply reply = inner.exchange(new Command("AUTH", "GSSAPI"));
            if (!Reply.isPositiveIntermediate(reply)) {
                throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                        "Server refused GSSAPI authentication.");
            }
        } catch (FTPReplyParseException rpe) {
            throw ServerException.embedFTPReplyParseException(rpe, "Received faulty reply to AUTH GSSAPI.");
        }

        context = factory.create(inner.getRemoteAddress(), inner.getLocalAddress());

        Reply reply;
        byte[] inToken = new byte[0];
        do {
            byte[] outToken = context.init(inToken);
            reply = inner.exchange(new Command("ADAT",
                    BaseEncoding.base64().encode(outToken != null ? outToken : new byte[0])));
            if (reply.getMessage().startsWith("ADAT=")) {
                inToken = BaseEncoding.base64().decode(reply.getMessage().substring(5));
            } else {
                inToken = new byte[0];
            }
        } while (Reply.isPositiveIntermediate(reply) && !context.isEstablished());

        if (!Reply.isPositiveCompletion(reply)) {
            throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                    "Server failed GSI handshake.");
        }

        if (inToken.length > 0 || !context.isEstablished()) {
            byte[] outToken = context.init(inToken);
            if (outToken != null || !context.isEstablished()) {
                throw new ServerException(ServerException.WRONG_PROTOCOL,
                        "Unexpected GSI handshake completion.");
            }
        }

        SSLSession session = ((SslEngineDssContext) context).getSSLSession();
        if (!this.hostnameVerifier.verify(expectedHostName, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + expectedHostName + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
    } catch (FTPReplyParseException e) {
        throw ServerException.embedFTPReplyParseException(e, "Received faulty reply to ADAT.");
    }
    return context;
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String
 *      authType)/*from www. j  a  v a2  s.c  om*/
 */
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // use delegate for client certificates
    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate chain:");
        if (chain != null) {
            for (int i = 0; i < chain.length; i++) {
                X509Certificate certificate = chain[i];
                LOG.debug(i + ": S: " + certificate.getSubjectX500Principal());
                LOG.debug(i + ": I: " + certificate.getIssuerX500Principal());
            }
        }
    }
    defaultTrustManager_.checkClientTrusted(chain, authType);
}

From source file:org.eclipse.gyrex.http.jetty.internal.admin.CertificateDefinition.java

@Override
public String getInfo() {
    try {//from  w w w .j  a  v a2 s . c  o m
        final StrBuilder certInfo = new StrBuilder();
        final KeyStore ks = getKeyStore();
        final Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            final String alias = (String) aliases.nextElement();
            if (!certInfo.isEmpty()) {
                certInfo.append(", ");
            }
            //            certInfo.append(alias).append(": ");
            if (ks.isKeyEntry(alias)) {
                Certificate[] chain = ks.getCertificateChain(alias);
                if (null == chain) {
                    final Certificate certificate = ks.getCertificate(alias);
                    chain = new Certificate[] { certificate };
                }
                for (int i = 0; i < chain.length; i++) {
                    if (i > 0) {
                        certInfo.append(" ");
                    }
                    final Certificate certificate = chain[i];
                    if (certificate instanceof X509Certificate) {
                        final X509Certificate x509 = (X509Certificate) certificate;
                        final X500PrincipalHelper helper = new X500PrincipalHelper(
                                x509.getSubjectX500Principal());
                        certInfo.append(helper.getCN());
                        certInfo.append(", valid till ").append(TO_STRING_FORMAT.format(x509.getNotAfter()));
                    } else {
                        certInfo.append("INVALID");
                    }
                }
            } else {
                certInfo.append("IGNORED");
            }
        }
        return StringUtils.trim(certInfo.toString());
    } catch (final Exception e) {
        return ExceptionUtils.getRootCauseMessage(e);
    }
}

From source file:org.taverna.server.master.localworker.SecurityContextDelegateImpl.java

/**
 * Adds a key-pair to the current keystore.
 * //  w  w  w . j  av  a2  s.c o  m
 * @param c
 *            The key-pair.
 * @throws KeyStoreException
 */
protected void addKeypairToKeystore(Credential.KeyPair c) throws KeyStoreException {
    X509Certificate subjectCert = (X509Certificate) c.loadedTrustChain[0];
    String alias = format("keypair#%s#%s#%s", getPrincipalName(subjectCert.getSubjectX500Principal()),
            getPrincipalName(subjectCert.getIssuerX500Principal()), x500Utils.getSerial(subjectCert));
    addKeypairToKeystore(alias, c);
}