List of usage examples for java.security.cert CertificateException CertificateException
public CertificateException(Throwable cause)
From source file:org.globus.security.stores.PEMKeyStore.java
private void initialize(String defaultDirectoryString, String directoryListString, String proxyFilename, String certFilename, String keyFilename) throws IOException, CertificateException { if (defaultDirectoryString != null) { defaultDirectory = new File(defaultDirectoryString);// .substring(0, // defaultDirectoryString.lastIndexOf(File.pathSeparator)) if (!defaultDirectory.exists()) { boolean directoryMade = defaultDirectory.mkdirs(); if (!directoryMade) { throw new IOException("Unable to create default certificate directory"); }//from w ww.jav a 2 s . com } loadDirectories(defaultDirectoryString); } if (directoryListString != null) { // String[] directoryList = directoryListString.split(","); loadDirectories(directoryListString); } try { if (proxyFilename != null && proxyFilename.length() > 0) { loadProxyCertificate(proxyFilename); } if ((certFilename != null && certFilename.length() > 0) && (keyFilename != null && keyFilename.length() > 0)) { loadCertificateKey(certFilename, keyFilename); } } catch (ResourceStoreException e) { throw new CertificateException(e); } catch (CredentialException e) { e.printStackTrace(); throw new CertificateException(e); } // for(String alias: this.aliasObjectMap.keySet()){ // System.out.println("alias = " + alias); // } }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
/** * Handles the HTTP 200 POST response (the MDN with status indications) * * @param transmissionId the transmissionId (used in HTTP headers as Message-ID) * @param outboundMic the calculated mic of the payload (should be verified against the one returned in MDN) * @param postResponse the http response to be decoded as MDN * @return/*from w ww . j a va2s.co m*/ */ MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic, CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) { try { HttpEntity entity = postResponse.getEntity(); // Any textual results? if (entity == null) { throw new IllegalStateException( "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode()); } String contents = EntityUtils.toString(entity); if (traceEnabled) { log.debug("HTTP-headers:"); Header[] allHeaders = postResponse.getAllHeaders(); for (Header header : allHeaders) { log.debug("" + header.getName() + ": " + header.getValue()); } log.debug("Contents:\n" + contents); log.debug("---------------------------"); } Header contentTypeHeader = postResponse.getFirstHeader("Content-Type"); if (contentTypeHeader == null) { throw new IllegalStateException("No Content-Type header in response, probably a server error"); } String contentType = contentTypeHeader.getValue(); MimeMessage mimeMessage = null; try { mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType)); try { mimeMessage.writeTo(System.out); } catch (MessagingException e) { throw new IllegalStateException("Unable to print mime message"); } } catch (MimeTypeParseException e) { throw new IllegalStateException("Invalid Content-Type header"); } // verify the signature of the MDN, we warn about dodgy signatures try { SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage); X509Certificate cert = signedMimeMessage.getSignersX509Certificate(); cert.checkValidity(); // Verify if the certificate used by the receiving Access Point in // the response message does not match its certificate published by the SMP if (peppolEndpointData.getCommonName() == null || !CommonName .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) { throw new CertificateException( "Common name in certificate from SMP does not match common name in AP certificate"); } log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString()); } catch (Exception ex) { log.warn("Exception when verifying MDN signature : " + ex.getMessage()); } // Verifies the actual MDN MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); String msg = mdnMimeMessageInspector.getPlainTextPartAsText(); if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) { return mimeMessage; } else { log.error("AS2 transmission failed with some error message, msg :" + msg); log.error(contents); throw new IllegalStateException("AS2 transmission failed : " + msg); } } catch (IOException e) { throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e); } finally { try { postResponse.close(); } catch (IOException e) { throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e); } } }
From source file:org.globus.gsi.stores.PEMKeyStore.java
/** * Initialize resources from filename, proxyfile name * * @param defaultDirectoryString//from w ww .java 2 s .co m * Name of the default directory name as: * "file: directory name" * @param directoryListString * @param proxyFilename * @param certFilename * @param keyFilename * * @throws IOException * @throws CertificateException */ private void initialize(String defaultDirectoryString, String directoryListString, String proxyFilename, String certFilename, String keyFilename) throws IOException, CertificateException { if (defaultDirectoryString != null) { defaultDirectory = new GlobusPathMatchingResourcePatternResolver().getResource(defaultDirectoryString) .getFile(); if (!defaultDirectory.exists()) { boolean directoryMade = defaultDirectory.mkdirs(); if (!directoryMade) { throw new IOException("Unable to create default certificate directory"); } } loadDirectories(defaultDirectoryString); } if (directoryListString != null) { loadDirectories(directoryListString); } try { if (proxyFilename != null && proxyFilename.length() > 0) { loadProxyCertificate(proxyFilename); } if ((certFilename != null && certFilename.length() > 0) && (keyFilename != null && keyFilename.length() > 0)) { loadCertificateKey(certFilename, keyFilename); } } catch (ResourceStoreException e) { throw new CertificateException(e); } catch (CredentialException e) { e.printStackTrace(); throw new CertificateException(e); } }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Accepts a legacy {@link javax.security.cert.X509Certificate} and returns an {@link X509Certificate}. The {@code javax.*} package certificate classes are for legacy compatibility and should * not be used for new development.//from ww w .ja v a 2s . c om * * @param legacyCertificate the {@code javax.security.cert.X509Certificate} * @return a new {@code java.security.cert.X509Certificate} * @throws CertificateException if there is an error generating the new certificate */ public static X509Certificate convertLegacyX509Certificate( javax.security.cert.X509Certificate legacyCertificate) throws CertificateException { if (legacyCertificate == null) { throw new IllegalArgumentException("The X.509 certificate cannot be null"); } try { return formX509Certificate(legacyCertificate.getEncoded()); } catch (javax.security.cert.CertificateEncodingException e) { throw new CertificateException(e); } }
From source file:controller.CCInstance.java
public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings, final SignatureListener sl) throws CertificateException, IOException, DocumentException, KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { PrivateKey pk;/*from w ww . java 2s . co m*/ final PdfReader reader = new PdfReader(pdfPath); pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias()); if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { String message = Bundle.getBundle().getString("fileDoesNotAllowChanges"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) { settings.setPageNumber(reader.getNumberOfPages() - 1); } if (null == pk) { String message = Bundle.getBundle().getString("noSmartcardFound"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) { String message = Bundle.getBundle().getString("certificateNullChain"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain(); final Certificate owner = embeddedCertificateChain.get(0); final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1); if (null == owner) { String message = Bundle.getBundle().getString("certificateNameUnknown"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final X509Certificate X509C = ((X509Certificate) lastCert); final Calendar now = Calendar.getInstance(); final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain( X509C); final Certificate[] fullCertificateChain; if (filledMissingCertsFromChainInTrustedKeystore.length < 2) { fullCertificateChain = new Certificate[embeddedCertificateChain.size()]; for (int i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } } else { fullCertificateChain = new Certificate[embeddedCertificateChain.size() + filledMissingCertsFromChainInTrustedKeystore.length - 1]; int i = 0; for (i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) { fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f]; } } // Leitor e Stamper FileOutputStream os = null; try { os = new FileOutputStream(destination); } catch (FileNotFoundException e) { String message = Bundle.getBundle().getString("outputFileError"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new IOException(message); } // Aparncia da Assinatura final char pdfVersion; switch (Settings.getSettings().getPdfVersion()) { case "/1.2": pdfVersion = PdfWriter.VERSION_1_2; break; case "/1.3": pdfVersion = PdfWriter.VERSION_1_3; break; case "/1.4": pdfVersion = PdfWriter.VERSION_1_4; break; case "/1.5": pdfVersion = PdfWriter.VERSION_1_5; break; case "/1.6": pdfVersion = PdfWriter.VERSION_1_6; break; case "/1.7": pdfVersion = PdfWriter.VERSION_1_7; break; default: pdfVersion = PdfWriter.VERSION_1_7; } final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0 ? PdfStamper.createSignature(reader, os, pdfVersion) : PdfStamper.createSignature(reader, os, pdfVersion, null, true)); final PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setSignDate(now); appearance.setReason(settings.getReason()); appearance.setLocation(settings.getLocation()); appearance.setCertificationLevel(settings.getCertificationLevel()); appearance.setSignatureCreator(SIGNATURE_CREATOR); appearance.setCertificate(owner); final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath)); if (settings.isVisibleSignature()) { appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1, fieldName); appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION); if (null != settings.getAppearance().getImageLocation()) { appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation())); } com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0) .getBaseFont()); font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB())); if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) { font.setStyle(Font.BOLD + Font.ITALIC); } else if (settings.getAppearance().isBold()) { font.setStyle(Font.BOLD); } else if (settings.getAppearance().isItalic()) { font.setStyle(Font.ITALIC); } else { font.setStyle(Font.PLAIN); } appearance.setLayer2Font(font); String text = ""; if (settings.getAppearance().isShowName()) { if (!settings.getCcAlias().getName().isEmpty()) { text += settings.getCcAlias().getName() + "\n"; } } if (settings.getAppearance().isShowReason()) { if (!settings.getReason().isEmpty()) { text += settings.getReason() + "\n"; } } if (settings.getAppearance().isShowLocation()) { if (!settings.getLocation().isEmpty()) { text += settings.getLocation() + "\n"; } } if (settings.getAppearance().isShowDate()) { DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("Z"); text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n"; } if (!settings.getText().isEmpty()) { text += settings.getText(); } PdfTemplate layer2 = appearance.getLayer(2); Rectangle rect = settings.getPositionOnDocument(); Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight()); float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT); ColumnText ct = new ColumnText(layer2); ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT); ct.setAlignment(Element.ALIGN_MIDDLE); int align; switch (settings.getAppearance().getAlign()) { case 0: align = Element.ALIGN_LEFT; break; case 1: align = Element.ALIGN_CENTER; break; case 2: align = Element.ALIGN_RIGHT; break; default: align = Element.ALIGN_LEFT; } ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(), size, align); ct.go(); } else { appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName); } // CRL <- Pesado! final ArrayList<CrlClient> crlList = null; // OCSP OcspClient ocspClient = new OcspClientBouncyCastle(); // TimeStamp TSAClient tsaClient = null; if (settings.isTimestamp()) { tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null); } final String hashAlg = getHashAlgorithm(X509C.getSigAlgName()); final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName()); final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName()); try { MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient, 0, MakeSignature.CryptoStandard.CMS); if (sl != null) { sl.onSignatureComplete(pdfPath, true, ""); } return true; } catch (Exception e) { os.flush(); os.close(); new File(destination).delete(); if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled")); } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions")); } else if (e instanceof ExceptionConverter) { String message = Bundle.getBundle().getString("timestampFailed"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } else { if (sl != null) { sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog")); } controller.Logger.getLogger().addEntry(e); } return false; } }
From source file:org.apache.nifi.security.util.CertificateUtils.java
/** * Accepts an abstract {@link java.security.cert.Certificate} and returns an {@link X509Certificate}. Because {@code sslSocket.getSession().getPeerCertificates()} returns an array of the * abstract certificates, they must be translated to X.509 to replace the functionality of {@code sslSocket.getSession().getPeerCertificateChain()}. * * @param abstractCertificate the {@code java.security.cert.Certificate} * @return a new {@code java.security.cert.X509Certificate} * @throws CertificateException if there is an error generating the new certificate *//* w w w .j av a2s . com*/ public static X509Certificate convertAbstractX509Certificate(java.security.cert.Certificate abstractCertificate) throws CertificateException { if (abstractCertificate == null || !(abstractCertificate instanceof X509Certificate)) { throw new IllegalArgumentException("The certificate cannot be null and must be an X.509 certificate"); } try { return formX509Certificate(abstractCertificate.getEncoded()); } catch (java.security.cert.CertificateEncodingException e) { throw new CertificateException(e); } }
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
/** * Accepts an abstract {@link Certificate} and returns an {@link X509Certificate}. Because {@code sslSocket.getSession().getPeerCertificates()} returns an array of the * abstract certificates, they must be translated to X.509 to replace the functionality of {@code sslSocket.getSession().getPeerCertificateChain()}. * * @param abstractCertificate the {@code java.security.cert.Certificate} * @return a new {@code java.security.cert.X509Certificate} * @throws CertificateException if there is an error generating the new certificate *//*from www. java 2s .c o m*/ public static X509Certificate convertAbstractX509Certificate(Certificate abstractCertificate) throws CertificateException { if (abstractCertificate == null || !(abstractCertificate instanceof X509Certificate)) { throw new IllegalArgumentException("The certificate cannot be null and must be an X.509 certificate"); } try { return formX509Certificate(abstractCertificate.getEncoded()); } catch (java.security.cert.CertificateEncodingException e) { throw new CertificateException(e); } }
From source file:org.globus.security.stores.PEMKeyStore.java
private void loadDirectories(String directoryList) throws CertificateException { try {/* w w w. j a va 2 s .c o m*/ caDelegate.loadWrappers(directoryList); Map<String, ResourceTrustAnchor> wrapperMap = caDelegate.getWrapperMap(); for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) { String alias = trustAnchor.getResourceURL().toExternalForm(); TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor(); X509Certificate trustCert = tmpTrustAnchor.getTrustedCert(); certFilenameMap.put(trustCert, alias); if (this.aliasObjectMap == null) { System.out.println("Alias Map Null"); } this.aliasObjectMap.put(alias, trustAnchor); } } catch (ResourceStoreException e) { throw new CertificateException(e); } }
From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java
@Override public void engineLoad(LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, CertificateException { if (this.sessionStore != null) { if (this.needToCloseSessionStore) this.sessionStore.close(); }/* w ww . j a va2 s .c o m*/ if (param instanceof PKCS11SessionStore) { this.sessionStore = (PKCS11SessionStore) param; this.needToCloseSessionStore = false; } else { this.sessionStore = new PKCS11SessionStore(); this.needToCloseSessionStore = true; this.sessionStore.open(this.provider, param); } // OK, the session is up and running, now get the certificates // and keys. this.entries = new HashMap<String, PKCS11KSEntry>(); List<PKCS11PrivateKey> privKeys = PKCS11PrivateKey.getPrivateKeys(this.sessionStore.getSession()); Map<PKCS11Id, PKCS11KSEntry> privKeysById = new HashMap<PKCS11Id, PKCS11KSEntry>(); for (PKCS11PrivateKey privKey : privKeys) { privKeysById.put(privKey.getId(), new PKCS11KSEntry(privKey)); } List<PKCS11Certificate> certificates = PKCS11Certificate.getCertificates(this.sessionStore.getSession()); for (PKCS11Certificate certificate : certificates) { // contruct a unique name for certificate entries. String subj = certificate.getSubject().toString(); String name = subj; name = subj; int i = 1; while (this.entries.containsKey(name) && i < MAX_SIMILAR_CERTIFICATES) { ++i; name = String.format("%s_%02X", subj, i); } if (i >= MAX_SIMILAR_CERTIFICATES) { throw new CertificateException("More than " + MAX_SIMILAR_CERTIFICATES + " instances of the same certificate subject [" + subj + "]found on the token."); } PKCS11KSEntry entry = new PKCS11KSEntry(certificate); PKCS11KSEntry pk_entry = privKeysById.get(certificate.getId()); if (pk_entry != null) { entry.privateKey = pk_entry.privateKey; pk_entry.certificate = certificate; } this.entries.put(name, entry); } for (PKCS11Id id : privKeysById.keySet()) { PKCS11KSEntry entry = privKeysById.get(id); if (entry.certificate != null) continue; String name = "ID_" + id; this.entries.put(name, entry); } }
From source file:osmcd.mapsources.loader.MapPackManager.java
/** * Verifies the class file signatures of the specified map pack * // ww w .j a va 2 s . c o m * @param mapPackFile * @throws IOException * @throws CertificateException */ public void testMapPack(File mapPackFile) throws IOException, CertificateException { String fileName = mapPackFile.getName(); JarFile jf = new JarFile(mapPackFile, true); try { Enumeration<JarEntry> it = jf.entries(); while (it.hasMoreElements()) { JarEntry entry = it.nextElement(); // We verify only class files if (!entry.getName().endsWith(".class")) continue; // directory or other entry // Get the input stream (triggers) the signature verification for the specific class Utilities.readFully(jf.getInputStream(entry)); if (entry.getCodeSigners() == null) throw new CertificateException("Unsigned class file found: " + entry.getName()); CodeSigner signer = entry.getCodeSigners()[0]; List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates(); if (cp.size() > 1) throw new CertificateException("Signature certificate not accepted: " + "certificate path contains more than one certificate"); // Compare the used certificate with the mapPack certificate if (!mapPackCert.equals(cp.get(0))) throw new CertificateException( "Signature certificate not accepted: " + "not the MapPack signer certificate"); } Manifest mf = jf.getManifest(); Attributes a = mf.getMainAttributes(); String mpv = a.getValue("MapPackVersion"); if (mpv == null) throw new IOException("MapPackVersion info missing!"); int mapPackVersion = Integer.parseInt(mpv); if (requiredMapPackVersion != mapPackVersion) throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version."); ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource"); if (entry == null) throw new IOException("MapSources services list is missing in file " + fileName); } finally { jf.close(); } }