List of usage examples for java.security.cert X509Certificate getSubjectX500Principal
public X500Principal getSubjectX500Principal()
From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * Throw an illegal state exception with a invalid host cert message. * //w ww .j a v a 2 s . co m * @param pass Password * @param keystore Keystore * @param host Host destination */ protected void invalidHostCert(char[] pass, File keystore, GvNix509TrustManager tm, String host) { StringBuffer msg = new StringBuffer("There is not access to the WSDL."); X509Certificate[] certs = getCerts(tm, host, keystore, pass); if (certs != null) { msg.append(" Maybe the emited certificate does not match the hostname where WSDL resides.\n"); for (X509Certificate x509Certificate : certs) { // X.500 distinguished name String dn = x509Certificate.getSubjectX500Principal().getName(); // X.500 common name from distinguished name String cn = getCn(dn); if (cn != null) { msg.append(" * Possible hostname: ".concat(cn).concat("\n")); } else msg.append(" * Possible hostname (check Cert. Distinguished name): ".concat(dn).concat("\n")); } } throw new IllegalStateException(msg.toString()); }
From source file:com.vmware.identity.interop.ldap.SslX509EqualityMatchVerificationCallback.java
@Override public boolean isTrustedCertificate(X509Certificate cert) { boolean certValidationResult = false; String fingerprint = ""; try {// w w w . java 2 s .c o m fingerprint = SslUtil.computeHexCertificateThumbprint(cert); } catch (Exception e) { log.info("Can not calculate thumbprint"); } try { if (this.trustedCertificates == null || trustedCertificates.size() == 0) { log.error(String.format( "Server SSL certificate verification failed for [Subject: %s] [SHA1 Fingerprint: %s]. Trusted certificates store is empty.", cert.getSubjectX500Principal().getName(), fingerprint)); } else { cert.checkValidity(); if (trustedCertificates.contains(cert)) { certValidationResult = true; } else { log.error(String.format( "Server SSL certificate verification failed for [Subject: %s] [SHA1 Fingerprint: %s].: No match found in the trusted certificates store.", cert.getSubjectX500Principal().getName(), fingerprint)); } } } catch (CertificateExpiredException | CertificateNotYetValidException e) { log.error(String.format( "Server SSL certificate verification failed for [Subject: %s] [SHA1 Fingerprint: %s].", cert.getSubjectX500Principal().getName(), fingerprint), e); } return certValidationResult; }
From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java
@Override public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {/* ww w .ja v a 2 s .c om*/ X509Certificate issuer = issuers.get(0); ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.CRL, CertificateValidity.UNKNOWN); try { Principal subjectX500Principal = certificate.getSubjectX500Principal(); String crlURL = getCrlUri(certificate); if (crlURL == null) { log.error("CRL's URL for '" + subjectX500Principal + "' is empty"); return status; } log.debug("CRL's URL for '" + subjectX500Principal + "' is '" + crlURL + "'"); X509CRL x509crl = getCrl(crlURL); if (!validateCRL(x509crl, certificate, issuer, validationDate)) { log.error("The CRL is not valid!"); status.setValidity(CertificateValidity.INVALID); return status; } X509CRLEntry crlEntry = x509crl.getRevokedCertificate(certificate.getSerialNumber()); if (crlEntry == null) { log.debug("CRL status is valid for '" + subjectX500Principal + "'"); status.setValidity(CertificateValidity.VALID); } else if (crlEntry.getRevocationDate().after(validationDate)) { log.warn("CRL revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate); status.setRevocationObjectIssuingTime(x509crl.getThisUpdate()); status.setValidity(CertificateValidity.VALID); } else { log.info("CRL for certificate '" + subjectX500Principal + "' is revoked since " + crlEntry.getRevocationDate()); status.setRevocationObjectIssuingTime(x509crl.getThisUpdate()); status.setRevocationDate(crlEntry.getRevocationDate()); status.setValidity(CertificateValidity.REVOKED); } } catch (Exception ex) { log.error("CRL exception: ", ex); } return status; }
From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java
/** * Sets the input for this composite. //from w ww. jav a 2s . c om * * @param certificateChain certificate chain input */ public void setInput(X509Certificate[] certificateChain) { X509Certificate certificate = certificateChain[0]; X500Principal issuedToPrincipal = certificate.getSubjectX500Principal(); Map<String, String> issuedToAttributes = getAttributeMap(issuedToPrincipal); issuedToCN.setText(issuedToAttributes.get("CN")); //$NON-NLS-1$ issuedToO.setText(issuedToAttributes.get("O")); //$NON-NLS-1$ issuedToOU.setText(issuedToAttributes.get("OU")); //$NON-NLS-1$ serialNumber.setText(certificate.getSerialNumber().toString(16)); X500Principal issuedFromPrincipal = certificate.getIssuerX500Principal(); Map<String, String> issuedFromAttributes = getAttributeMap(issuedFromPrincipal); issuedByCN.setText(issuedFromAttributes.get("CN")); //$NON-NLS-1$ issuedByO.setText(issuedFromAttributes.get("O")); //$NON-NLS-1$ issuedByOU.setText(issuedFromAttributes.get("OU")); //$NON-NLS-1$ issuesOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotBefore())); expiresOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotAfter())); byte[] encoded2 = null; try { encoded2 = certificate.getEncoded(); } catch (CertificateEncodingException e) { } byte[] md5 = DigestUtils.md5(encoded2); String md5HexString = getHexString(md5); fingerprintMD5.setText(md5HexString); byte[] sha = DigestUtils.sha(encoded2); String shaHexString = getHexString(sha); fingerprintSHA1.setText(shaHexString); // Details: certificate chain CertificateChainItem parentItem = null; CertificateChainItem certificateItem = null; for (X509Certificate cert : certificateChain) { CertificateChainItem item = new CertificateChainItem(cert); if (parentItem != null) { item.child = parentItem; parentItem.parent = item; } if (certificateItem == null) { certificateItem = item; } parentItem = item; } hierarchyTreeViewer.setInput(new CertificateChainItem[] { parentItem }); hierarchyTreeViewer.expandAll(); hierarchyTreeViewer.setSelection(new StructuredSelection(certificateItem), true); // Details: certificateTree.removeAll(); populateCertificateTree(); valueText.setText(StringUtils.EMPTY); }
From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java
/** * Gets the trusted responder certificate. The response contains the responder certificate, however we cannot blindly trust it. Instead, we use a configured trusted CA. If the responder * certificate is a trusted CA, then we can use it. If the responder certificate is not directly trusted, we still may be able to trust it if it was issued by the same CA that issued the subject * certificate. Other various checks may be required (this portion is currently not implemented). * * @param responderCertificateHolder cert * @param issuerCertificate cert * @return cert/* ww w .jav a2s .c om*/ */ private X509Certificate getTrustedResponderCertificate(final X509CertificateHolder responderCertificateHolder, final X509Certificate issuerCertificate) throws CertificateException { // look for the responder's certificate specifically final X509Certificate responderCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(responderCertificateHolder); final String trustedCAName = responderCertificate.getSubjectX500Principal().getName(); if (trustedCAs.containsKey(trustedCAName)) { return trustedCAs.get(trustedCAName); } // if the responder certificate was issued by the same CA that issued the subject certificate we may be able to use that... final X500Principal issuerCA = issuerCertificate.getSubjectX500Principal(); if (responderCertificate.getIssuerX500Principal().equals(issuerCA)) { // perform a number of verification steps... TODO... from sun.security.provider.certpath.OCSPResponse.java... currently incomplete... // try { // // ensure appropriate key usage // final List<String> keyUsage = responderCertificate.getExtendedKeyUsage(); // if (keyUsage == null || !keyUsage.contains(KP_OCSP_SIGNING_OID)) { // return null; // } // // // ensure the certificate is valid // responderCertificate.checkValidity(); // // // verify the signature // responderCertificate.verify(issuerCertificate.getPublicKey()); // // return responderCertificate; // } catch (final CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) { // return null; // } return null; } else { return null; } }
From source file:org.cesecore.audit.log.SecurityEventsLoggerSessionBeanTest.java
@Test public void test08Authorization() throws Exception { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); X509Certificate certificate = CertTools.genSelfCert( "C=SE,O=Test,CN=Test SecurityEventsLoggerSessionTestNoAuth", 365, null, keys.getPrivate(), keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); Set<X509Certificate> credentials = new HashSet<X509Certificate>(); credentials.add(certificate);//from ww w. ja v a2 s.co m Set<X500Principal> principals = new HashSet<X500Principal>(); principals.add(certificate.getSubjectX500Principal()); AuthenticationToken adminTokenNoAuth = new X509CertificateAuthenticationToken(principals, credentials); try { securityEventsLogger.log(adminTokenNoAuth, EventTypes.AUTHENTICATION, EventStatus.SUCCESS, ModuleTypes.AUTHENTICATION, ServiceTypes.CORE); fail("should throw"); } catch (AuthorizationDeniedException e) { // NOPMD: ignore this is what we want } }
From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultX509TrustManager.java
/** * {@inheritDoc}/*from w ww . j av a2 s. com*/ */ @Override public void checkServerTrusted(X509Certificate[] certificates, final String authType) throws CertificateException { if (certificates != null && certificates.length > 0) { /* * See if the terminal certificate in the chain is known to us (we * have its certificate.) If so, we can add our certificate to be * the last in the list. * * This emulates sending the certificate in the server's chain, * without making the server team do any actual work. */ final X509Certificate terminalCertificate = certificates[certificates.length - 1]; /* * Make sure the terminal certificate is not self-signed. We cannot * possibly have an issuer certificate to add if the terminal * certificate is self-signed, and we may cause problems with the * certificate validation. */ if (!terminalCertificate.getIssuerX500Principal() .equals(terminalCertificate.getSubjectX500Principal())) { for (final X509Certificate certificateAddition : certificateAdditions) { /* * If this certificate was issued by our known-good * principal, and its issuer is not its principal (ie, it is * not self-signed), then include it. */ if (terminalCertificate.getIssuerX500Principal() .equals(certificateAddition.getSubjectX500Principal())) { log.info(MessageFormat.format("Including certificate for {0}", //$NON-NLS-1$ certificateAddition.getSubjectX500Principal())); /* * Rewrite the certificate array to include our trusted * certificate at the end of the chain. */ final X509Certificate[] newCertificates = new X509Certificate[certificates.length + 1]; for (int i = 0; i < certificates.length; i++) { newCertificates[i] = certificates[i]; } newCertificates[newCertificates.length - 1] = certificateAddition; certificates = newCertificates; break; } } } } standardTrustManager.checkServerTrusted(certificates, authType); }
From source file:test.integ.be.fedict.trust.util.TestUtils.java
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, PrivateKey issuerPrivateKey, X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, String signatureAlgorithm, boolean includeAuthorityKeyIdentifier, boolean caCert, boolean timeStampingPurpose, String ocspUri, String crlUri, KeyUsage keyUsage, BigInteger serialNumber) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { String finalSignatureAlgorithm = signatureAlgorithm; if (null == signatureAlgorithm) { finalSignatureAlgorithm = "SHA512WithRSAEncryption"; }//from w ww . ja v a 2 s .c om X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset(); certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(finalSignatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN; if (null != issuerCert) { issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().getName()); } else { issuerDN = new X509Principal(subjectDn); } certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(serialNumber); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; if (null != issuerCert) { issuerPublicKey = issuerCert.getPublicKey(); } else { issuerPublicKey = subjectPublicKey; } if (includeAuthorityKeyIdentifier) { certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); } certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(caCert)); if (timeStampingPurpose) { certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); } if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false, authorityInformationAccess); } if (null != crlUri) { GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlUri)); GeneralNames gns = new GeneralNames(gn); DistributionPointName dpn = new DistributionPointName(0, gns); DistributionPoint distp = new DistributionPoint(dpn, null, null); certificateGenerator.addExtension(X509Extensions.CRLDistributionPoints, false, new DERSequence(distp)); } if (null != keyUsage) { certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage); } return certificateGenerator.generate(issuerPrivateKey); // /* // * Make sure the default certificate provider is active. // */ // CertificateFactory certificateFactory = CertificateFactory // .getInstance("X.509"); // certificate = (X509Certificate) certificateFactory // .generateCertificate(new ByteArrayInputStream(certificate // .getEncoded())); // // return certificate; }
From source file:be.fedict.trust.service.bean.HarvesterMDB.java
private void processHarvestMessage(HarvestMessage harvestMessage) { if (null == harvestMessage) { return;//from ww w . j ava 2 s . c om } String caName = harvestMessage.getCaName(); boolean update = harvestMessage.isUpdate(); String crlFilePath = harvestMessage.getCrlFile(); File crlFile = new File(crlFilePath); LOG.debug("processHarvestMessage - Don't have CA's Serial Number??"); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); deleteCrlFile(crlFile); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { /* * Possible that another harvester instance already activated or is * processing the CA cache in the meanwhile. */ LOG.debug("CA status not marked for processing"); deleteCrlFile(crlFile); return; } Date validationDate = new Date(); X509Certificate issuerCertificate = certificateAuthority.getCertificate(); Date notAfter = issuerCertificate.getNotAfter(); if (validationDate.after(notAfter)) { LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal()); deleteCrlFile(crlFile); return; } FileInputStream crlInputStream; try { crlInputStream = new FileInputStream(crlFile); } catch (FileNotFoundException e) { LOG.error("CRL file does not exist: " + crlFilePath); return; } X509CRL crl; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); crl = (X509CRL) certificateFactory.generateCRL(crlInputStream); } catch (Exception e) { LOG.error("BC error: " + e.getMessage(), e); deleteCrlFile(crlFile); return; } LOG.debug("checking integrity CRL..."); boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate); if (!crlValid) { this.auditDAO.logAudit("Invalid CRL for CA=" + caName); deleteCrlFile(crlFile); return; } BigInteger crlNumber = getCrlNumber(crl); LOG.debug("CRL number: " + crlNumber); BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName); if (null != currentCrlNumber) { LOG.debug("CRL number in database: " + currentCrlNumber); } if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0 && certificateAuthority.getStatus() == Status.ACTIVE) { // current CRL cache is higher or equal, no update needed LOG.debug("current CA cache is new enough."); deleteCrlFile(crlFile); return; } List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO .getRevokedCertificates(caName); LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size()); Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>(); for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) { String serialNumber = revokedCertificateEntity.getPk().getSerialNumber(); revokedCertificatesMap.put(serialNumber, revokedCertificateEntity); } LOG.debug("processing CRL... " + caName); boolean isIndirect; Enumeration revokedCertificatesEnum; try { isIndirect = isIndirectCRL(crl); revokedCertificatesEnum = getRevokedCertificatesEnum(crl); } catch (Exception e) { this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName); this.failures++; throw new RuntimeException(e); } int entries = 0; if (revokedCertificatesEnum.hasMoreElements()) { /* * Split up persisting the crl entries to avoid memory issues. */ Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>(); X500Principal previousCertificateIssuer = crl.getIssuerX500Principal(); int added = 0; while (revokedCertificatesEnum.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement(); X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779)); X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name); previousCertificateIssuer = revokedCertificate.getCertificateIssuer(); revokedCertsBatch.add(revokedCertificate); added++; if (added == BATCH_SIZE) { /* * Persist batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); revokedCertsBatch.clear(); added = 0; } } /* * Persist final batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); /* * Cleanup redundant CRL entries */ if (null != crlNumber) { this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber, crl.getIssuerX500Principal().toString()); } } deleteCrlFile(crlFile); LOG.debug("CRL this update: " + crl.getThisUpdate()); LOG.debug("CRL next update: " + crl.getNextUpdate()); certificateAuthority.setStatus(Status.ACTIVE); certificateAuthority.setThisUpdate(crl.getThisUpdate()); certificateAuthority.setNextUpdate(crl.getNextUpdate()); LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")"); }
From source file:mitm.common.security.certificate.X509CertificateInspector.java
public X509CertificateInspector(X509Certificate certificate) throws CertificateParsingException, IOException { super(certificate); this.certificate = certificate; subjectAltNames = new AltNamesInspector(certificate); subjectInspector = new X500PrincipalInspector(certificate.getSubjectX500Principal()); issuerInspector = new X500PrincipalInspector(certificate.getIssuerX500Principal()); }