List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public String writePEMCertFile(String path) { String correctedPath = StringUtils.trimToEmpty(path); File certFilePath;/*from www . j av a2s .c o m*/ if (StringUtils.isNotBlank(correctedPath)) { certFilePath = new File(correctedPath); boolean pathExists = certFilePath.exists(); if (!pathExists) { pathExists = certFilePath.mkdirs(); } if (pathExists && !correctedPath.endsWith("/")) { correctedPath = correctedPath + "/"; } } InputStream certInputStream = IOUtils.toInputStream(cert); X509Certificate trustedCert; try { trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certInputStream); certFilePath = new File( correctedPath + trustedCert.getSubjectDN().getName().split(",")[0].substring(2) + ".crt"); if (!certFilePath.exists()) { certFilePath.createNewFile(); FileWriter writer = new FileWriter(certFilePath, true); writer.write(cert); writer.flush(); writer.close(); return certFilePath.getAbsolutePath(); } else { logger.error("File allready exists!"); } } catch (IOException e) { logger.error("An IOException occurred: ", e); } catch (CertificateException e1) { logger.error("A CertificateException occurred: ", e1); } return null; }
From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler.java
protected final boolean doAuthentication(final Credentials credentials) throws AuthenticationException { final X509CertificateCredentials x509Credentials = (X509CertificateCredentials) credentials; final X509Certificate[] certificates = x509Credentials.getCertificates(); /*//from w ww . j ava2 s . com * the certificate that was fully authenticated succesfully will be set * as the user credentials for CAS last certificate that can be set is * the end-user certificate */ X509Certificate certificateCredentialsCandidate = null; // flag to check whether a trusted issuer is in the certificate chain boolean hasTrustedIssuerInChain = false; /* * reverse transversal of certificates (should be from root to end-user * cert) */ for (int i = (certificates.length - 1); i >= 0; i--) { final X509Certificate certificate = certificates[i]; try { final Principal issuerPrincipal = certificate.getIssuerDN(); // flag that is set when this cert is an end user cert (no CA // cert) boolean isEndUserCertificate = false; if (log.isDebugEnabled()) { log.debug("--examining cert[" + certificate.getSerialNumber().toString() + "] " + certificate.getSubjectDN() + "\"" + " from issuer \"" + issuerPrincipal.getName() + "\""); } // check basic validity of the current certificate certificate.checkValidity(); log.debug("certificate is valid"); // initial check for trusted issuer in certificate chain // final check is done outside for loop if (isCertificateFromTrustedIssuer(issuerPrincipal)) { hasTrustedIssuerInChain = true; log.debug("certificate was issued by trusted issuer"); } // getBasicConstraints returns pathLenContraint which is // >=0 when this is a CA cert and -1 when it's not int pathLength = certificate.getBasicConstraints(); if (pathLength != -1) { log.debug("this is a CA certificate"); // check pathLength when CA cert //if unlimited/unspecified and unlimited/unspecified not allowed: warn+stop if (pathLength == Integer.MAX_VALUE && this.maxPathLength_allowUnspecified != true) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength not specified" + " and unlimited/unspecified not allowed by config [see maxPathLength_allow_unlimited]"); } return false; //else if more than allowed length but not unlimited/unspecified: warn+stop } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength [" + pathLength + "] is more than allowed by config [" + this.maxPathLength + "]"); } return false; } } else { isEndUserCertificate = true; log.debug("this is an end-user certificate"); } /* * set this certificate as the user credentials if there is an * issuer in the cert (always so if valid cert) and this is an * end-user or CA certificate (so not a CA cert) and optional * KeyUsage check */ if (issuerPrincipal != null && isEndUserCertificate && this.doesCertificateSubjectDnMatchPattern(certificate.getSubjectDN()) && (!this.checkKeyUsage || (this.checkKeyUsage && this.doesCertificateKeyUsageMatch(certificate)))) { if (log.isDebugEnabled()) { log.debug("cert[" + certificate.getSerialNumber().toString() + "] ok, setting as credentials candidate"); } certificateCredentialsCandidate = certificate; } } catch (final CertificateExpiredException e) { log.warn("authentication failed; certficiate expired [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } catch (final CertificateNotYetValidException e) { log.warn("authentication failed; certficate not yet valid [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } } // check whether one of the certificates in the chain was // from the trusted issuer; else => fail auth if (certificateCredentialsCandidate != null && hasTrustedIssuerInChain) { if (log.isInfoEnabled()) { log.info("authentication OK; SSL client authentication data meets criteria for cert[" + certificateCredentialsCandidate.getSerialNumber().toString() + "]"); } x509Credentials.setCertificate(certificateCredentialsCandidate); return true; } if (log.isInfoEnabled()) { if (!hasTrustedIssuerInChain) { log.info("client cert did not have trusted issuer pattern \"" + this.regExTrustedIssuerDnPattern.pattern() + "\" in chain; authentication failed"); } else { log.info("authentication failed; SSL client authentication data doesn't meet criteria"); } } return false; }
From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
/** * Runs the command//from w w w.ja v a2s . com * * @throws IllegalAdminCommandException Error in command args * @throws ErrorAdminCommandException Error running command */ public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException { try { CertRequest certReq = genCertReq(userDN, null); PKIMessage certMsg = genPKIMessage(false, certReq); if (certMsg == null) { getPrintStream().println("No certificate request."); System.exit(-1); } AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption); certMsg.getHeader().setProtectionAlg(pAlg); certMsg.getHeader().setSenderKID(new DEROctetString("CMPEnduser".getBytes())); PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey); addExtraCert(signedMsg, innerCertificate); if (signedMsg == null) { getPrintStream().println("No protected message."); System.exit(-1); } PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2), new GeneralName(new X509Name("CN=CMSSender,C=SE")), new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(nonce)); //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg))); PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody); PKIMessage cmsMessage = signPKIMessage(myPKIMessage, outerSignKey); reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(cmsMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmp(ba); if (resp == null || resp.length <= 0) { getPrintStream().println("No response message."); System.exit(-1); } /* if ( !checkCmpResponseGeneral(resp, true) ) { System.exit(-1); } */ final X509Certificate cert = checkCmpCertRepMessage(resp, reqId); if (cert == null) { getPrintStream().println("No certificate was created."); System.exit(-1); } getPrintStream().println("Certificate for " + userDN + " was created with the serialnumber: " + cert.getSerialNumber().toString()); if (createsCertsPath != null) { String filename = CertTools.getPartFromDN(cert.getSubjectDN().toString(), "CN") + ".pem"; writeCertificate(cert, createsCertsPath, filename); getPrintStream().println("Certificate was written to: " + createsCertsPath + "/" + filename); } } catch (IOException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (InvalidKeyException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchAlgorithmException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (SignatureException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchProviderException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (CertificateEncodingException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (Exception e) { e.printStackTrace(getPrintStream()); System.exit(-1); } getPrintStream().println("Test successfull"); }
From source file:com.bitplan.rest.RestServerImpl.java
/** * show Debug Information for the given request * //ww w . j a v a 2 s . c o m * @param req */ public void showDebug(Request req) { for (String attrName : req.getAttributeNames()) { System.out.println("req attr: " + attrName + "=" + req.getAttribute(attrName)); } Object certobj = req.getAttribute("javax.servlet.request.X509Certificate"); if (certobj != null) { System.out.println("certificate " + certobj.getClass().getName() + " found"); if (certobj instanceof java.security.cert.X509Certificate[]) { java.security.cert.X509Certificate[] certs = (X509Certificate[]) certobj; for (java.security.cert.X509Certificate cert : certs) { System.out.println("issuer DN:" + cert.getIssuerDN().getName()); System.out.println("subject DN: " + cert.getSubjectDN().getName()); } } } for (String headerName : req.getHeaderNames()) { System.out.println("req header: " + headerName + "=" + req.getHeader(headerName)); } }
From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java
protected String resolveUID(X509Certificate cert) throws SSOAuthenticationException { try {// w ww. j ava2s. c o m // If CN is used, UID is CN // If DN is used, we need to resolve it using the credentials store // If Certificate is used, we need to resolve it using the credential store // If Email is used, we need to resolve it using the credential store Principal dn = cert.getSubjectDN(); java.util.Collection an = (java.util.Collection) cert.getSubjectAlternativeNames(); X500Principal x500 = cert.getSubjectX500Principal(); return null; } catch (Exception e) { throw new SSOAuthenticationException(e); } }
From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java
/** * validate the certificate using the selected subject. * * @param subject matched string or the username that uses to authenticate. * @param authenticationContext authenticationContext. * @param cert x509 certificate. * @param claims user claims. *//*w ww . j av a2 s . c o m*/ private void validateUsingSubject(String subject, AuthenticationContext authenticationContext, X509Certificate cert, Map<ClaimMapping, String> claims) throws AuthenticationFailedException { byte[] data; try { data = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new AuthenticationFailedException( "Encoded certificate is not found in the certificate with subjectDN: " + cert.getSubjectDN(), e); } AuthenticatedUser authenticatedUser = getUsername(authenticationContext); if (log.isDebugEnabled()) { log.debug("Getting X509Certificate username"); } if (authenticatedUser != null) { if (log.isDebugEnabled()) { log.debug("Authenticated username is: " + authenticatedUser); } String authenticatedUserName = authenticatedUser.getAuthenticatedSubjectIdentifier(); if (authenticatedUserName.equals(subject)) { addOrValidateCertificate(subject, authenticationContext, data, claims, cert); } else { authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE, X509CertificateConstants.USERNAME_CONFLICT); throw new AuthenticationFailedException( "Couldn't find X509 certificate to this authenticated user: " + authenticatedUserName); } } else { addOrValidateCertificate(subject, authenticationContext, data, claims, cert); } }
From source file:de.duenndns.ssl.MemorizingTrustManager.java
void storeCert(X509Certificate cert) { storeCert(cert.getSubjectDN().toString(), cert); }
From source file:org.signserver.admin.gui.ViewCertificateFrame.java
public ViewCertificateFrame(final List<X509Certificate> certificates) { this.certificates = certificates; this.certificate = certificates.get(0); initComponents();// ww w . j av a2 s . c om chainList.setModel(new AbstractListModel() { @Override public int getSize() { return certificates.size(); } @Override public Object getElementAt(int index) { return certificates.get(index); } }); chainList.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList list, Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { if (value instanceof X509Certificate) { final X509Certificate cert = (X509Certificate) value; value = cert.getSubjectDN().getName(); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } }); chainList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(final ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { viewCertificate((X509Certificate) chainList.getSelectedValue()); } } }); fieldsList.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(final JList list, Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { if (value instanceof Field) { value = ((Field) value).getName(); } return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } }); fieldsList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(final ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { viewFieldValue((Field) fieldsList.getSelectedValue()); } } }); subjectTextArea.setText(certificate.getSubjectDN().getName()); issuerTextArea.setText(certificate.getIssuerDN().getName()); serialNumberField.setText(certificate.getSerialNumber().toString(16)); notBeforeLabel.setText(String.valueOf(certificate.getNotBefore())); notAfterLabel.setText(String.valueOf(certificate.getNotAfter())); String fingerprint = ""; try { fingerprint = calcFingerprint(certificate.getEncoded()); } catch (CertificateEncodingException ex) { LOG.error("Error calculating certificate fingerprint", ex); } fingerprintLabel.setText(fingerprint); usages = new ArrayList<String>(); boolean[] keyUsages = certificate.getKeyUsage(); if (keyUsages != null) { // digitalSignature (0), if (keyUsages[0]) { usages.add("digitalSignature"); } // nonRepudiation (1), if (keyUsages[1]) { usages.add("nonRepudiation"); } // keyEncipherment (2), if (keyUsages[2]) { usages.add("keyEncipherment"); } // dataEncipherment (3), if (keyUsages[3]) { usages.add("dataEncipherment"); } // keyAgreement (4), if (keyUsages[4]) { usages.add("keyAgreement"); } // keyCertSign (5), if (keyUsages[5]) { usages.add("keyCertSign"); } // cRLSign (6), if (keyUsages[6]) { usages.add("cRLSign"); } // encipherOnly (7), if (keyUsages[7]) { usages.add("encipherOnly"); } // decipherOnly if (keyUsages[8]) { usages.add("decipherOnly"); } } try { final List<String> eku = certificate.getExtendedKeyUsage(); if (eku != null) { usages.addAll(eku); } } catch (CertificateParsingException ex) { LOG.error("Error getting extended key usage", ex); } usagesList.setModel(new AbstractListModel() { @Override public int getSize() { return usages.size(); } @Override public Object getElementAt(int index) { return usages.get(index); } }); chainList.setSelectedIndex(0); }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To get the certificate meta data information such as version expiry data * * @param certificate Relevant certificate to get certificate meta data information. * @return Certificate meta data information. *///from ww w. ja va2 s. co m private CertificateInformationDTO getCertificateMetaData(X509Certificate certificate) { CertificateInformationDTO certificateInformation = new CertificateInformationDTO(); certificateInformation .setStatus(certificate.getNotAfter().getTime() > System.currentTimeMillis() ? "Active" : "Expired"); certificateInformation.setFrom(certificate.getNotBefore().toString()); certificateInformation.setTo(certificate.getNotAfter().toString()); certificateInformation.setSubject(certificate.getSubjectDN().toString()); certificateInformation.setVersion(String.valueOf(certificate.getVersion())); return certificateInformation; }
From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java
/** * Comprueba que la respuesta OCSP no ha sido manipulada y es correcta. * // ww w. j a v a 2s . c o m * @param certificadoX509Emisor * @param brep * @throws OCSPException * @throws CertPathValidatorException */ private void checkOCSP(BasicOCSPResp ocspResponse) throws OCSPException, CertPathValidatorException { // Recuperamos la clave pblica esperada con el OCSP firmo la respuesta. X509Certificate certificatePath[] = null; try { certificatePath = ocspResponse.getCerts(BouncyCastleProvider.PROVIDER_NAME); } catch (NoSuchProviderException e) { throw new CertPathValidatorException("La respuesta OCSP no puede ser validada.", e); } // Recuperamos el inicio del camino ( suponemos que el resto de // certificados estara ya if (certificatePath == null || certificatePath.length == 0) { throw new CertPathValidatorException( "No se ha podido encontrar un certificado en la respuesta OCSP. La respuesta OCSP debe ser firmada por el servidor de OCSP."); } X509Certificate certificadoResponseOCSP = certificatePath[0]; // Recuperamos la clave pblica almacenada en nuestros certificados de // confianza. PublicKey keyCertificadoOCSP = getPublicKeyBySubjectName(certificadoResponseOCSP); if (keyCertificadoOCSP == null) { throw new CertPathValidatorException( "No hay un certificado de confianza asociado a al certificado con el que se firmo esta respuesta OCSP. " + certificadoResponseOCSP.getSubjectDN().getName()); } try { if (!ocspResponse.verify(keyCertificadoOCSP, BouncyCastleProvider.PROVIDER_NAME)) { throw new CertPathValidatorException( "La respuesta OCSP no es vlida, La firma no corresponde a un certificado de confianza."); } } catch (NoSuchProviderException e) { throw new CertPathValidatorException("La respuesta OCSP no puede ser validada.", e); } }