List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:io.hops.hopsworks.util.CertificateHelper.java
private static boolean isCertSigned(File certFile, File intermediateCertFile) throws IllegalStateException { X509Certificate cert = getX509Cert(certFile); X509Certificate caCert = getX509Cert(intermediateCertFile); String intermediateSubjectDN = caCert.getSubjectDN().getName(); String issuerDN = cert.getIssuerDN().getName(); LOG.log(Level.INFO, "sign check: {0} {1}", new Object[] { issuerDN, intermediateSubjectDN }); return issuerDN.equals(intermediateSubjectDN); }
From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java
public static Map<String, String> getCertX500Map(javax.security.cert.X509Certificate cert) { return getX500Map(cert.getSubjectDN()); }
From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java
/** * For debuging only. Prints out keystore certificate chain. * * @param keystore Keystore to print out. * @throws KeyStoreException If the keystore is broken. *///from w w w .jav a 2 s. c o m public static void printKeyCertificates(KeyStore keystore) throws KeyStoreException { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { String message = "Certificate chain '" + alias + "':"; int i = 1; for (Certificate cert : certs) { if (cert instanceof X509Certificate) { X509Certificate Xcert = (X509Certificate) cert; message += "\n Certificate " + i++ + ":"; message += "\n Subject DN: " + Xcert.getSubjectDN(); message += "\n Signature Algorithm: " + Xcert.getSigAlgName(); message += "\n Valid from: " + Xcert.getNotBefore(); message += "\n Valid until: " + Xcert.getNotAfter(); message += "\n Issuer: " + Xcert.getIssuerDN(); } } log.info(message); } } }
From source file:org.zuinnote.hadoop.office.format.common.util.CertificateChainVerificationUtil.java
public static boolean verifyCertificateChain(X509Certificate theCertificate, Set<X509Certificate> chainCertificates) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { // check if we can establish a trust chain if (isSelfSigned(theCertificate)) { LOG.error("Certificate is self-signed - no trust chain can be established with provided truststore"); return false; }/* w w w . j ava2 s . c om*/ if (chainCertificates.size() < 2) { LOG.error( "One needs at least three certificates (including certificate used for signing to establish a trust chain. Please check that you included them"); return false; } HashSet<X509Certificate> rootCertificates = new HashSet<>(); HashSet<X509Certificate> subCertificates = new HashSet<>(); subCertificates.add(theCertificate); for (X509Certificate currentCertificate : chainCertificates) { if (CertificateChainVerificationUtil.isSelfSigned(currentCertificate)) { LOG.debug("Root: " + currentCertificate.getSubjectDN().getName()); rootCertificates.add(currentCertificate); } else { LOG.debug("Sub: " + currentCertificate.getSubjectDN().getName()); subCertificates.add(currentCertificate); } } // Configure verification X509CertSelector selector = new X509CertSelector(); selector.setCertificate(theCertificate); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); HashSet<TrustAnchor> trustAnchors = new HashSet<>(); for (X509Certificate currentCertificate : rootCertificates) { trustAnchors.add(new TrustAnchor(currentCertificate, null)); } PKIXBuilderParameters builderParams = new PKIXBuilderParameters(trustAnchors, selector); CertStore subCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(subCertificates), "BC"); builderParams.addCertStore(subCertStore); try { PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(builderParams); return true; } catch (CertPathBuilderException e) { LOG.error("Exception: ", e); LOG.error("Cannot verify certification chain for " + theCertificate.getSubjectX500Principal()); } return false; }
From source file:com.iaspec.rda.plugins.rfid.license.LicenseReader.java
public static void verifyChallengeCode(String challenge, String expect, Device device) throws RdaException { ChallengeVerifier verifier = ChallengeVerifier.getInstance(); byte[] pkcs7 = Base64.decode(challenge); SignatureVerificationResultHolder resultHolder = null; try {//from ww w .ja v a2 s . com resultHolder = verifier.verifySignature(pkcs7); } catch (SignatureInvalidException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } catch (CryptoException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } CertificateDnInfoDTO certSubjectDn = CertUtil.getCertificateSubjectInfo(resultHolder.signingCertChain[0]); // Handle CN checks String cn = certSubjectDn.getCn().get(0).toString(); if (!cn.equalsIgnoreCase(device.getId())) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE); } logger.debug("Signature Verification success: certSubject=[" + resultHolder.signingCertChain[0].getSubjectDN().toString() + "], orignialContent=[" + new String(resultHolder.originalData) + "]"); if (!new String(resultHolder.originalData).equalsIgnoreCase(expect)) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } try { KeyStore trustedStore = KeyStore.getInstance("JKS"); trustedStore.load(null, null); // byte[] certBytes = IOUtils.toByteArray(new // FileInputStream("RDA_RFID_CA_2.cer")); //false CA certificate // byte[] certBytes = IOUtils.toByteArray(new // FileInputStream("RDA_RFID_CA.cer")); byte[] certBytes = IOUtils.toByteArray(ResourceHelper.readResource("RDA_RFID_CA.cer")); // valid CA certificate X509Certificate cert = CertUtil.getX509Certificate(certBytes); // may add any trusted certificate (CA or Self-signed) to the // keystore... trustedStore.setCertificateEntry(cert.getSubjectDN().getName().toString(), cert); verifier.isCertificateTrust(resultHolder.signingCertChain[0], trustedStore, null); // if trusted, do CRL verification if crl can supplied /* * if * (!CertUtil.verifyRevoked(ResourceHelper.readResource("crl.crl"), * cert)) { throw new * RdaException(ExceptionMessages.EXCEPTION_CERTIFICATE_IS_REVOKED); * } */ } catch (com.iaspec.rda.rfid.server.crypto.exception.CertificateNotValidException se) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE); } catch (CertificateException ce) { throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE); } catch (RdaException e) { throw new RdaException(e.getMessage()); } catch (Exception e) { throw new RdaException(ExceptionMessages.EXCEPTION_SYSTEM); } logger.debug("The certificate is trusted"); }
From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java
static private void dumpCertificate(X509Certificate cert) { LOG.debug("Certificate:"); LOG.debug(" Subject: " + cert.getSubjectDN()); LOG.debug(" Issuer: " + cert.getIssuerDN()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Fingerprint: " + getCertificateFingerprint(cert, "MD5")); }
From source file:Main.java
public static String getClientIdFromCertificate(X509Certificate certificate) { if (certificate == null) { throw new IllegalArgumentException("Certificate cannot be null"); }//w w w . j ava 2 s . c o m //subjectDN is of the form: "UID=<clientId>, DC=<some other value>" or "DC=<some other value>, UID=<clientId>" String clientId = null; String subjectDN = certificate.getSubjectDN().getName(); String[] parts = subjectDN.split(Pattern.quote(",")); for (String part : parts) { if (part.contains("UID=")) { String uid = part.substring(part.indexOf("UID=")); clientId = uid.split(Pattern.quote("="))[1]; } } return clientId; }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method used to verify signed data.//from w ww .j av a2 s . c om * * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used. * @param signedData the data to verify * @param date the date used to check the validity against. * @return a ParsedSignatureResult. */ public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs, byte[] signedData, Date date) { boolean verifies = false; X509Certificate usercert = null; ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null); byte[] content = null; try { // First verify the signature CMSSignedData sp = new CMSSignedData(signedData); CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = sp.getSignerInfos(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ((CMSProcessableByteArray) sp.getSignedContent()).write(baos); content = baos.toByteArray(); baos.close(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); usercert = (X509Certificate) certIt.next(); boolean validalg = signer.getDigestAlgOID().equals(signAlg); verifies = validalg && signer.verify(usercert.getPublicKey(), "BC"); } // Second validate the certificate X509Certificate rootCert = null; Iterator iter = cACertChain.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert.getIssuerDN().equals(cert.getSubjectDN())) { rootCert = cert; break; } } if (rootCert == null) { throw new CertPathValidatorException("Error Root CA cert not found in cACertChain"); } List list = new ArrayList(); list.add(usercert); list.add(cACertChain); if (trustedCRLs != null) { list.add(trustedCRLs); } CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp); //validating path List certchain = new ArrayList(); certchain.addAll(cACertChain); certchain.add(usercert); CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain); Set trust = new HashSet(); trust.add(new TrustAnchor(rootCert, null)); CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertStore(store); param.setDate(date); if (trustedCRLs == null) { param.setRevocationEnabled(false); } else { param.setRevocationEnabled(true); } cpv.validate(cp, param); retval = new ParsedSignatureResult(verifies, usercert, content); } catch (Exception e) { log.error("Error verifying data : ", e); } return retval; }
From source file:wsattacker.library.signatureFaking.helper.CertificateHandlerTest.java
public static void testCertificateHandler() throws Exception { String certificate = FileReader.readFile(DIR + "/test-cert"); CertificateHandler ch = new CertificateHandler(certificate); ch.createFakedCertificate();//from www. j a v a 2 s.c o m X509CertImpl faked = ch.getFakedCertificate(); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate original = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(certificate))); assertEquals(faked.getIssuerDN().getName(), original.getIssuerDN().getName()); assertEquals(faked.getSigAlgOID(), original.getSigAlgOID()); assertEquals(faked.getSubjectDN().getName(), original.getSubjectDN().getName()); faked.verify(faked.getPublicKey()); }
From source file:org.globus.pkcs11.PKCS11Util.java
/** * Loads a certificate onto the PKCS11 device and labels it with the specified * label//from ww w . j av a 2 s.c o m */ public static PKCS11Object instantiateUserCert(X509Certificate userCert, String label, byte[] id) throws CertificateEncodingException { Name issuer = (Name) userCert.getIssuerDN(); Name subject = (Name) userCert.getSubjectDN(); byte[] issuerBytes = issuer.getEncoded(); byte[] subjectBytes = subject.getEncoded(); if (label == null) { label = subject.toString(); } logger.debug("Instantiating user cert with label " + label + " on device"); //X_509 CERTIFICATE int[] certAttributes = { PKCS11Object.CLASS, PKCS11Object.TOKEN, PKCS11Object.LABEL, PKCS11Object.CERTIFICATE_TYPE, PKCS11Object.ID, PKCS11Object.SUBJECT, PKCS11Object.ISSUER, PKCS11Object.SERIAL_NUMBER, PKCS11Object.VALUE }; Object[] certAttrValues = { PKCS11Object.CERTIFICATE, PKCS11Object.TRUE, label, PKCS11Object.X_509, id, subjectBytes, issuerBytes, userCert.getSerialNumber().toByteArray(), userCert.getEncoded() }; return session.createObject(certAttributes, certAttrValues); }