List of usage examples for java.security.cert X509Certificate getIssuerDN
public abstract Principal getIssuerDN();
From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java
@Test public void test19RevocationApprovals() throws Exception { log.trace(">test19RevocationApprovals"); final String APPROVINGADMINNAME = "superadmin"; final String TOKENSERIALNUMBER = "42424242"; final String TOKENUSERNAME = "WSTESTTOKENUSER3"; final String ERRORNOTSENTFORAPPROVAL = "The request was never sent for approval."; final String ERRORNOTSUPPORTEDSUCCEEDED = "Reactivation of users is not supported, but succeeded anyway."; // Generate random username and CA name String randomPostfix = Integer.toString(secureRandom.nextInt(999999)); String caname = "wsRevocationCA" + randomPostfix; String username = "wsRevocationUser" + randomPostfix; int cryptoTokenId = 0; int caID = -1; try {//w w w .ja v a2s. c om cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(intAdmin, caname, "1024"); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); caID = RevocationApprovalTest.createApprovalCA(intAdmin, caname, CAInfo.REQ_APPROVAL_REVOCATION, caAdminSessionRemote, caSession, catoken); X509Certificate adminCert = (X509Certificate) certificateStoreSession .findCertificatesByUsername(APPROVINGADMINNAME).iterator().next(); Set<X509Certificate> credentials = new HashSet<X509Certificate>(); credentials.add(adminCert); Set<Principal> principals = new HashSet<Principal>(); principals.add(adminCert.getSubjectX500Principal()); AuthenticationToken approvingAdmin = simpleAuthenticationProvider .authenticate(new AuthenticationSubject(principals, credentials)); //AuthenticationToken approvingAdmin = new X509CertificateAuthenticationToken(principals, credentials); //Admin approvingAdmin = new Admin(adminCert, APPROVINGADMINNAME, null); try { X509Certificate cert = createUserAndCert(username, caID); String issuerdn = cert.getIssuerDN().toString(); String serno = cert.getSerialNumber().toString(16); // revoke via WS and verify response try { ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (WaitingForApprovalException_Exception e1) { } try { ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (ApprovalException_Exception e1) { } RevokeStatus revokestatus = ejbcaraws.checkRevokationStatus(issuerdn, serno); assertNotNull(revokestatus); assertTrue(revokestatus.getReason() == RevokedCertInfo.NOT_REVOKED); // Approve revocation and verify success approveRevocation(intAdmin, approvingAdmin, username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession, approvalExecutionSession, caID); // Try to unrevoke certificate try { ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (WaitingForApprovalException_Exception e) { } try { ejbcaraws.revokeCert(issuerdn, serno, RevokedCertInfo.NOT_REVOKED); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (ApprovalException_Exception e) { } // Approve revocation and verify success approveRevocation(intAdmin, approvingAdmin, username, RevokedCertInfo.NOT_REVOKED, ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession, approvalExecutionSession, caID); // Revoke user try { ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (WaitingForApprovalException_Exception e) { } try { ejbcaraws.revokeUser(username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, false); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (ApprovalException_Exception e) { } // Approve revocation and verify success approveRevocation(intAdmin, approvingAdmin, username, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, ApprovalDataVO.APPROVALTYPE_REVOKEENDENTITY, certificateStoreSession, approvalSession, approvalExecutionSession, caID); // Try to reactivate user try { ejbcaraws.revokeUser(username, RevokedCertInfo.NOT_REVOKED, false); assertTrue(ERRORNOTSUPPORTEDSUCCEEDED, false); } catch (AlreadyRevokedException_Exception e) { } } finally { endEntityManagementSession.deleteUser(intAdmin, username); } try { // Create a hard token issued by this CA createHardToken(TOKENUSERNAME, caname, TOKENSERIALNUMBER); assertTrue(ejbcaraws.existsHardToken(TOKENSERIALNUMBER)); // Revoke token try { ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (WaitingForApprovalException_Exception e) { } try { ejbcaraws.revokeToken(TOKENSERIALNUMBER, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD); assertTrue(ERRORNOTSENTFORAPPROVAL, false); } catch (ApprovalException_Exception e) { } // Approve actions and verify success approveRevocation(intAdmin, approvingAdmin, TOKENUSERNAME, RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, certificateStoreSession, approvalSession, approvalExecutionSession, caID); } finally { hardTokenSessionRemote.removeHardToken(intAdmin, TOKENSERIALNUMBER); } } finally { // Nuke CA try { caAdminSessionRemote.revokeCA(intAdmin, caID, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED); } finally { caSession.removeCA(intAdmin, caID); CryptoTokenTestUtils.removeCryptoToken(intAdmin, cryptoTokenId); } } log.trace("<test19RevocationApprovals"); }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
private void saveNodeCertificateChain(KeyStore keyStore, Key key, String keyPassword, X509Certificate nodeCert, X509Certificate[] chain) { if (keyPassword == null) { keyPassword = ""; }/* w w w .j a v a 2 s.c o m*/ X509Certificate caCert = getCACertificate(keyStore); if (chain.length < 1) { throw new CertificateException("No certificates avaialble"); } if (chain.length > 1) { // we have to trust the parents... the end of the chain must be our CA try { final int caIdx = chain.length - 1; if (caCert == null) { // if we don't have a CA cert yet, install that now log.info("Installing trusted CA certificate {}", chain[caIdx].getSubjectDN()); keyStore.setCertificateEntry(caAlias, chain[caIdx]); caCert = chain[caIdx]; } else { // verify CA is the same... maybe we shouldn't do this? if (!chain[caIdx].getSubjectDN().equals(caCert.getSubjectDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getSubjectDN().getName() + " does not match expected " + caCert.getSubjectDN().getName()); } if (!chain[caIdx].getIssuerDN().equals(caCert.getIssuerDN())) { throw new CertificateException("Chain CA " + chain[caIdx].getIssuerDN().getName() + " does not match expected " + caCert.getIssuerDN().getName()); } } // install intermediate certs... for (int i = caIdx - 1, j = 1; i > 0; i--, j++) { String alias = caAlias + "sub" + j; log.info("Installing trusted intermediate certificate {}", chain[i].getSubjectDN()); keyStore.setCertificateEntry(alias, chain[i]); } } catch (KeyStoreException e) { throw new CertificateException("Error storing CA chain", e); } } else { // put CA at end of chain if (caCert == null) { throw new CertificateException("No CA certificate available"); } chain = new X509Certificate[] { chain[0], caCert }; } // the issuer must be our CA cert subject... if (!chain[0].getIssuerDN().equals(chain[1].getSubjectDN())) { throw new CertificateException("Issuer " + chain[0].getIssuerDN().getName() + " does not match expected " + chain[1].getSubjectDN().getName()); } // the subject must be our node's existing subject... if (!chain[0].getSubjectDN().equals(nodeCert.getSubjectDN())) { throw new CertificateException("Subject " + chain[0].getIssuerDN().getName() + " does not match expected " + nodeCert.getSubjectDN().getName()); } log.info("Installing node certificate {} reply {} issued by {}", chain[0].getSerialNumber(), chain[0].getSubjectDN().getName(), chain[0].getIssuerDN().getName()); try { keyStore.setKeyEntry(nodeAlias, key, keyPassword.toCharArray(), chain); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } }
From source file:org.viafirma.nucleo.X509.CertificadoGenericoFactory.java
/** * Retorna un certificado generico parseando los datos de un certificado X509 * @param certificadoX509 //from w w w . jav a2 s. co m * @return */ public CertificadoGenerico generar(X509Certificate certificadoX509) { CertificadoGenerico certificado = new CertificadoGenerico(); // recuperamos el conjunto de oids Map<String, String> propiedadesOid = X509Handler.getCurrentInstance().readPropertiesOid(certificadoX509); String subject = certificadoX509.getSubjectDN().toString(); // parseo el subject //StringTokenizer tokenizer=new StringTokenizer(subject,",\""); //String [] tokens=subject.split(","); //for (int i = 0; i < tokens.length; i++) { // String parIdValor = tokens[i].trim(); // String id= parIdValor.split("=")[0]; // String valor= parIdValor.split("=")[1]; // propiedadesOid.put(id,valor); //} loadPropiedadesOid(subject, propiedadesOid); // guardo todas las propiedades(pintables) Set<String> keys = propiedadesOid.keySet(); for (Iterator<String> iter = keys.iterator(); iter.hasNext();) { String key = iter.next(); String valor = propiedadesOid.get(key); // FIX: Problema con el encondig utf-8 en openid. String newValue = StringUtils.replaceChars(valor, "??", "aeiounuAEIOU"); if (!StringUtils.isAsciiPrintable(newValue)) { // omitimos el campo iter.remove(); } else { // remplazamos el valor propiedadesOid.put(key, newValue); } } certificado.setPropiedades(propiedadesOid); // identifico el nombre de la CA propietaria del certificado certificado.setCa(certificadoX509.getIssuerDN().getName()); certificado.setNombre(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.1")); certificado.setApellido1(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.2")); certificado.setApellido2(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.3")); certificado.setNumberUserId(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.4")); certificado.setCn(propiedadesOid.get("CN")); // si no hemos recuperado el nombre en la extensin lo intento recuperar del GIVENNAME. if (StringUtils.isEmpty(certificado.getNombre())) { certificado.setNombre(propiedadesOid.get("GIVENNAME")); } // si no hemos recuperado el nombre APELLIDO. if (StringUtils.isEmpty(certificado.getApellido1())) { certificado.setApellido1(propiedadesOid.get("SURNAME")); } // si no tenemos apelligos, los intentamos recuperar del CN ( cado del edni) // CN="Apelido1 apellido2, nombre (AUTENTICACIN)", if (StringUtils.isEmpty(certificado.getApellido1())) { // TODO, no se recupera correctamente el CN, pero el resultado es el correcto. // Debera de ser StringUtils.substringAfterLast(propiedadesOid.get("CN").replaceAll("\"", ""),",") // pero nos vale con propiedadesOid.get("CN") certificado.setApellido1(propiedadesOid.get("CN")); } // si no hemos recuperado el nombre NIF. if (StringUtils.isEmpty(certificado.getNumberUserId())) { certificado.setNumberUserId(propiedadesOid.get("SERIALNUMBER")); } // si no hemos recuperado el nombre email. if (StringUtils.isEmpty(certificado.getEmail())) { certificado.setEmail(certificado.getPropiedades().get(OID_EMAIL)); } // si sige siendo null lo recupero del oid if (StringUtils.isEmpty(certificado.getEmail())) { certificado.setEmail(propiedadesOid.get("EMAILADDRESS")); } // si no hemos recuperado el pais if (StringUtils.isEmpty(certificado.getPais())) { certificado.setPais(certificado.getPropiedades().get("C")); } // filtrado para que ningun campo sea null if (certificado.getApellido1() == null) { certificado.setApellido1(""); } if (certificado.getApellido2() == null) { certificado.setApellido2(""); } if (certificado.getCa() == null) { certificado.setCa(""); } if (certificado.getEmail() == null) { certificado.setEmail(""); } if (certificado.getNombre() == null) { certificado.setNombre(""); } if (certificado.getPais() == null) { certificado.setPais(""); } if (certificado.getNumberUserId() == null) { certificado.setNumberUserId(""); } // recupero el cargo. String cargo = propiedadesOid.get("T"); if (cargo != null) { certificado.setCargo(cargo); } // recupero el nombre de la organizacin. String organizacion = propiedadesOid.get("O"); if (organizacion != null) { certificado.setOrganizacion(organizacion); } // Detectamos si el certificado est caducado Date hoy = new Date(); if (certificadoX509.getNotAfter().before(hoy)) { // el certificado est caducado. certificado.setCaducado(true); } // recuperar el tpo de certificado loadTipoCertificado(certificado, propiedadesOid, certificado.getCa()); return certificado; }
From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java
/** * Converts certificate into string format. * should eventually go into the locator itself *///from www . j ava 2s . co m protected String getCertificateStringWithoutVersion(X509Certificate cert) { if (cert == null) { return null; } // note that it did not represent a certificate fully return "-1;" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN(); }
From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java
public String getCertificateString(X509Certificate cert) { if (cert == null) { return null; }//from w w w . jav a2s . com // note that it did not represent a certificate fully return cert.getVersion() + ";" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN(); }
From source file:org.ejbca.util.CertTools.java
/** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate//from w w w . j a va2s .com * @param which 1 = subjectDN, anything else = issuerDN * * @return String containing the DN. */ private static String getDN(Certificate cert, int which) { /*if (log.isTraceEnabled()) { log.trace(">getDN("+which+")"); }*/ String ret = null; if (cert == null) { return null; } if (cert instanceof X509Certificate) { // cert.getType=X.509 try { CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); //log.debug("Created certificate of class: " + x509cert.getClass().getName()); String dn = null; if (which == 1) { dn = x509cert.getSubjectDN().toString(); } else { dn = x509cert.getIssuerDN().toString(); } ret = stringToBCDNString(dn); } catch (CertificateException ce) { log.info("Could not get DN from X509Certificate. " + ce.getMessage()); log.debug("", ce); return null; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ReferenceField rf = null; if (which == 1) { rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference(); } else { rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference(); } if (rf != null) { // Construct a "fake" DN which can be used in EJBCA // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part String dn = ""; // if (rf.getSequence() != null) { // dn += "SERIALNUMBER="+rf.getSequence(); // } if (rf.getMnemonic() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "CN=" + rf.getMnemonic(); } if (rf.getCountry() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "C=" + rf.getCountry(); } ret = stringToBCDNString(dn); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); return null; } } /*if (log.isTraceEnabled()) { log.trace("<getDN("+which+"):"+dn); }*/ return ret; }
From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java
private void obtainCertificateChain(String keyAlgorithmName, int keySize, AcmeAccount account, String domainName) throws Exception { X509CertificateChainAndSigningKey certificateChainAndSigningKey = acmeClient.obtainCertificateChain(account, false, keyAlgorithmName, keySize, domainName); PrivateKey privateKey = certificateChainAndSigningKey.getSigningKey(); X509Certificate[] replyCertificates = certificateChainAndSigningKey.getCertificateChain(); assertTrue(replyCertificates.length == 2); X509Certificate signedCert = replyCertificates[0]; X509Certificate caCert = replyCertificates[1]; assertTrue(signedCert.getSubjectDN().getName().contains(domainName)); assertEquals(caCert.getSubjectDN(), signedCert.getIssuerDN()); assertEquals("CN=cackling cryptographer fake ROOT", caCert.getIssuerDN().getName()); if (keyAlgorithmName != null && keySize != -1) { assertEquals(keyAlgorithmName, privateKey.getAlgorithm()); assertEquals(keyAlgorithmName, signedCert.getPublicKey().getAlgorithm()); if (keyAlgorithmName.equals("EC")) { assertEquals(keySize,//from w w w . ja v a 2 s . co m ((ECPublicKey) signedCert.getPublicKey()).getParams().getCurve().getField().getFieldSize()); } else if (keyAlgorithmName.equals("RSA")) { assertEquals(keySize, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); } } else { if (signedCert.getPublicKey().getAlgorithm().equals("RSA")) { assertEquals(AcmeClientSpi.DEFAULT_KEY_SIZE, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); assertEquals("RSA", privateKey.getAlgorithm()); } else if (signedCert.getPublicKey().getAlgorithm().equals("EC")) { assertEquals(AcmeClientSpi.DEFAULT_EC_KEY_SIZE, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); assertEquals("EC", privateKey.getAlgorithm()); } } }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * //from w w w.ja v a 2 s . co m * @param keyInfo the key info * @param ownKeyStore * @param ownKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) { LOG.trace("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA); final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(HEXA); X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (RuntimeException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } return alias; }
From source file:org.cesecore.util.CertTools.java
/** * Checks if a certificate is valid./* w ww .j ava 2 s . c o m*/ * Does also print a WARN if the certificate is about to expire. * * @param signerCert the certificate to be tested * @return true if the certificate is valid */ public static boolean isCertificateValid(final X509Certificate signerCert) { try { signerCert.checkValidity(); } catch (CertificateExpiredException e) { log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } catch (CertificateNotYetValidException e) { log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime(); if (warnBeforeExpirationTime < 1) { return true; } final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime); try { signerCert.checkValidity(warnDate); } catch (CertificateExpiredException e) { log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(), signerCert.getIssuerDN(), signerCert.getNotAfter())); } catch (CertificateNotYetValidException e) { throw new Error("This should never happen.", e); } if (log.isDebugEnabled()) { log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: " + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime)); } return true; }