List of usage examples for java.security.cert CertificateFactory getInstance
public static final CertificateFactory getInstance(String type) throws CertificateException
From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java
/** * Verifies the signature in the update center data file. *//* w w w. j a v a 2 s. c om*/ private FormValidation verifySignature(JSONObject o) throws IOException { try { FormValidation warning = null; JSONObject signature = o.getJSONObject("signature"); if (signature.isNullObject()) { return FormValidation.error("No signature block found in update center '" + getId() + "'"); } o.remove("signature"); List<X509Certificate> certs = new ArrayList<X509Certificate>(); {// load and verify certificates CertificateFactory cf = CertificateFactory.getInstance("X509"); for (Object cert : signature.getJSONArray("certificates")) { X509Certificate c = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray()))); try { c.checkValidity(); } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet, // we'll proceed it anyway warning = FormValidation.warning(e, String.format( "Certificate %s has expired in update center '%s'", cert.toString(), getId())); } catch (CertificateNotYetValidException e) { warning = FormValidation.warning(e, String.format( "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId())); } certs.add(c); } // all default root CAs in JVM are trusted, plus certs bundled in Jenkins Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs(); ServletContext context = Hudson.getInstance().servletContext; anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null)); for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) { if (cert.endsWith(".txt")) { continue; // skip text files that are meant to be documentation } InputStream stream = context.getResourceAsStream(cert); if (stream != null) { try { anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null)); } finally { IOUtils.closeQuietly(stream); } } } CertificateUtil.validatePath(certs, anchors); } // this is for computing a digest to check sanity MessageDigest sha1 = MessageDigest.getInstance("SHA1"); DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1); // this is for computing a signature Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(certs.get(0)); SignatureOutputStream sos = new SignatureOutputStream(sig); // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature) // that only covers the earlier portion of the file. This was caused by the lack of close() call // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to // the digest output stream. This affects Jenkins [1.424,1,431]. // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it // compute the correct digest, but it breaks all the existing UC json metadata out there. We then // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature, // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*). // // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature" // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated // correctly. // // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows // the attacker to inject a fragment at the end of the json. o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close(); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell String computedDigest = new String(Base64.encode(sha1.digest())); String providedDigest = signature.optString("correct_digest"); if (providedDigest == null) { return FormValidation.error("No correct_digest parameter in update center '" + getId() + "'. This metadata appears to be old."); } if (!computedDigest.equalsIgnoreCase(providedDigest)) { return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest + " in update center '" + getId() + "'"); } String providedSignature = signature.getString("correct_signature"); if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) { return FormValidation.error( "Signature in the update center doesn't match with the certificate in update center '" + getId() + "'"); } if (warning != null) { return warning; } return FormValidation.ok(); } catch (GeneralSecurityException e) { return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'"); } }
From source file:org.exoplatform.services.videocall.AuthService.java
protected static TrustManager[] getTrustManagers(InputStream trustStoreFile, String trustStorePassword) throws Exception { CertificateFactory certificateFactory = null; try {/*w ww. j a v a 2 s .co m*/ certificateFactory = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not initialize the certificate " + e.getMessage()); } } Certificate caCert = null; try { caCert = certificateFactory.generateCertificate(trustStoreFile); } catch (CertificateException e) { if (LOG.isErrorEnabled()) { LOG.error("Bad key or certificate in " + trustStoreFile, e.getMessage()); } } KeyStore trustStore = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); } catch (KeyStoreException e) { if (LOG.isErrorEnabled()) { LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " keystores"); } } catch (NoSuchAlgorithmException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not initialize truststore ", e); } } catch (CertificateException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not initialize truststore ", e); } } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not initialize truststore ", e); } } try { trustStore.setCertificateEntry("CA", caCert); } catch (KeyStoreException e) { if (LOG.isErrorEnabled()) { LOG.error(trustStoreFile + " cannot be used as a CA", e); } } TrustManagerFactory tmf = null; try { tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); } catch (NoSuchAlgorithmException e) { if (LOG.isErrorEnabled()) { LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e); } } catch (KeyStoreException e) { LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e); } return tmf.getTrustManagers(); }
From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpWSFedProtocolHandler.java
private X509Certificate parseCertificate(String certificate) throws CertificateException, Base64DecodingException { //before decoding we need to get rod off the prefix and suffix byte[] decoded = Base64.decode(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "") .replaceAll("-----END CERTIFICATE-----", "")); return (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(decoded)); }
From source file:org.apache.jmeter.assertions.SMIMEAssertion.java
private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s, String name) throws CMSException { AssertionResult res = new AssertionResult(name); try {/*from w ww . j a va 2 s.c om*/ Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Iterator<?> signerIt = signers.getSigners().iterator(); if (signerIt.hasNext()) { SignerInformation signer = (SignerInformation) signerIt.next(); Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator(); if (certIt.hasNext()) { // the signer certificate X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (testElement.isVerifySignature()) { SignerInformationVerifier verifier = null; try { verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert); } catch (OperatorCreationException e) { log.error("Can't create a provider", e); } if (verifier == null || !signer.verify(verifier)) { res.setFailure(true); res.setFailureMessage("Signature is invalid"); } } if (testElement.isSignerCheckConstraints()) { StringBuilder failureMessage = new StringBuilder(); String serial = testElement.getSignerSerial(); if (!JOrphanUtils.isBlank(serial)) { BigInteger serialNbr = readSerialNumber(serial); if (!serialNbr.equals(cert.getSerialNumber())) { res.setFailure(true); failureMessage.append("Serial number ").append(serialNbr) .append(" does not match serial from signer certificate: ") .append(cert.getSerialNumber()).append("\n"); } } String email = testElement.getSignerEmail(); if (!JOrphanUtils.isBlank(email)) { List<String> emailFromCert = getEmailFromCert(cert); if (!emailFromCert.contains(email)) { res.setFailure(true); failureMessage.append("Email address \"").append(email) .append("\" not present in signer certificate\n"); } } String subject = testElement.getSignerDn(); if (subject.length() > 0) { final X500Name certPrincipal = cert.getSubject(); log.debug("DN from cert: " + certPrincipal.toString()); X500Name principal = new X500Name(subject); log.debug("DN from assertion: " + principal.toString()); if (!principal.equals(certPrincipal)) { res.setFailure(true); failureMessage.append("Distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } String issuer = testElement.getIssuerDn(); if (issuer.length() > 0) { final X500Name issuerX500Name = cert.getIssuer(); log.debug("IssuerDN from cert: " + issuerX500Name.toString()); X500Name principal = new X500Name(issuer); log.debug("IssuerDN from assertion: " + principal); if (!principal.equals(issuerX500Name)) { res.setFailure(true); failureMessage .append("Issuer distinguished name of signer certificate does not match \"") .append(subject).append("\"\n"); } } if (failureMessage.length() > 0) { res.setFailureMessage(failureMessage.toString()); } } if (testElement.isSignerCheckByFile()) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CertificateHolder certFromFile; InputStream inStream = null; try { inStream = new BufferedInputStream( new FileInputStream(testElement.getSignerCertFile())); certFromFile = new JcaX509CertificateHolder( (X509Certificate) cf.generateCertificate(inStream)); } finally { IOUtils.closeQuietly(inStream); } if (!certFromFile.equals(cert)) { res.setFailure(true); res.setFailureMessage("Signer certificate does not match certificate " + testElement.getSignerCertFile()); } } } else { res.setFailure(true); res.setFailureMessage("No signer certificate found in signature"); } } // TODO support multiple signers if (signerIt.hasNext()) { log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported."); } } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); res.setError(true); res.setFailureMessage(e.getMessage()); } catch (FileNotFoundException e) { res.setFailure(true); res.setFailureMessage("certificate file not found: " + e.getMessage()); } return res; }
From source file:com.zimbra.cs.service.authenticator.CertUtil.java
private void loadCert(String certFilePath) throws Exception { InputStream inStream = new FileInputStream(certFilePath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close();// w w w . ja v a 2s .co m }
From source file:it.anyplace.sync.core.security.KeystoreHandler.java
public void checkSocketCerificate(SSLSocket socket, String deviceId) throws SSLPeerUnverifiedException, CertificateException { SSLSession session = socket.getSession(); List<Certificate> certs = Arrays.asList(session.getPeerCertificates()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certificateFactory.generateCertPath(certs); Certificate certificate = certPath.getCertificates().get(0); checkArgument(certificate instanceof X509Certificate); byte[] derData = certificate.getEncoded(); String deviceIdFromCertificate = derDataToDeviceIdString(derData); logger.trace("remote pem certificate =\n{}", derToPem(derData)); checkArgument(equal(deviceIdFromCertificate, deviceId), "device id mismatch! expected = %s, got = %s", deviceId, deviceIdFromCertificate); logger.debug("remote ssl certificate match deviceId = {}", deviceId); }
From source file:com.brienwheeler.apps.tomcat.TomcatBean.java
private X509Certificate readCertFile() throws IOException, CertificateException { String parse[] = readPEMFile(sslCertFile, CERT_PATTERN, 1); if (parse == null) throw new IllegalArgumentException("invalid certificate file contents"); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(Base64.decode(parse[0]))); }
From source file:com.sun.identity.security.cert.AMCRLStore.java
private X509CRL getCRLFromEntry(LDAPEntry crlEntry) throws Exception { if (debug.messageEnabled()) { debug.message("AMCRLStore.getCRLFromEntry:"); }//from w ww .jav a 2 s . com if (crlEntry == null) { return null; } LDAPAttributeSet attributeSet = crlEntry.getAttributeSet(); LDAPAttribute crlAttribute = null; X509CRL crl = null; try { /* * Retrieve the certificate revocation list if available. */ if (mCrlAttrName == null) { crlAttribute = attributeSet.getAttribute("certificaterevocationlist"); if (crlAttribute == null) { crlAttribute = attributeSet.getAttribute("certificaterevocationlist;binary"); if (crlAttribute == null) { debug.error("No CRL Cache is configured"); return null; } } mCrlAttrName = crlAttribute.getName(); } else { crlAttribute = attributeSet.getAttribute(mCrlAttrName); } if (crlAttribute.size() > 1) { debug.error("More than one CRL entries are configured"); return null; } } catch (Exception e) { debug.error("Error in getting Cached CRL"); return null; } try { Enumeration Crls = crlAttribute.getByteValues(); byte[] bytes = (byte[]) Crls.nextElement(); if (debug.messageEnabled()) { debug.message("AMCRLStore.getCRLFromEntry: crl size = " + bytes.length); } cf = CertificateFactory.getInstance("X.509"); crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(bytes)); } catch (Exception e) { debug.error("Certificate: CertRevoked = ", e); } return crl; }
From source file:com.vmware.identity.samlservice.impl.CasIdmAccessor.java
@Override public CertPath getCertificatesForRelyingParty(String relyingParty) { logger.debug("getCertificatesForRelyingParty {}", relyingParty); List<X509Certificate> certificates = new ArrayList<X509Certificate>(); // only query relying party if it's not null // simply return an empty chain for 'null' relying party if (relyingParty != null) { try {/*from w ww . j ava 2 s . c om*/ // TODO support more than one cert RelyingParty rp = client.getRelyingPartyByUrl(tenant, relyingParty); Validate.notNull(rp); Certificate c = rp.getCertificate(); Validate.notNull(c); certificates.add((X509Certificate) c); } catch (Exception e) { logger.error("Caught exception ", e); } } try { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); CertPath certPath = certFactory.generateCertPath(certificates); return certPath; } catch (Exception e) { logger.error("Caught exception ", e); throw new IllegalStateException(e); } }
From source file:ddf.security.samlp.SimpleSign.java
public boolean validateSignature(String sigAlg, String queryParamsToValidate, String encodedSignature, @Nullable String encodedPublicKey) throws SignatureException { if (encodedPublicKey == null) { LOGGER.warn(/*from w w w . j a va 2s .c o m*/ "Could not verify the signature of request because there was no signing certificate. Ensure that the IdP Metadata includes a signing certificate."); return false; } try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); Certificate certificate = certificateFactory.generateCertificate( new ByteArrayInputStream(Base64.getMimeDecoder().decode(encodedPublicKey))); java.security.Signature sig; String jceSigAlg = JCEMapper.translateURItoJCEID(sigAlg); if (jceSigAlg == null) { throw new SignatureException(new NoSuchAlgorithmException( String.format("The Signature Algorithm %s is not supported.", sigAlg))); } try { sig = java.security.Signature.getInstance(jceSigAlg); } catch (NoSuchAlgorithmException e) { throw new SignatureException(e); } sig.initVerify(certificate.getPublicKey()); sig.update(queryParamsToValidate.getBytes(StandardCharsets.UTF_8)); return sig.verify(Base64.getMimeDecoder().decode(encodedSignature)); } catch (InvalidKeyException | CertificateException | java.security.SignatureException | IllegalArgumentException e) { throw new SignatureException(e); } }