/** * Test for <code>KeyStoreException(Throwable)</code> constructor Assertion: constructs * KeyStoreException when <code>cause</code> is not null */ public void testKeyStoreException05() { KeyStoreException tE = new KeyStoreException(tCause); if (tE.getMessage() != null) { String toS = tCause.toString(); String getM = tE.getMessage(); assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1)); } assertNotNull("getCause() must not return null", tE.getCause()); assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause); }
/** * ִ��http���á�true:�ɹ� false:ʧ�� * * @return boolean */ public boolean call() { boolean isRet = false; // http if (null == this.caFile && null == this.certFile) { try { this.callHttp(); isRet = true; } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; } // https try { this.callHttps(); isRet = true; } catch (UnrecoverableKeyException e) { this.errInfo = e.getMessage(); } catch (KeyManagementException e) { this.errInfo = e.getMessage(); } catch (CertificateException e) { this.errInfo = e.getMessage(); } catch (KeyStoreException e) { this.errInfo = e.getMessage(); } catch (NoSuchAlgorithmException e) { this.errInfo = e.getMessage(); } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; }
public static KeyPair getPrivateKey(String alias, char[] password) throws FileNotFoundException, IOException, CertificateException { try { KeyStore ks = KeyStore.getInstance("JKS"); char[] passPhrase = "123456".toCharArray(); // BASE64Encoder myB64 = new BASE64Encoder(); File certificateFile = new File("C:\\Temp\\repositorio.jks"); ks.load(new FileInputStream(certificateFile), passPhrase); // Get private key Key key = ks.getKey(alias, password); if (key instanceof PrivateKey) { // Get certificate of public key Certificate cert = ks.getCertificate(alias); // Get public key PublicKey publicKey = cert.getPublicKey(); // Return a key pair return new KeyPair(publicKey, (PrivateKey) key); } } catch (UnrecoverableKeyException e) { System.out.print(e.getMessage()); } catch (NoSuchAlgorithmException e) { System.out.print(e.getMessage()); } catch (KeyStoreException e) { System.out.print(e.getMessage()); } return null; }
/** * Test for <code>KeyStoreException(String)</code> constructor Assertion: constructs * KeyStoreException with detail message msg. Parameter <code>msg</code> is not null. */ public void testKeyStoreException02() { KeyStoreException tE; for (int i = 0; i < msgs.length; i++) { tE = new KeyStoreException(msgs[i]); assertEquals("getMessage() must return: ".concat(msgs[i]), tE.getMessage(), msgs[i]); assertNull("getCause() must return null", tE.getCause()); } }
private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) { KeyStore ks = getKeyStore(keyStoreName, password); KeyManagerFactory keyManagerFactory = null; try { keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(ks, password.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); return context.getSocketFactory(); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyManagementException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
private KeyStore getKeyStore(String keyStoreName, String password) { KeyStore ks = null; FileInputStream fis = null; try { ks = KeyStore.getInstance("JKS"); char[] passwordArray = password.toCharArray(); fis = new java.io.FileInputStream(keyStoreName); ks.load(fis, passwordArray); fis.close(); } catch (CertificateException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } } return ks; }
private void sslFileTransfer(String filename) { try { KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore); trusted.load(in, "mysecret".toCharArray()); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trusted); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL(host); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); transfer(urlConnection, filename); // SSLSocketFactory sf = new SSLSocketFactory(trusted); // // Hostname verification from certificate // // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 // sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // // Socket sslsocket = sf.createSocket(); // sslsocket.setKeepAlive(true); // // InetSocketAddress address = new InetSocketAddress(host, 443); // sslsocket.connect(address); // // OutputStream sout = sslsocket.getOutputStream(); } catch (KeyStoreException e) { Log.v("mark", "KeyStoreException:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { Log.v("mark", "NoSuchAlgorithmException:" + e.getMessage()); } catch (CertificateException e) { Log.v("mark", "CertificateException:" + e.getMessage()); } catch (IOException e) { Log.v("mark", "IOException:" + e.getMessage()); } catch (KeyManagementException e) { Log.v("mark", "KeyManagementException:" + e.getMessage()); } }
private static String getAlias(KeyStore keyStore) throws IOException { String alias = null; try { Enumeration nombres = keyStore.aliases(); while (nombres.hasMoreElements()) { String tmpAlias = (String) nombres.nextElement(); if (keyStore.isKeyEntry(tmpAlias)) { alias = tmpAlias; } } } catch (KeyStoreException e) { throw new IOException("Error: " + e.getMessage()); } return alias; }
/** * Test for <code>KeyStoreException(String, Throwable)</code> constructor Assertion: constructs * KeyStoreException when <code>cause</code> is not null <code>msg</code> is not null */ public void testKeyStoreException09() { KeyStoreException tE; for (int i = 0; i < msgs.length; i++) { tE = new KeyStoreException(msgs[i], tCause); String getM = tE.getMessage(); String toS = tCause.toString(); if (msgs[i].length() > 0) { assertTrue("getMessage() must contain ".concat(msgs[i]), getM.indexOf(msgs[i]) != -1); if (!getM.equals(msgs[i])) { assertTrue("getMessage() should contain ".concat(toS), getM.indexOf(toS) != -1); } } assertNotNull("getCause() must not return null", tE.getCause()); assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause); } }
private KeyStore getKeyStore() throws CertificateException, IOException { KeyStore ks = null; try { ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(this.pathSignature), this.passSignature.toCharArray()); } catch (KeyStoreException e) { throw new IOException("Error: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Error: " + e.getMessage()); } catch (CertificateException e) { throw new IOException("Error: " + e.getMessage()); } catch (IOException e) { throw new IOException("Error: " + e.getMessage()); } return ks; }
protected void execute() throws CertificateException, IOException { KeyStore keyStore = getKeyStore(); if (keyStore == null) { throw new IOException("No se pudo obtener almacen de firma."); } String alias = getAlias(keyStore); X509Certificate certificate = null; try { certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw new IOException("No existe ningún certificado para firmar."); } } catch (KeyStoreException e1) { throw new IOException("Error: " + e1.getMessage()); } PrivateKey privateKey = null; KeyStore tmpKs = keyStore; try { privateKey = (PrivateKey) tmpKs.getKey(alias, this.passSignature.toCharArray()); } catch (UnrecoverableKeyException e) { throw new IOException("No existe clave privada para firmar."); } catch (KeyStoreException e) { throw new IOException("No existe clave privada para firmar."); } catch (NoSuchAlgorithmException e) { throw new IOException("No existe clave privada para firmar."); } Provider provider = keyStore.getProvider(); DataToSign dataToSign = createDataToSign(); FirmaXML firma = new FirmaXML(); Document docSigned = null; try { Object[] res = firma.signFile(certificate, dataToSign, privateKey, provider); docSigned = (Document) res[0]; } catch (Exception ex) { throw new IOException("Error realizando la firma: " + ex.getMessage()); } String filePath = getPathOut() + File.separatorChar + getSignatureFileName(); saveDocumenteDisk(docSigned, filePath); }
public void onGenerateClicked(View view) { try { log.debug("Key name {}", getKeyName()); log.debug("Key type {}", getKeyType()); log.debug("Key bits {}", getKeyBits()); KeyChain.getInstance(getActivity()) .generateKeyAsync(getKeyName(), getKeyType(), getKeyBits()); getActivity() .finish(); // this has to be changed if we are using single activity at some point } catch (InvalidInputException e) { log.warn("TODO: handle specific cases"); Toast.makeText(getActivity(), R.string.pk_invalid_input, Toast.LENGTH_SHORT).show(); } catch (ViewNotFoundException e) { log.error(e.getMessage(), e); } catch (KeyStoreException e) { log.error(e.getMessage(), e); } }
/** * Test for <code>KeyStoreException(String)</code> constructor Assertion: constructs * KeyStoreException when <code>msg</code> is null */ public void testKeyStoreException03() { String msg = null; KeyStoreException tE = new KeyStoreException(msg); assertNull("getMessage() must return null.", tE.getMessage()); assertNull("getCause() must return null", tE.getCause()); }
/** Creates a new SSLSocket bound to ContextWrapper * */ private Socket createSocket() throws IOException { if (_factory == null) { Properties attributes = getCurrentProperties(); StoreUpdateListener listener = new StoreUpdateListener() { public void loadingNotification( String location, String type, Severity level, Exception cause) { if (level != Severity.NOTIFICATION) { System.out.println( "Error when creating or using SSL socket. Type " + type + " level: " + level + " cause: " + cause.getClass() + ":" + cause.getMessage()); } else { // log successful (re)loading } } }; ArrayList<StoreUpdateListener> listenerList = new ArrayList<StoreUpdateListener>(); listenerList.add(listener); RevocationParameters revParam = new RevocationParameters( CrlCheckingMode.REQUIRE, new OCSPParametes(), false, RevocationCheckingOrder.CRL_OCSP); String crlCheckingMode = (String) attributes.get(CRL_CHEKING_MODE_STRING); if (crlCheckingMode != null) { if (crlCheckingMode.equalsIgnoreCase("ifvalid")) { revParam = new RevocationParameters( CrlCheckingMode.IF_VALID, new OCSPParametes(), false, RevocationCheckingOrder.CRL_OCSP); } else { if (crlCheckingMode.equalsIgnoreCase("ignore")) { revParam = new RevocationParameters( CrlCheckingMode.IGNORE, new OCSPParametes(), false, RevocationCheckingOrder.CRL_OCSP); } } } ProxySupport proxySupport = ProxySupport.ALLOW; String proxySupportString = (String) attributes.get(PROXY_SUPPORT_STRING); if (proxySupportString != null) { if (proxySupportString.equalsIgnoreCase("no") || proxySupportString.equalsIgnoreCase("false")) { proxySupport = ProxySupport.DENY; } } ValidatorParams validatorParams = new ValidatorParams(revParam, proxySupport, listenerList); String trustStoreLocation = (String) attributes.get(TRUSTSTORE_STRING); if (trustStoreLocation == null) { throw new IOException( "No truststore defined, unable to load CA certificates and thus create SSL socket."); } String namespaceModeString = (String) attributes.get(NAMESPACE_STRING); NamespaceCheckingMode namespaceMode = NamespaceCheckingMode.EUGRIDPMA_AND_GLOBUS; if (namespaceModeString != null) { if (namespaceModeString.equalsIgnoreCase("no") || namespaceModeString.equalsIgnoreCase("false") || namespaceModeString.equalsIgnoreCase("off")) { namespaceMode = NamespaceCheckingMode.IGNORE; } else { if (namespaceModeString.equalsIgnoreCase("require")) { namespaceMode = NamespaceCheckingMode.EUGRIDPMA_AND_GLOBUS_REQUIRE; } } } String intervalString = (String) attributes.get(UPDATEINTERVAL_STRING); long intervalMS = 3600000; // update ever hour if (intervalString != null) { intervalMS = Long.parseLong(intervalString); } OpensslCertChainValidator validator = new OpensslCertChainValidator( trustStoreLocation, namespaceMode, intervalMS, validatorParams); X509Credential credentials = null; String proxyLoc = (String) attributes.get(PROXY_STRING); if (proxyLoc != null) { try { credentials = new PEMCredential(proxyLoc, (char[]) null); } catch (KeyStoreException e) { throw new IOException("Error opening proxy from " + proxyLoc + ": ", e); } catch (CertificateException e) { throw new IOException("Error reading proxy from " + proxyLoc + ": ", e); } } else { String hostCertLoc = (String) attributes.get(CERT_STRING); if (hostCertLoc == null) { throw new IOException( "Variable hostcert undefined, cannot start server with SSL/TLS without host certificate."); } java.security.cert.X509Certificate[] hostCertChain = CertificateUtils.loadCertificateChain(new FileInputStream(hostCertLoc), Encoding.PEM); String password = (String) attributes.get(PASSWORD_STRING); String hostKeyLoc = (String) attributes.get(KEY_STRING); if (hostKeyLoc == null) { throw new IOException( "Variable hostkey undefined, cannot start server with SSL/TLS without host private key."); } PrivateKey hostKey = CertificateUtils.loadPrivateKey( new FileInputStream(hostKeyLoc), Encoding.PEM, password == null ? null : password.toCharArray()); try { credentials = new KeyAndCertCredential(hostKey, hostCertChain); } catch (KeyStoreException e) { throw new IOException("Error while creating keystore: " + e + ": " + e.getMessage(), e); } } SSLSocketFactory newFactory = SocketFactoryCreator.getSocketFactory(credentials, validator); SSLSocket socket = (SSLSocket) newFactory.createSocket(); return socket; } else { return _factory.createSocket(); } }
/** * Performs test signatures for the specified keys or for all if "all" specified. * * @param keyStore Loaded keystore to read keys from * @param alias Alias of key to test or "all" to test all * @param authCode Key password (if used, ie for JKS only) * @param signatureProvider Provider for creating the signature * @return The results for each key found * @throws CryptoTokenOfflineException In case the key could not be used */ public static Collection<KeyTestResult> testKey( KeyStore keyStore, String alias, char[] authCode, String signatureProvider) throws CryptoTokenOfflineException { if (LOG.isDebugEnabled()) { LOG.debug("testKey for alias: " + alias); } final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>(); try { final Enumeration<String> e = keyStore.aliases(); while (e.hasMoreElements()) { final String keyAlias = e.nextElement(); if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) { if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } if (keyStore.isKeyEntry(keyAlias)) { String status; String publicKeyHash = null; boolean success = false; try { final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode); final Certificate entryCert = keyStore.getCertificate(keyAlias); if (entryCert != null) { final PublicKey publicKey = entryCert.getPublicKey(); publicKeyHash = createKeyHash(publicKey); testSignAndVerify(privateKey, publicKey, signatureProvider); success = true; status = ""; } else { status = "Not testing keys with alias " + keyAlias + ". No certificate exists."; } } catch (ClassCastException ce) { status = "Not testing keys with alias " + keyAlias + ". Not a private key."; } catch (InvalidKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (KeyStoreException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchAlgorithmException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (NoSuchProviderException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (SignatureException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } catch (UnrecoverableKeyException ex) { LOG.error("Error testing key: " + keyAlias, ex); status = ex.getMessage(); } result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash)); } } } } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } if (LOG.isDebugEnabled()) { LOG.debug("<testKey"); } return result; }
public void actionPerformed(ActionEvent e) { final String S_ProcName = "actionPerformed"; CFBamSwingMainJFrame mainJFrame = null; { Container cont = getParent(); while ((cont != null) && (!(cont instanceof CFBamSwingMainJFrame))) { cont = cont.getParent(); } if (cont != null) { mainJFrame = (CFBamSwingMainJFrame) cont; } } char pw[] = textKeystorePassword.getPassword(); String keystorePassword; if (pw != null) { keystorePassword = new String(pw); } else { keystorePassword = null; } CFBamClientConfigurationFile configFile = swingSchema.getClientConfigurationFile(); String keystoreFileName = configFile.getKeyStore(); boolean exitApp = false; boolean exitForm = false; boolean creatingKeystore = false; KeyStore keyStore = null; File keystoreFile = new File(keystoreFileName); if (!keystoreFile.exists()) { int userOption = JOptionPane.NO_OPTION; try { userOption = JOptionPane.showOptionDialog( null, "Would you like to create the keystore \"" + keystoreFileName + "\"?\n" + "Selecting No will exit the application so you can edit the client configuration file and restart.", "Create Keystore?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); } catch (HeadlessException x) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught HeadlessException -- " + x.getMessage(), x); } if (userOption == JOptionPane.YES_OPTION) { creatingKeystore = true; JInternalFrame nextForm = swingSchema.newCreateKeystoreJInternalFrame(); getDesktopPane().add(nextForm); nextForm.setVisible(true); nextForm.show(); Container cont = getParent(); while ((cont != null) && (!(cont instanceof JInternalFrame))) { cont = cont.getParent(); } if (cont != null) { JInternalFrame frame = (JInternalFrame) cont; try { frame.setClosed(true); } catch (Exception x) { } } } else { exitApp = true; } } else if (!keystoreFile.isFile()) { JOptionPane.showMessageDialog( null, "The referenced JCEKS keystore \"" + keystoreFileName + "\" is not a file.", "Error", JOptionPane.ERROR_MESSAGE, null); exitApp = true; } else if (!keystoreFile.canRead()) { JOptionPane.showMessageDialog( null, "Permission denied attempting to access JCEKS keystore \"" + keystoreFileName + "\".", "Error", JOptionPane.ERROR_MESSAGE, null); exitApp = true; } if ((!exitApp) && (!creatingKeystore)) { try { keyStore = KeyStore.getInstance("jceks"); char[] caPassword = keystorePassword.toCharArray(); FileInputStream input = new FileInputStream(keystoreFileName); keyStore.load(input, caPassword); input.close(); swingSchema.setKeyStore(keyStore); exitForm = true; } catch (CertificateException x) { keyStore = null; JOptionPane.showMessageDialog( null, "Could not open keystore due to CertificateException -- " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, null); exitApp = true; } catch (IOException x) { keyStore = null; JOptionPane.showMessageDialog( null, "Could not open keystore due to IOException -- " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, null); } catch (KeyStoreException x) { keyStore = null; JOptionPane.showMessageDialog( null, "Could not open keystore due to KeyStoreException -- " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, null); exitApp = true; } catch (NoSuchAlgorithmException x) { keyStore = null; JOptionPane.showMessageDialog( null, "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, null); exitApp = true; } } if (exitApp) { swingSchema.setKeyStore(null); mainJFrame.exitApplication(); } else if (exitForm) { JInternalFrame nextForm = swingSchema.newOpenDeviceKeyJInternalFrame(); getDesktopPane().add(nextForm); nextForm.setVisible(true); nextForm.show(); Container cont = getParent(); while ((cont != null) && (!(cont instanceof JInternalFrame))) { cont = cont.getParent(); } if (cont != null) { JInternalFrame frame = (JInternalFrame) cont; try { frame.setClosed(true); } catch (Exception x) { } } } }
private AlfrescoRuntimeException signFile( final NodeRef nodeRefToSign, final DigitalSigningDTO signingDTO, final File alfTempDir, final String alias, final KeyStore ks, final PrivateKey key, final Certificate[] chain) { final String fileNameToSign = fileFolderService.getFileInfo(nodeRefToSign).getName(); File fileConverted = null; File tempDir = null; try { ContentReader fileToSignContentReader = getReader(nodeRefToSign); if (fileToSignContentReader != null) { String newName = null; // Check if document is PDF or transform it if (!MimetypeMap.MIMETYPE_PDF.equals(fileToSignContentReader.getMimetype())) { // Transform document in PDF document final ContentTransformer tranformer = contentTransformerRegistry.getTransformer( fileToSignContentReader.getMimetype(), fileToSignContentReader.getSize(), MimetypeMap.MIMETYPE_PDF, new TransformationOptions()); if (tranformer != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); fileConverted = new File(tempDir, fileNameToSign + "_" + System.currentTimeMillis() + ".pdf"); if (fileConverted != null) { final ContentWriter newDoc = new FileContentWriter(fileConverted); if (newDoc != null) { newDoc.setMimetype(MimetypeMap.MIMETYPE_PDF); tranformer.transform(fileToSignContentReader, newDoc); fileToSignContentReader = new FileContentReader(fileConverted); final String originalName = (String) nodeService.getProperty(nodeRefToSign, ContentModel.PROP_NAME); newName = originalName.substring(0, originalName.lastIndexOf(".")) + ".pdf"; } } } } else { log.error( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] No suitable converter found to convert the document in PDF."); } } // Convert PDF in PDF/A format final File pdfAFile = convertPdfToPdfA(fileToSignContentReader.getContentInputStream()); final PdfReader reader = new PdfReader(new FileInputStream(pdfAFile)); if (nodeRefToSign != null) { tempDir = new File(alfTempDir.getPath() + File.separatorChar + nodeRefToSign.getId()); if (tempDir != null) { tempDir.mkdir(); final File file = new File(tempDir, fileNameToSign); if (file != null) { final FileOutputStream fout = new FileOutputStream(file); final PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); if (stp != null) { final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (sap != null) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(signingDTO.getSignReason()); sap.setLocation(signingDTO.getSignLocation()); sap.setContact(signingDTO.getSignContact()); sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); sap.setImageScale(1); // digital signature if (signingDTO.getSigningField() != null && !signingDTO.getSigningField().trim().equalsIgnoreCase("")) { Image img = null; if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); final AcroFields af = reader.getAcroFields(); if (af != null) { final List<FieldPosition> positions = af.getFieldPositions(signingDTO.getSigningField()); if (positions != null && positions.size() > 0 && positions.get(0) != null && positions.get(0).position != null) { final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, Float.valueOf(positions.get(0).position.getWidth()).intValue(), Float.valueOf(positions.get(0).position.getHeight()).intValue()); img = Image.getInstance(newImg, null); } else { log.error( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The field '" + signingDTO.getSigningField() + "' doesn't exist in the document."); } } if (img == null) { img = Image.getInstance( ImageIO.read(imageContentReader.getContentInputStream()), null); } sap.setImage(img); } sap.setVisibleSignature(signingDTO.getSigningField()); } else { int pageToSign = 1; if (DigitalSigningDTO.PAGE_LAST.equalsIgnoreCase( signingDTO.getPages().trim())) { pageToSign = reader.getNumberOfPages(); } else if (DigitalSigningDTO.PAGE_SPECIFIC.equalsIgnoreCase( signingDTO.getPages().trim())) { if (signingDTO.getPageNumber() > 0 && signingDTO.getPageNumber() <= reader.getNumberOfPages()) { pageToSign = signingDTO.getPageNumber(); } else { throw new AlfrescoRuntimeException("Page number is out of bound."); } } if (signingDTO.getImage() != null) { final ContentReader imageContentReader = getReader(signingDTO.getImage()); // Resize image final BufferedImage newImg = scaleImage( ImageIO.read(imageContentReader.getContentInputStream()), BufferedImage.TYPE_INT_RGB, signingDTO.getSignWidth(), signingDTO.getSignHeight()); final Image img = Image.getInstance(newImg, null); sap.setImage(img); } if (signingDTO.getPosition() != null && !DigitalSigningDTO.POSITION_CUSTOM.equalsIgnoreCase( signingDTO.getPosition().trim())) { final Rectangle pageRect = reader.getPageSizeWithRotation(1); sap.setVisibleSignature( positionSignature( signingDTO.getPosition(), pageRect, signingDTO.getSignWidth(), signingDTO.getSignHeight(), signingDTO.getxMargin(), signingDTO.getyMargin()), pageToSign, null); } else { sap.setVisibleSignature( new Rectangle( signingDTO.getLocationX(), signingDTO.getLocationY(), signingDTO.getLocationX() + signingDTO.getSignWidth(), signingDTO.getLocationY() - signingDTO.getSignHeight()), pageToSign, null); } } stp.close(); NodeRef destinationNode = null; NodeRef originalDoc = null; boolean addAsNewVersion = false; if (signingDTO.getDestinationFolder() == null) { destinationNode = nodeRefToSign; nodeService.addAspect(destinationNode, ContentModel.ASPECT_VERSIONABLE, null); addAsNewVersion = true; } else { originalDoc = nodeRefToSign; destinationNode = createDestinationNode( file.getName(), signingDTO.getDestinationFolder(), nodeRefToSign); } if (destinationNode != null) { final ContentWriter writer = contentService.getWriter(destinationNode, ContentModel.PROP_CONTENT, true); if (writer != null) { writer.setEncoding(fileToSignContentReader.getEncoding()); writer.setMimetype("application/pdf"); writer.putContent(file); file.delete(); if (fileConverted != null) { fileConverted.delete(); } nodeService.addAspect( destinationNode, SigningModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); nodeService.setProperty( destinationNode, SigningModel.PROP_REASON, signingDTO.getSignReason()); nodeService.setProperty( destinationNode, SigningModel.PROP_LOCATION, signingDTO.getSignLocation()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNATUREDATE, new java.util.Date()); nodeService.setProperty( destinationNode, SigningModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); if (newName != null) { nodeService.setProperty(destinationNode, ContentModel.PROP_NAME, newName); } final X509Certificate c = (X509Certificate) ks.getCertificate(alias); nodeService.setProperty( destinationNode, SigningModel.PROP_VALIDITY, c.getNotAfter()); nodeService.setProperty( destinationNode, SigningModel.PROP_ORIGINAL_DOC, originalDoc); if (!addAsNewVersion) { if (!nodeService.hasAspect(originalDoc, SigningModel.ASPECT_ORIGINAL_DOC)) { nodeService.addAspect( originalDoc, SigningModel.ASPECT_ORIGINAL_DOC, new HashMap<QName, Serializable>()); } nodeService.createAssociation( originalDoc, destinationNode, SigningModel.PROP_RELATED_DOC); } } } else { log.error("[" + fileNameToSign + "] Destination node is not a valid NodeRef."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Destination node is not a valid NodeRef."); } } else { log.error("[" + fileNameToSign + "] Unable to get PDF appearance signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get PDF appearance signature."); } } else { log.error("[" + fileNameToSign + "] Unable to create PDF signature."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to create PDF signature."); } } } } else { log.error("[" + fileNameToSign + "] Unable to get document to sign content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] Unable to get document to sign content."); } if (pdfAFile != null) { pdfAFile.delete(); } return null; } else { log.error("[" + fileNameToSign + "] The document has no content."); return new AlfrescoRuntimeException( "[" + fileNameToSign + "] The document has no content."); } } catch (KeyStoreException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (ContentIOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (IOException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } catch (DocumentException e) { log.error("[" + fileNameToSign + "] " + e); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { log.error("[" + fileNameToSign + "] " + ex); return new AlfrescoRuntimeException("[" + fileNameToSign + "] " + ex.getMessage(), ex); } } } }
/** * Sign file. * * @param signingDTO sign informations * @param pdfSignedFile signed pdf returned */ public void sign(final DigitalSigningDTO signingDTO) { if (signingDTO != null) { try { Security.addProvider(new BouncyCastleProvider()); final File alfTempDir = TempFileProvider.getTempDir(); if (alfTempDir != null) { final String keyType = (String) nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE); if (SigningConstants.KEY_TYPE_X509.equals(keyType)) { // Sign the file final KeyStore ks = KeyStore.getInstance("pkcs12"); final ContentReader keyContentReader = getReader(signingDTO.getKeyFile()); if (keyContentReader != null && ks != null && signingDTO.getKeyPassword() != null) { final List<AlfrescoRuntimeException> errors = new ArrayList<AlfrescoRuntimeException>(); // Get crypted secret key and decrypt it final Serializable encryptedPropertyValue = nodeService.getProperty( signingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET); final Serializable decryptedPropertyValue = metadataEncryptor.decrypt( SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue); // Decrypt key content InputStream decryptedKeyContent; try { decryptedKeyContent = CryptUtils.decrypt( decryptedPropertyValue.toString(), keyContentReader.getContentInputStream()); } catch (Throwable e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } ks.load( new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)), signingDTO.getKeyPassword().toCharArray()); final String alias = (String) nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYALIAS); final PrivateKey key = (PrivateKey) ks.getKey(alias, signingDTO.getKeyPassword().toCharArray()); final Certificate[] chain = ks.getCertificateChain(alias); final Iterator<NodeRef> itFilesToSign = signingDTO.getFilesToSign().iterator(); while (itFilesToSign.hasNext()) { final NodeRef nodeRefToSign = itFilesToSign.next(); final AlfrescoRuntimeException exception = signFile(nodeRefToSign, signingDTO, alfTempDir, alias, ks, key, chain); if (exception != null) { // Error on the file process errors.add(exception); } } if (errors != null && errors.size() > 0) { final StringBuffer allErrors = new StringBuffer(); final Iterator<AlfrescoRuntimeException> itErrors = errors.iterator(); if (errors.size() > 1) { allErrors.append("\n"); } while (itErrors.hasNext()) { final AlfrescoRuntimeException alfrescoRuntimeException = itErrors.next(); allErrors.append(alfrescoRuntimeException.getMessage()); if (itErrors.hasNext()) { allErrors.append("\n"); } } throw new RuntimeException(allErrors.toString()); } } else { log.error("Unable to get key content, key type or key password."); throw new AlfrescoRuntimeException( "Unable to get key content, key type or key password."); } } } else { log.error("Unable to get temporary directory."); throw new AlfrescoRuntimeException("Unable to get temporary directory."); } } catch (KeyStoreException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (CertificateException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (IOException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } } else { log.error("No object with signing informations."); throw new AlfrescoRuntimeException("No object with signing informations."); } }
public List<VerifyResultDTO> verifySign(final VerifyingDTO verifyingDTO) { final List<VerifyResultDTO> result = new ArrayList<VerifyResultDTO>(); try { if (verifyingDTO != null) { final String keyType = (String) nodeService.getProperty(verifyingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE); final KeyStore ks = KeyStore.getInstance(keyType); final ContentReader keyContentReader = getReader(verifyingDTO.getKeyFile()); if (keyContentReader != null && ks != null && verifyingDTO.getKeyPassword() != null) { // Get crypted secret key and decrypt it final Serializable encryptedPropertyValue = nodeService.getProperty(verifyingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET); final Serializable decryptedPropertyValue = metadataEncryptor.decrypt(SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue); // Decrypt key content final InputStream decryptedKeyContent = CryptUtils.decrypt( decryptedPropertyValue.toString(), keyContentReader.getContentInputStream()); ks.load( new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)), verifyingDTO.getKeyPassword().toCharArray()); final ContentReader fileToVerifyContentReader = getReader(verifyingDTO.getFileToVerify()); if (fileToVerifyContentReader != null) { final PdfReader reader = new PdfReader(fileToVerifyContentReader.getContentInputStream()); if (reader != null) { final AcroFields af = reader.getAcroFields(); if (af != null) { final ArrayList<String> names = af.getSignatureNames(); if (names != null) { for (int k = 0; k < names.size(); ++k) { final VerifyResultDTO verifyResultDTO = new VerifyResultDTO(); final String name = (String) names.get(k); verifyResultDTO.setName(name); verifyResultDTO.setSignatureCoversWholeDocument( af.signatureCoversWholeDocument(name)); verifyResultDTO.setRevision(af.getRevision(name)); verifyResultDTO.setTotalRevision(af.getTotalRevisions()); final PdfPKCS7 pk = af.verifySignature(name); if (pk != null) { final Calendar cal = pk.getSignDate(); final Certificate[] pkc = pk.getCertificates(); Object fails[] = PdfPKCS7.verifyCertificates(pkc, ks, null, cal); if (fails == null) { verifyResultDTO.setIsSignValid(true); } else { verifyResultDTO.setIsSignValid(false); verifyResultDTO.setFailReason(fails[1]); } verifyResultDTO.setSignSubject( PdfPKCS7.getSubjectFields(pk.getSigningCertificate()).toString()); verifyResultDTO.setIsDocumentModified(!pk.verify()); verifyResultDTO.setSignDate(pk.getSignDate()); verifyResultDTO.setSignLocation(pk.getLocation()); verifyResultDTO.setSignInformationVersion(pk.getSigningInfoVersion()); verifyResultDTO.setSignReason(pk.getReason()); verifyResultDTO.setSignVersion(pk.getVersion()); verifyResultDTO.setSignName(pk.getSignName()); result.add(verifyResultDTO); } else { log.error("Unable to verify signature."); throw new AlfrescoRuntimeException("Unable to verify signature."); } } } else { log.error("Unable to get signature names."); throw new AlfrescoRuntimeException("Unable to get signature names."); } } else { log.error("Unable to get PDF fields."); throw new AlfrescoRuntimeException("Unable to get PDF fields."); } } } else { log.error("Unable to get document to verify content."); throw new AlfrescoRuntimeException("Unable to get document to verify content."); } } else { log.error("Unable to get key content, key type or key password."); throw new AlfrescoRuntimeException( "Unable to get key content, key type or key password."); } } else { log.error("No object with verification informations."); throw new AlfrescoRuntimeException("No object with verification informations."); } } catch (KeyStoreException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (CertificateException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (IOException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (GeneralSecurityException e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (Throwable e) { log.error(e); throw new AlfrescoRuntimeException(e.getMessage(), e); } return result; }
@Override public void contextInitialized(ServletContextEvent arg0) { final String S_ProcName = "contextInitialized"; Properties props = System.getProperties(); if (null == CFBamSchemaPool.getSchemaPool()) { try { Context ctx = new InitialContext(); String poolClassName = (String) ctx.lookup("java:comp/env/CFBam24PoolClass"); if ((poolClassName == null) || (poolClassName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24PoolClass"); } Class poolClass = Class.forName(poolClassName); if (poolClass == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "CFBam24PoolClass \"" + poolClassName + "\" not found."); } Object obj = poolClass.newInstance(); if (obj instanceof CFBamSchemaPool) { CFBamSchemaPool newPool = (CFBamSchemaPool) obj; newPool.setConfigurationFile(null); newPool.setJndiName("java:comp/env/CFBam24Connection"); CFBamSchemaPool.setSchemaPool(newPool); } else { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Problems constructing an instance of " + poolClassName); } String smtpHost = (String) ctx.lookup("java:comp/env/CFBam24SmtpHost"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpHost"); } props.setProperty("mail.smtp.host", smtpHost); String smtpStartTLS = (String) ctx.lookup("java:comp/env/CFBam24SmtpStartTLS"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpStartTLS"); } props.setProperty("mail.smtp.starttls.enable", smtpStartTLS); String smtpSocketFactoryClass = (String) ctx.lookup("java:comp/env/CFBam24SmtpSocketFactoryClass"); if ((smtpSocketFactoryClass == null) || (smtpSocketFactoryClass.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpSocketFactoryClass"); } props.setProperty("mail.smtp.socketFactory.class", smtpSocketFactoryClass); props.setProperty("mail.smtp.socketFactory.fallback", "false"); String smtpPort = (String) ctx.lookup("java:comp/env/CFBam24SmtpPort"); if ((smtpPort == null) || (smtpPort.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPort"); } props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.port", smtpPort); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFBam24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpEmailFrom"); } smtpUsername = (String) ctx.lookup("java:comp/env/CFBam24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFBam24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPassword"); } String serverKeyStore; try { serverKeyStore = (String) ctx.lookup("java:comp/env/CFBam24ServerKeyStore"); } catch (NamingException e) { serverKeyStore = null; } String keyStorePassword; try { keyStorePassword = (String) ctx.lookup("java:comp/env/CFBam24KeyStorePassword"); } catch (NamingException e) { keyStorePassword = null; } String keyName; try { keyName = (String) ctx.lookup("java:comp/env/CFBam24KeyName"); } catch (NamingException e) { keyName = null; } String keyPassword; try { keyPassword = (String) ctx.lookup("java:comp/env/CFBam24KeyPassword"); } catch (NamingException e) { keyPassword = null; } if (((serverKeyStore != null) && (serverKeyStore.length() > 0)) && (keyStorePassword != null) && ((keyName != null) && (keyName.length() > 0)) && (keyPassword != null)) { KeyStore keyStore = null; File keystoreFile = new File(serverKeyStore); if (!keystoreFile.exists()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" does not exist."); } else if (!keystoreFile.isFile()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" is not a file."); } else if (!keystoreFile.canRead()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Permission denied attempting to read CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } try { keyStore = KeyStore.getInstance("jceks"); char[] caPassword = keyStorePassword.toCharArray(); FileInputStream input = new FileInputStream(serverKeyStore); keyStore.load(input, caPassword); input.close(); Certificate publicKeyCertificate = keyStore.getCertificate(keyName); if (publicKeyCertificate == null) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Could not read CFBam24KeyName \"" + keyName + "\" from CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } publicKey = publicKeyCertificate.getPublicKey(); char[] caKeyPassword = keyPassword.toCharArray(); Key key = keyStore.getKey(keyName, caKeyPassword); if (key instanceof PrivateKey) { privateKey = (PrivateKey) key; } else { throw CFLib.getDefaultExceptionFactory() .newUnsupportedClassException(getClass(), S_ProcName, "key", key, "PrivateKey"); } getServerInfo(); } catch (CertificateException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to CertificateException -- " + x.getMessage(), x); } catch (IOException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to IOException -- " + x.getMessage(), x); } catch (KeyStoreException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to KeyStoreException -- " + x.getMessage(), x); } catch (NoSuchAlgorithmException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(), x); } catch (UnrecoverableKeyException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not access key due to UnrecoverableKeyException -- " + x.getMessage(), x); } catch (RuntimeException x) { publicKey = null; privateKey = null; throw x; } } else if ((serverKeyStore != null) || (keyStorePassword != null) || (keyName != null) || (keyPassword != null)) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "All or none of CFBam24ServerKeyStore, " + "CFBam24KeyStorePassword, " + "CFBam24KeyName, and " + "CFBam24KeyPassword must be configured"); } else { getServerInfo(); try { serverInfo.initServerKeys(); } catch (Exception x) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught " + x.getClass().getName() + " during initServerKeys() -- " + x.getMessage(), x); } } } catch (ClassNotFoundException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught ClassNotFoundException -- " + e.getMessage(), e); } catch (IllegalAccessException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught IllegalAccessException trying to construct newInstance() -- " + e.getMessage(), e); } catch (InstantiationException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught InstantiationException trying to construct newInstance() -- " + e.getMessage(), e); } catch (NamingException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e); } } }
/** * Test for <code>KeyStoreException()</code> constructor Assertion: constructs KeyStoreException * with no detail message */ public void testKeyStoreException01() { KeyStoreException tE = new KeyStoreException(); assertNull("getMessage() must return null.", tE.getMessage()); assertNull("getCause() must return null", tE.getCause()); }
/** * parse arguments * * @param args arguments */ private void parseArguments(String[] args) { // parse arguments int z = 0; while (z < args.length) { if (args[z].startsWith("-h") || args[z].startsWith("--help")) { printUsage(); System.exit(0); } else if (args[z].startsWith("-p=") || args[z].startsWith("--port=")) { String value = args[z].substring(args[z].indexOf('=') + 1); try { serverPort = Integer.parseInt(value); } catch (NumberFormatException exception) { throw new Error( "Invalid value '" + value + "' for option --port (error: " + exception.getMessage() + ")!"); } z += 1; } else if (args[z].equals("-p") || args[z].equals("--port")) { if ((z + 1) >= args.length) { throw new Error("Expected value for option --port!"); } try { serverPort = Integer.parseInt(args[z + 1]); } catch (NumberFormatException exception) { throw new Error( "Invalid value '" + args[z + 1] + "' for option --port (error: " + exception.getMessage() + ")!"); } z += 2; } else if (args[z].startsWith("--tls-port=")) { String value = args[z].substring(args[z].indexOf('=') + 1); try { serverTLSPort = Integer.parseInt(value); } catch (NumberFormatException exception) { throw new Error( "Invalid value '" + value + "' for option --tls-port (error: " + exception.getMessage() + ")!"); } z += 1; } else if (args[z].equals("--tls-port")) { if ((z + 1) >= args.length) { throw new Error("Expected value for option --tls-port!"); } try { serverTLSPort = Integer.parseInt(args[z + 1]); } catch (NumberFormatException exception) { throw new Error( "Invalid value '" + args[z + 1] + "' for option --tls-port (error: " + exception.getMessage() + ")!"); } z += 2; } else if (args[z].startsWith("--login-dialog=")) { String value = args[z].substring(args[z].indexOf('=') + 1).toLowerCase(); if (value.equals("yes") || value.equals("on") || value.equals("1")) { loginDialogFlag = true; } else if (value.equals("no") || value.equals("off") || value.equals("0")) { loginDialogFlag = false; } else { throw new Error( "Invalid value '" + value + "' for option --login-dialog (error: expected yes,on,1 or no,off,0)!"); } z += 1; } else if (args[z].equals("--login-dialog")) { loginDialogFlag = true; z += 1; } else if (args[z].startsWith("--key-file=")) { serverKeyFileName = args[z].substring(args[z].indexOf('=') + 1); z += 1; } else if (args[z].equals("--key-file")) { if ((z + 1) >= args.length) { throw new Error("Expected value for option --key-file!"); } serverKeyFileName = args[z + 1]; z += 2; } else if (args[z].equals("--debug")) { debug = true; z += 1; } else if (args[z].equals("--bar-server-debug")) { BARServer.debug = true; z += 1; } else if (args[z].equals("--")) { z += 1; break; } else if (args[z].startsWith("--")) { throw new Error("Unknown option '" + args[z] + "'!"); } else { serverName = args[z]; z += 1; } } // check arguments if (serverKeyFileName != null) { // check if JKS file readable try { KeyStore keyStore = java.security.KeyStore.getInstance("JKS"); keyStore.load(new java.io.FileInputStream(serverKeyFileName), null); } catch (java.security.NoSuchAlgorithmException exception) { throw new Error(exception.getMessage()); } catch (java.security.cert.CertificateException exception) { throw new Error(exception.getMessage()); } catch (java.security.KeyStoreException exception) { throw new Error(exception.getMessage()); } catch (IOException exception) { throw new Error("not a JKS file '" + serverKeyFileName + "'"); } } }
/** * Test for <code>KeyStoreException(Throwable)</code> constructor Assertion: constructs * KeyStoreException when <code>cause</code> is null */ public void testKeyStoreException04() { Throwable cause = null; KeyStoreException tE = new KeyStoreException(cause); assertNull("getMessage() must return null.", tE.getMessage()); assertNull("getCause() must return null", tE.getCause()); }
public PushManager get(Product product) { if (StringUtils.isBlank(product.getDevCertPath()) || StringUtils.isBlank(product.getDevCertPass()) || StringUtils.isBlank(product.getCertPath()) || StringUtils.isBlank(product.getCertPass())) { logger.error("Product iOS Push Service Miss Cert Path and Password. {}", product); return null; } PushManager service = mapping.get(product.getId()); if (service == null) { ApnsEnvironment apnsEnvironment = null; SSLContext sslContext = null; try { if (sandBox) { apnsEnvironment = ApnsEnvironment.getSandboxEnvironment(); sslContext = SSLContextUtil.createDefaultSSLContext( product.getDevCertPath(), product.getDevCertPass()); } else { apnsEnvironment = ApnsEnvironment.getProductionEnvironment(); sslContext = SSLContextUtil.createDefaultSSLContext(product.getCertPath(), product.getCertPass()); } } catch (KeyStoreException e) { logger.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e); } catch (CertificateException e) { logger.error(e.getMessage(), e); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage(), e); } catch (KeyManagementException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } PushManagerConfiguration configuration = new PushManagerConfiguration(); configuration.setConcurrentConnectionCount(1); final PushManager<SimpleApnsPushNotification> pushManager = new PushManager<SimpleApnsPushNotification>( apnsEnvironment, sslContext, null, // Optional: custom event loop group null, // Optional: custom ExecutorService for calling listeners null, // Optional: custom BlockingQueue implementation configuration, "ApnsPushManager-" + product.getId()); pushManager.registerRejectedNotificationListener(new PushRejectedNotificationListener()); pushManager.registerFailedConnectionListener(new PushFailedConnectionListener()); pushManager.start(); // ApnsServiceBuilder builder = APNS.newService(); // if (sandBox){ // builder.withCert(product.getDevCertPath(), product.getDevCertPass()); // builder.withSandboxDestination(); // }else{ // builder.withCert(product.getCertPath(), product.getCertPass()); // builder.withProductionDestination(); // } // service = // builder.asPool(10).withCacheLength(Integer.MAX_VALUE).withDelegate(delegateAdapter).asQueued().build(); mapping.put(product.getId(), pushManager); service = pushManager; } return service; }