List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
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 .jav a2 s. c o 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 country from X.509 Certificate. * /*from www. j ava 2 s .c om*/ * @param keyInfo the key info * * @return the country */ private String getCountry(final KeyInfo keyInfo) { LOG.trace("Recover country information."); String result = ""; 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); String distName = cert.getSubjectDN().toString(); distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName)); final String countryCode = "C="; final int init = distName.indexOf(countryCode); if (init > StringUtils.INDEX_NOT_FOUND) { // Exist country code. int end = distName.indexOf(',', init); if (end <= StringUtils.INDEX_NOT_FOUND) { end = distName.length(); } if (init < end && end > StringUtils.INDEX_NOT_FOUND) { result = distName.substring(init + countryCode.length(), end); //It must be a two characters value if (result.length() > 2) { result = result.substring(0, 2); } } } } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate. {}", e); } return result.trim(); }
From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java
/** * Gets the User that is associated with the specified certificate. * * @throws UserNotFoundException when no matching User is found *//* ww w . j ava 2 s . c om*/ public UserType getUserFromCertificate(X509Certificate cert) throws RegistryException { UserType user = null; if (cert == null) { boolean noRegRequired = Boolean.valueOf( CommonProperties.getInstance().getProperty("omar.common.noUserRegistrationRequired", "false")) .booleanValue(); if (noRegRequired) { return registryOperator; } else { return registryGuest; } } //The registry expects the KeyInfo to either have the PublicKey or the DN from the public key //In case of DN the registry can lookup the public key based on the DN java.security.PublicKey publicKey = null; String alias = null; try { // lots of trace if (log.isTraceEnabled()) { log.trace("getUserFromCertificate cert:\n" + cert); StringBuffer storedCerts = new StringBuffer("Stored certificates:"); Enumeration aliases = getKeyStore().aliases(); while (aliases.hasMoreElements()) { X509Certificate storedCert = (X509Certificate) getKeyStore() .getCertificate((String) aliases.nextElement()); storedCerts.append("\n").append(storedCert).append("\n--------"); } log.trace(storedCerts.toString()); } else if (log.isDebugEnabled()) { log.debug("getUserFromCertificate cert:\n" + cert); } alias = getKeyStore().getCertificateAlias(cert); if (alias == null) { if (log.isDebugEnabled()) { log.debug("Unknown certificate: " + cert.getSubjectDN().getName()); } throw new UserNotFoundException(cert.getSubjectDN().getName()); } if (log.isDebugEnabled()) { log.debug("Alias found for certificate:: " + alias); } } catch (KeyStoreException e) { throw new RegistryException(e); } user = getUserFromAlias(alias); return user; }
From source file:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java
/** * Gets the User that is associated with the specified certificate. * // ww w.ja va2s. c o m * @throws UserNotFoundException * when no matching User is found */ public UserType getUserFromCertificate(X509Certificate cert) throws RegistryException { UserType user = null; if (cert == null) { boolean noRegRequired = Boolean.valueOf( CommonProperties.getInstance().getProperty("eric.common.noUserRegistrationRequired", "false")) .booleanValue(); if (noRegRequired) { return registryOperator; } else { return registryGuest; } } // The registry expects the KeyInfo to either have the PublicKey or the // DN from the public key // In case of DN the registry can lookup the public key based on the DN @SuppressWarnings("unused") java.security.PublicKey publicKey = null; String alias = null; try { // lots of trace if (log.isTraceEnabled()) { log.trace("getUserFromCertificate cert:\n" + cert); StringBuffer storedCerts = new StringBuffer("Stored certificates:"); Enumeration<String> aliases = getKeyStore().aliases(); while (aliases.hasMoreElements()) { X509Certificate storedCert = (X509Certificate) getKeyStore() .getCertificate(aliases.nextElement()); storedCerts.append("\n").append(storedCert).append("\n--------"); } log.trace(storedCerts.toString()); } else if (log.isDebugEnabled()) { log.debug("getUserFromCertificate cert:\n" + cert); } alias = getKeyStore().getCertificateAlias(cert); if (alias == null) { if (log.isDebugEnabled()) { log.debug("Unknown certificate: " + cert.getSubjectDN().getName()); } throw new UserNotFoundException(cert.getSubjectDN().getName()); } if (log.isDebugEnabled()) { log.debug("Alias found for certificate:: " + alias); } } catch (KeyStoreException e) { throw new RegistryException(e); } user = getUserFromAlias(alias); return user; }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList, TrustedCertificates trustedCerts) throws ProxyPathValidatorException { if (crlsList == null) { return;/*from w w w . j a va2s . co m*/ } logger.debug("checkCRLs: enter"); // Should not happen, just a sanity check. if (trustedCerts == null) { String err = "Trusted certificates are null, cannot verify CRLs"; logger.error(err); throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err); } String issuerName = cert.getIssuerDN().getName(); X509CRL crl = crlsList.getCrl(issuerName); if (crl == null) { logger.debug("No CRL for certificate"); return; } // get CA cert for the CRL X509Certificate x509Cert = trustedCerts.getCertificate(issuerName); if (x509Cert == null) { // if there is no trusted certs from that CA, then // the chain cannot contain a cert from that CA, // which implies not checking this CRL should be fine. logger.debug("No trusted cert with this CA signature"); return; } // validate CRL try { crl.verify(x509Cert.getPublicKey()); } catch (Exception exp) { logger.error("CRL verification failed"); throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp); } Date now = new Date(); // check date validity of CRL if ((crl.getThisUpdate().before(now)) || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) { if (crl.isRevoked(cert)) { throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert, "This cert " + cert.getSubjectDN().getName() + " is on a CRL"); } } logger.debug("checkCRLs: exit"); }
From source file:org.apache.rahas.impl.SAMLTokenIssuer.java
protected SAMLAssertion createHoKAssertion(SAMLTokenIssuerConfig config, Document doc, Crypto crypto, Date creationTime, Date expirationTime, RahasData data) throws TrustException { String keyType = data.getKeyType(); if (StringUtils.isBlank(keyType)) { keyType = data.getRstElement().getNamespace().getNamespaceURI() + RahasConstants.KEY_TYPE_SYMM_KEY; }/*w w w. j a va 2s . co m*/ if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) { Element encryptedKeyElem; SAMLNameIdentifier nameId = null; X509Certificate serviceCert = null; try { if (data.getPrincipal() != null) { String subjectNameId = data.getPrincipal().getName(); nameId = new SAMLNameIdentifier(subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL); } // Get ApliesTo to figure out which service to issue the token // for serviceCert = getServiceCert(config, crypto, data.getAppliesToAddress()); // Create the encrypted key WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey(); // Use thumbprint id encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); // SEt the encryption cert encrKeyBuilder.setUseThisCert(serviceCert); // set keysize int keysize = data.getKeysize(); keysize = (keysize != -1) ? keysize : config.keySize; encrKeyBuilder.setKeySize(keysize); encrKeyBuilder .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize)); // Set key encryption algo encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); // Build encrKeyBuilder.prepare(doc, crypto); // Extract the base64 encoded secret value byte[] tempKey = new byte[keysize / 8]; System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8); data.setEphmeralKey(tempKey); // Extract the Encryptedkey DOM element encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement(); } catch (Exception e) { throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal", new String[] { serviceCert.getSubjectDN().getName() }, e); } return this.createAttributeAssertion(doc, data, encryptedKeyElem, nameId, config, crypto, creationTime, expirationTime); } else { try { String subjectNameId = data.getPrincipal().getName(); SAMLNameIdentifier nameId = new SAMLNameIdentifier(subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL); // Create the ds:KeyValue element with the ds:X509Data X509Certificate clientCert = data.getClientCert(); if (clientCert == null) { X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName()); clientCert = certs[0]; } byte[] clientCertBytes = clientCert.getEncoded(); String base64Cert = Base64.encode(clientCertBytes); Text base64CertText = doc.createTextNode(base64Cert); Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "X509Certificate"); x509CertElem.appendChild(base64CertText); Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "X509Data"); x509DataElem.appendChild(x509CertElem); return this.createAuthAssertion(doc, SAMLSubject.CONF_HOLDER_KEY, nameId, x509DataElem, config, crypto, creationTime, expirationTime, data); } catch (Exception e) { throw new TrustException("samlAssertionCreationError", e); } } }
From source file:org.cesecore.util.CertTools.java
/** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * //w w w . j ava2 s . c o m * @param cert X509Certificate * @param which 1 = subjectDN, anything else = issuerDN * * @return String containing the DN. */ private static String getDN(final Certificate cert, final int which) { String ret = null; if (cert == null) { return null; } if (cert instanceof X509Certificate) { // cert.getType=X.509 try { final CertificateFactory cf = CertTools.getCertificateFactory(); final X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); 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")) { final 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.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; } } return ret; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
/** * Perform two WS certificate requests with different response-types: Certificate and PKCS#7. If the first one fails an error code will be * returned. I the second fails a Exception will be thrown. *//* ww w. j a v a 2s . co m*/ private ErrorCode certreqInternal(UserDataVOWS userdata, String requestdata, int requesttype) throws Exception { // Request a certificate via the WS API final CertificateResponse certificateResponse; try { certificateResponse = ejbcaraws.certificateRequest(userdata, requestdata, requesttype, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); } catch (EjbcaException_Exception e) { final ErrorCode errorCode = e.getFaultInfo().getErrorCode(); log.info(errorCode.getInternalErrorCode(), e); assertNotNull("error code should not be null", errorCode); return errorCode; } // Verify that the response is of the right type assertNotNull(certificateResponse); assertTrue(certificateResponse.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE)); // Verify that the certificate in the response has the same Subject DN // as in the request. final X509Certificate cert = certificateResponse.getCertificate(); assertNotNull(cert); assertTrue(cert.getSubjectDN().toString().equals(userdata.getSubjectDN())); // Request a PKCS#7 via the WS API final CertificateResponse pkcs7Response = ejbcaraws.certificateRequest(userdata, requestdata, requesttype, null, CertificateHelper.RESPONSETYPE_PKCS7); // Verify that the response is of the right type assertTrue(pkcs7Response.getResponseType().equals(CertificateHelper.RESPONSETYPE_PKCS7)); // Verify that the PKCS#7 response contains a certificate CMSSignedData cmsSignedData = new CMSSignedData(CertificateHelper.getPKCS7(pkcs7Response.getData())); assertNotNull(cmsSignedData); Store certStore = cmsSignedData.getCertificates(); assertTrue(certStore.getMatches(null).size() == 1); return null; }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs10Request() throws Exception { // Change token to P12 UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null);/* w w w . j ava2s. co m*/ assertTrue(userdatas.size() == 1); userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword(PASSWORD); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); CertificateResponse certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE)); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertTrue(cert.getSubjectDN().toString().equals(getDN(CA1_WSTESTUSER1))); ejbcaraws.editUser(userdatas.get(0)); certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_PKCS7); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_PKCS7)); CMSSignedData cmsSignedData = new CMSSignedData(CertificateHelper.getPKCS7(certenv.getData())); assertTrue(cmsSignedData != null); Store certStore = cmsSignedData.getCertificates(); assertTrue(certStore.getMatches(null).size() == 1); }
From source file:org.cesecore.util.CertTools.java
/** Reads PrivateKeyUsagePeriod extension from a certificate * // ww w . j a va2s. com */ public static PrivateKeyUsagePeriod getPrivateKeyUsagePeriod(final X509Certificate cert) { PrivateKeyUsagePeriod res = null; final byte[] extvalue = cert.getExtensionValue(Extension.privateKeyUsagePeriod.getId()); if ((extvalue != null) && (extvalue.length > 0)) { if (log.isTraceEnabled()) { log.trace("Found a PrivateKeyUsagePeriod in the certificate with subject: " + cert.getSubjectDN().toString()); } ASN1InputStream extAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(extvalue)); try { try { final DEROctetString oct = (DEROctetString) (extAsn1InputStream.readObject()); ASN1InputStream octAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(oct.getOctets())); try { res = PrivateKeyUsagePeriod.getInstance((ASN1Sequence) octAsn1InputStream.readObject()); } finally { octAsn1InputStream.close(); } } finally { extAsn1InputStream.close(); } } catch (IOException e) { throw new IllegalStateException("Unknown IOException caught when trying to parse certificate.", e); } } return res; }