List of usage examples for java.security.cert X509Certificate getSubjectX500Principal
public X500Principal getSubjectX500Principal()
From source file:be.fedict.eid.applet.service.JSONServlet.java
private static JSONObject createCertJSONObject(X509Certificate certificate, SimpleDateFormat simpleDateFormat) throws CertificateEncodingException, IOException { JSONObject certJSONObject = new JSONObject(); certJSONObject.put("subject", certificate.getSubjectX500Principal().toString()); certJSONObject.put("issuer", certificate.getIssuerX500Principal().toString()); certJSONObject.put("serialNumber", certificate.getSerialNumber().toString()); certJSONObject.put("notBefore", certificate.getNotBefore().toString()); certJSONObject.put("notAfter", certificate.getNotAfter().toString()); certJSONObject.put("signatureAlgo", certificate.getSigAlgName()); certJSONObject.put("thumbprint", DigestUtils.shaHex(certificate.getEncoded())); certJSONObject.put("details", certificate.toString()); certJSONObject.put("pem", toPem(certificate)); return certJSONObject; }
From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java
public static void extractAliases(Certificate certificate, Set<String> aliases) throws CertificateParsingException { Logger logger = LoggerFactory.getLogger(SSLUtils.class); X509Certificate cert = (X509Certificate) certificate; // logger.debug( "Extracting aliases from:\n\n{}\n\n", cert ); X500Principal x500Principal = cert.getSubjectX500Principal(); X500Name x500Name = new X500Name(x500Principal.getName(X500Principal.RFC1779)); logger.trace("Certificate X.500 name: '{}'", x500Name.toString()); RDN[] matchingRDNs = x500Name.getRDNs(BCStyle.CN); if (matchingRDNs != null && matchingRDNs.length > 0) { RDN cn = matchingRDNs[0];//from w w w. j a va2s .c o m AttributeTypeAndValue typeAndValue = cn.getFirst(); if (typeAndValue != null) { String alias = IETFUtils.valueToString(typeAndValue.getValue()); logger.trace("Found certificate alias: '{}'", alias); aliases.add(alias); } } Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) { for (List<?> names : subjectAlternativeNames) { if (names.size() > 1 && (DNSNAME_TYPE.equals(names.get(0)))) { String alias = (String) names.get(1); logger.trace("Found subjectAlternativeName: '{}'", alias); aliases.add(alias); } } } else { logger.debug("NO SubjectAlternativeNames available!"); } }
From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureVerifier.java
private static X509Certificate getVerifiedSignatureSigner(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException { if (null == odfUrl) { throw new IllegalArgumentException("odfUrl is null"); }/*from w w w .j a v a2 s . c o m*/ KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureNode); ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); LOG.debug("java version: " + System.getProperty("java.version")); /* * Requires Java 6u10 because of a bug. See also: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582 */ XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validity = xmlSignature.validate(domValidateContext); if (false == validity) { LOG.debug("invalid signature"); return null; } // TODO: check what has been signed. X509Certificate signer = keySelector.getCertificate(); if (null == signer) { throw new IllegalStateException("signer X509 certificate is null"); } LOG.debug("signer: " + signer.getSubjectX500Principal()); return signer; }
From source file:io.fabric8.utils.cxf.WebClients.java
public static KeyStore createTrustStore(String caCertData, File caCertFile) throws Exception { try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream); KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null);/* ww w. j av a 2s.com*/ String alias = cert.getSubjectX500Principal().getName(); trustStore.setCertificateEntry(alias, cert); return trustStore; } }
From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Method used to create an enveloped digital signature for an element of a TAXII document. * * @param element the element to be signed * @param keyEntry the PrivateKeyEntry//from w w w . j av a 2 s .co m * @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element * @return the status of the operation * * Usage Example: * String pks = config.getProperty("pathToPublisherKeyStore"); * String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword")); * String keyName = config.getProperty("publisherKeyName"); * String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword")); * PrivateKeyEntry keyEntry = FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW); * List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1); */ private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) { element.normalize(); boolean status = false; //Create XML Signature Factory XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM"); PublicKey publicKey = ClientUtil.getPublicKey(keyEntry); PrivateKey privateKey = keyEntry.getPrivateKey(); DOMSignContext dsc = new DOMSignContext(privateKey, element); dsc.setDefaultNamespacePrefix("ds"); dsc.setURIDereferencer(new MyURIDereferencer(element)); SignedInfo si = null; DigestMethod dm = null; SignatureMethod sm = null; KeyInfo ki = null; X509Data xd; List<Serializable> x509Content = new ArrayList<>(); try { String algorithm = publicKey.getAlgorithm(); X509Certificate cert = (X509Certificate) keyEntry.getCertificate(); x509Content.add(cert.getSubjectX500Principal().getName()); x509Content.add(cert); String algorithmName = cert.getSigAlgName(); if (algorithm.toUpperCase().contains("RSA")) { if (algorithmName.toUpperCase().contains("SHA1")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null); sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); } else if (algorithmName.toUpperCase().contains("SHA2")) { dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null); sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } CanonicalizationMethod cm; if (cbIndex != -1) { cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex + "]/*[local-name()='Content'][1]/*)"; List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } else { List<Transform> transforms = new ArrayList<>(2); transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); String refUri = "#xpointer(/*)"; List<Reference> references = Collections .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null)); si = xmlSigFactory.newSignedInfo(cm, sm, references); } KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory(); xd = kif.newX509Data(x509Content); ki = kif.newKeyInfo(Collections.singletonList(xd)); } else { logger.error("Error in digital signature application. " + algorithmName + " is not supported."); } } catch (NoSuchAlgorithmException ex) { logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document."); } catch (InvalidAlgorithmParameterException ex) { logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document."); } // Create a new XML Signature XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki); try { // Sign the document signature.sign(dsc); status = true; } catch (MarshalException ex) { logger.error("MarshalException when attempting to digitally sign a document."); } catch (XMLSignatureException ex) { logger.error("XMLSignature Exception when attempting to digitally sign a document."); } catch (Exception e) { logger.error("General exception when attempting to digitally sign a document."); } return status; }
From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java
static void checkServerCertsExpirationDays(Configuration conf, String hostname, int port) throws IOException { setupSslProps(conf);/* w w w .j a v a 2 s . c om*/ HttpsURLConnection connection = null; connection = openConnection(hostname, port, null); connection.connect(); X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates(); Date curDate = new Date(); long curTime = curDate.getTime(); if (serverCerts != null) { for (X509Certificate cert : serverCerts) { StringBuffer sb = new StringBuffer(); sb.append("\n Server certificate Subject Name: " + cert.getSubjectX500Principal().getName()); Date expDate = cert.getNotAfter(); long expTime = expDate.getTime(); int dayOffSet = (int) ((expTime - curTime) / MM_SECONDS_PER_DAY); sb.append(" have " + dayOffSet + " days to expire"); if (dayOffSet < CERT_EXPIRATION_WARNING_THRESHOLD) LOG.warn(sb.toString()); else LOG.info(sb.toString()); } } else { LOG.info("\n No Server certs was found"); } if (connection != null) { connection.disconnect(); } }
From source file:org.opensaml.xml.security.x509.X509Util.java
/** * Gets the common name components of the issuer and all the subject alt names of a given type. * /*from w w w .jav a2s . co m*/ * @param certificate certificate to extract names from * @param altNameTypes type of alt names to extract * * @return list of subject names in the certificate */ @SuppressWarnings("unchecked") public static List getSubjectNames(X509Certificate certificate, Integer[] altNameTypes) { List issuerNames = new LinkedList(); List<String> entityCertCNs = X509Util.getCommonNames(certificate.getSubjectX500Principal()); issuerNames.add(entityCertCNs.get(0)); issuerNames.addAll(X509Util.getAltNames(certificate, altNameTypes)); return issuerNames; }
From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java
static boolean sendCommand(Configuration conf, String path) throws IOException { setupSslProps(conf);//from w w w. j av a 2 s.c o m int sslPort = getSslAddr(conf).getPort(); int err = 0; StringBuilder b = new StringBuilder(); HostsFileReader hostsReader = new HostsFileReader(conf.get("hdfsproxy.hosts", "hdfsproxy-hosts"), ""); Set<String> hostsList = hostsReader.getHosts(); for (String hostname : hostsList) { HttpsURLConnection connection = null; try { connection = openConnection(hostname, sslPort, path); connection.connect(); if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer(); X509Certificate[] clientCerts = (X509Certificate[]) connection.getLocalCertificates(); if (clientCerts != null) { for (X509Certificate cert : clientCerts) sb.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName()); } else { sb.append("\n No client certificates were found"); } X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates(); if (serverCerts != null) { for (X509Certificate cert : serverCerts) sb.append("\n Server certificate Subject Name is " + cert.getSubjectX500Principal().getName()); } else { sb.append("\n No server certificates were found"); } LOG.debug(sb.toString()); } if (connection.getResponseCode() != HttpServletResponse.SC_OK) { b.append("\n\t" + hostname + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); err++; } } catch (IOException e) { b.append("\n\t" + hostname + ": " + e.getLocalizedMessage()); if (LOG.isDebugEnabled()) LOG.debug("Exception happend for host " + hostname, e); err++; } finally { if (connection != null) connection.disconnect(); } } if (err > 0) { System.err.print("Command failed on the following " + err + " host" + (err == 1 ? ":" : "s:") + b.toString() + "\n"); return false; } return true; }
From source file:com.raspberry.library.util.AppUtils.java
/** * Judge whether an app is dubuggable//from w w w. ja v a 2s . c o m * * @param ctx * @return */ public static boolean isDebuggable(Context ctx) { boolean debuggable = false; try { PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES); Signature signatures[] = pinfo.signatures; for (int i = 0; i < signatures.length; i++) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray()); X509Certificate cert = (X509Certificate) cf.generateCertificate(stream); debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN); if (debuggable) { break; } } } catch (NameNotFoundException e) { } catch (CertificateException e) { } return debuggable; }
From source file:be.fedict.trust.TrustValidator.java
/** * Gives back the trust linker result of a verification of a self-signed * X509 certificate.// w w w. java 2 s .c o m * * @param certificate * the self-signed certificate to validate. * @return the validation result. */ public static TrustLinkerResult getSelfSignedResult(X509Certificate certificate) { if (false == certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) { return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "root certificate should be self-signed: " + certificate.getSubjectX500Principal()); } try { certificate.verify(certificate.getPublicKey()); } catch (Exception e) { return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "certificate signature error: " + e.getMessage()); } return new TrustLinkerResult(true); }