/* * CreateFileDialog.java * * * ==================================================== Professional Data Security (PDS) http://crypto.brettlee.com ==================================================== Copyright (c) 2009-2011, Brett Lee All rights reserved. Portions Copyright (C) 1995-2008, Sun Microsystems, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ORGANIZATION nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================= */ package com.brettlee.crypto; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.StyledEditorKit; import javax.swing.undo.UndoManager; /** * CreateFileDialog - File-> New-> File "Dialog" * */ class CreateFileDialog { /** * */ Gui mGui; JDialog createFileDialog; JButton jButtonCreate = new JButton("Create"); final JTextField cryptoFileNameField = new JTextField("", 25); final JTextField keyStoreNameField = new JTextField("", 20); final JTextField keyAliasNameField = new JTextField( 20 ); final JTextField encryptToRawDeviceField = new JTextField("", 35); final JTextField encryptToSelectedDirField = new JTextField("", 35); JCheckBox encryptToDefaultDir = new JCheckBox("Create in the encrypted files default directory", true); JCheckBox encryptToSameDir = new JCheckBox("Create in the same directory as the source", true); JCheckBox encryptToRawDevice = new JCheckBox("Create on a tape drive or other raw device", true); JCheckBox encryptToSelectedDir = new JCheckBox("Select a directory", true); JCheckBox encryptBinary = new JCheckBox("Binary", true); JCheckBox encryptBase64 = new JCheckBox("Base64", true); JCheckBox useDefaultKeyCheckBox = new JCheckBox("", true); String[] zipLevel = {"0","1","2","3","4","5","6","7","8","9"}; JComboBox compressionLevel = new JComboBox(zipLevel); String newline = System.getProperty("line.separator"); public CreateFileDialog ( Gui theGui, final CryptoFile cryptoFile ) { ///////////////////////////////////////////////////////////// // Build the Dialog mGui = theGui; createFileDialog = new JDialog(mGui.mainFrame, "Create a New File", true); JPanel contentPane = new JPanel(); createFileDialog.getContentPane().add(contentPane); GroupLayout layout = new GroupLayout(contentPane); contentPane.setLayout(layout); layout.setAutoCreateGaps(true); layout.setAutoCreateContainerGaps(true); FlowLayout flowLayoutLeft = new FlowLayout(); flowLayoutLeft.setAlignment(FlowLayout.LEFT); FlowLayout flowLayoutRight = new FlowLayout(); flowLayoutRight.setAlignment(FlowLayout.RIGHT); JPanel p1 = new JPanel(); JPanel p2 = new JPanel( flowLayoutLeft ); JPanel p3 = new JPanel( new GridLayout(3,1,0,0) ); JPanel p4 = new JPanel( new GridLayout(1,2,0,0) ); JPanel p5 = new JPanel( new GridLayout(3,3,0,0) ); JPanel p6 = new JPanel(); layout.setHorizontalGroup( layout.createSequentialGroup() .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING) .addComponent(p1) .addComponent(p2) .addComponent(p3) .addComponent(p4) .addComponent(p5) .addComponent(p6) )); layout.setVerticalGroup( layout.createSequentialGroup() .addComponent(p1) .addComponent(p2) .addComponent(p3) .addComponent(p4) .addComponent(p5) .addComponent(p6) ); ///////////////////////////////////////////////////////////// // p1 - Title JLabel jlabel = null; if (cryptoFile instanceof CryptoFileNative) { jlabel = new JLabel("Create a New PDS File"); createFileDialog.setTitle("Professional Data Security (PDS) - Create New File"); } else if (cryptoFile instanceof CryptoFileExternal) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 1) { jlabel = new JLabel("Encrypt an Existing File"); createFileDialog.setTitle("Professional Data Security (PDS) - Encrypt Existing File"); } else { jlabel = new JLabel("Encrypt an Existing Directory"); createFileDialog.setTitle("Professional Data Security (PDS) - Encrypt Existing Directory"); } } p1.add(jlabel); // p2 - Assign the New File a Name p2.setBorder(new TitledBorder("Filename")); if (cryptoFile instanceof CryptoFileExternal) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 2) { p2.setBorder(new TitledBorder("Directory")); } } JPanel p2SubPanel = new JPanel(flowLayoutLeft); p2.add(p2SubPanel); JLabel p2Label = null; if ( cryptoFile instanceof CryptoFileNative ) { p2Label = new JLabel("Name of new file: "); } else if ( cryptoFile instanceof CryptoFileExternal ) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 1) { p2Label = new JLabel("File to encrypt: "); } else { p2Label = new JLabel("Directory to encrypt: "); } } p2SubPanel.add(p2Label); p2SubPanel.add(cryptoFileNameField); JButton iconOpenp2 = new JButton(Gui.createImageIcon("images/folder.gif", 28)); iconOpenp2.setFocusable(false); Gui.enterPressesWhenFocused(iconOpenp2); if ( cryptoFile instanceof CryptoFileNative ) { iconOpenp2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { newCryptoFileActionPerformed(evt, 0, cryptoFile); } }); } else if ( cryptoFile instanceof CryptoFileExternal ) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 1) { iconOpenp2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { newCryptoFileActionPerformed(evt, 1, cryptoFile); } }); } else { iconOpenp2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { newCryptoFileActionPerformed(evt, 2, cryptoFile); } }); } } iconOpenp2.setToolTipText("Create New File"); p2SubPanel.add(iconOpenp2); if ( cryptoFile instanceof CryptoFileExternal ) { final CryptoFileExternal cryptoFileExternal = (CryptoFileExternal) cryptoFile; // p3 - Define location for new encrypted file to be written p3.setBorder(new TitledBorder("Destination for the Encrypted Data")); final JButton p3iconOpen1 = new JButton(Gui.createImageIcon("images/folder.gif", 28)); p3iconOpen1.setFocusable(false); final JButton p3iconOpen2 = new JButton(Gui.createImageIcon("images/folder.gif", 28)); p3iconOpen2.setFocusable(false); JPanel p3SubPanel1 = new JPanel( new GridLayout(2,1,0,0) ); encryptToDefaultDir.setSelected(true); encryptToDefaultDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptToDefaultDir.isSelected() ) { encryptToSameDir.setSelected(false); encryptToSelectedDir.setSelected(false); encryptToSelectedDirField.setEditable(false); p3iconOpen1.setEnabled(false); encryptToRawDevice.setSelected(false); encryptToRawDeviceField.setEditable(false); p3iconOpen2.setEnabled(false); } } }); p3SubPanel1.add(encryptToDefaultDir); encryptToSameDir.setSelected(false); encryptToSameDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptToSameDir.isSelected() ) { encryptToDefaultDir.setSelected(false); encryptToSelectedDir.setSelected(false); encryptToSelectedDirField.setEditable(false); p3iconOpen1.setEnabled(false); encryptToRawDevice.setSelected(false); encryptToRawDeviceField.setEditable(false); p3iconOpen2.setEnabled(false); } } }); p3SubPanel1.add(encryptToSameDir); p3.add(p3SubPanel1); if (cryptoFile instanceof CryptoFileExternal) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 2) { encryptToSameDir.setEnabled(false); } } JPanel p3SubPanel2 = new JPanel( new GridLayout(2,1,0,0) ); JPanel p3SubPanel2a = new JPanel(flowLayoutRight); encryptToSelectedDir.setSelected(false); encryptToSelectedDir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptToSelectedDir.isSelected() ) { encryptToDefaultDir.setSelected(false); encryptToSameDir.setSelected(false); encryptToSelectedDirField.setEditable(true); p3iconOpen1.setEnabled(true); encryptToRawDevice.setSelected(false); encryptToRawDeviceField.setEditable(false); p3iconOpen2.setEnabled(false); } else { encryptToSelectedDirField.setEditable(false); p3iconOpen1.setEnabled(false); } } }); p3SubPanel2.add(encryptToSelectedDir); encryptToSelectedDirField.setEditable(false); p3SubPanel2a.add(encryptToSelectedDirField); Gui.enterPressesWhenFocused(p3iconOpen1); p3iconOpen1.setEnabled(false); p3iconOpen1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JFrame frame = new JFrame(); JFileChooser fileChooser = new JFileChooser ( mGui.stateObject.getDefaultEncryptedFilePath() ); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle( "Output File" ); fileChooser.setApproveButtonText("Select"); int returnVal = fileChooser.showOpenDialog(frame); if ( returnVal == 0 ) { // Get Absolute Path: String dirName = (fileChooser.getSelectedFile().getPath() + mGui.fileSeparator); // System.out.println("Dir Selected: " + dirName); cryptoFileExternal.setEncFilePath(dirName); // System.out.println("Encr File Path in CryptoFile: " + cryptoFileExternal.getEncFilePath()); encryptToSelectedDirField.setText(cryptoFileExternal.getEncFilePath()); encryptToSelectedDirField.setCaretPosition(0); } } }); p3SubPanel2a.add(p3iconOpen1); p3SubPanel2.add(p3SubPanel2a); p3.add(p3SubPanel2); JPanel p3SubPanel3 = new JPanel( new GridLayout(2,1,0,0) ); JPanel p3SubPanel3a = new JPanel(flowLayoutRight); encryptToRawDevice.setSelected(false); encryptToRawDevice.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptToRawDevice.isSelected() ) { encryptToDefaultDir.setSelected(false); encryptToSameDir.setSelected(false); encryptToSelectedDir.setSelected(false); encryptToSelectedDirField.setEditable(false); p3iconOpen1.setEnabled(false); encryptToRawDeviceField.setEditable(true); p3iconOpen2.setEnabled(true); } else { encryptToRawDeviceField.setEditable(false); p3iconOpen2.setEnabled(false); } } }); p3SubPanel3.add(encryptToRawDevice); encryptToRawDeviceField.setEditable(false); p3SubPanel3a.add(encryptToRawDeviceField); Gui.enterPressesWhenFocused(p3iconOpen2); p3iconOpen2.setEnabled(false); p3iconOpen2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JFrame frame = new JFrame(); JFileChooser fileChooser = new JFileChooser ( mGui.stateObject.getDefaultEncryptedFilePath() ); fileChooser.setDialogTitle( "Output Device" ); fileChooser.setApproveButtonText("Select"); int returnVal = fileChooser.showOpenDialog(frame); if ( returnVal == 0 ) { // Get Device Path String deviceName = ( fileChooser.getSelectedFile().getPath() ); // System.out.println("Device Selected: " + deviceName); cryptoFileExternal.setEncFilePath(deviceName); // System.out.println("Encr File Path in CryptoFile: " + cryptoFileExternal.getEncFilePath()); encryptToRawDeviceField.setText(cryptoFileExternal.getEncFilePath()); encryptToRawDeviceField.setCaretPosition(0); } } }); p3SubPanel3a.add(p3iconOpen2); p3SubPanel3.add(p3SubPanel3a); p3.add(p3SubPanel3); // p4 - Define the output format p4.setBorder(new TitledBorder("Output Format")); if (cryptoFile instanceof CryptoFileExternal) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 2) { p4.setBorder(new TitledBorder("Compression Level")); } } final JLabel compressionLevelLabel = new JLabel("Select the Level of Compression (0=none) "); JPanel p4SubPanel1 = new JPanel( new GridLayout(2,1,0,0) ); encryptBinary.setSelected(true); encryptBinary.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptBinary.isSelected() ) { encryptBase64.setSelected(false); compressionLevelLabel.setEnabled(false); compressionLevel.setEnabled(false); } } }); encryptBase64.setSelected(false); encryptBase64.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( encryptBase64.isSelected() ) { encryptBinary.setSelected(false); compressionLevelLabel.setEnabled(false); compressionLevel.setEnabled(false); } } }); JPanel p4SubPanel2 = new JPanel(flowLayoutLeft); p4SubPanel2.add(compressionLevelLabel); compressionLevelLabel.setEnabled(true); compressionLevel.setSelectedIndex(0); compressionLevel.setEnabled(true); p4SubPanel2.add(compressionLevel); if (cryptoFile instanceof CryptoFileExternal) { if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 2) { p4.add(p4SubPanel2); } else { p4SubPanel1.add(encryptBinary); p4SubPanel1.add(encryptBase64); p4.add(p4SubPanel1); } } else { p4SubPanel1.add(encryptBinary); p4SubPanel1.add(encryptBase64); p4.add(p4SubPanel1); } } // p5 - Associate the New File with a KeyStore Key p5.setBorder(new TitledBorder("Associate with this Encryption Key")); JPanel p5SubPanel1 = new JPanel(flowLayoutLeft); p5.add(p5SubPanel1); JLabel p5Label1 = new JLabel("Use My Default Key"); p5SubPanel1.add(p5Label1); if ( mGui.stateObject.getHaveDefaults() ) { cryptoFileNameField.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { if (! ( cryptoFileNameField.getText().equals(""))) { createFileDialog.setVisible(false); createFile(evt, cryptoFile); } } } ); } else { useDefaultKeyCheckBox.setEnabled(false); useDefaultKeyCheckBox.setSelected(false); jButtonCreate.setEnabled(false); } p5SubPanel1.add(useDefaultKeyCheckBox); JPanel p5SubPanel2 = new JPanel(flowLayoutLeft); p5.add(p5SubPanel2); JLabel p5Label2 = new JLabel("KeyStore that contains the Key: "); p5SubPanel2.add(p5Label2); p5SubPanel2.add(keyStoreNameField); keyStoreNameField.setEditable(false); final JButton p5iconOpen2 = new JButton(Gui.createImageIcon("images/folder.gif", 28)); p5iconOpen2.setFocusable(false); Gui.enterPressesWhenFocused(p5iconOpen2); if ( mGui.stateObject.getHaveDefaults() ) { p5iconOpen2.setEnabled(false); } useDefaultKeyCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if ( useDefaultKeyCheckBox.isSelected() ) { p5iconOpen2.setEnabled(false); jButtonCreate.setEnabled(true); } else if ( ! useDefaultKeyCheckBox.isSelected() ) { p5iconOpen2.setEnabled(true); if ( cryptoFile.getKeyAlias() != null ) { jButtonCreate.setEnabled(true); } else { jButtonCreate.setEnabled(false); } } } }); p5iconOpen2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JFrame frame = new JFrame(); // ///////////////////////////////////////////// // Have Filename // // Need KeyStore Filename // Need KeyStore Passphrase // Need Key Alias // Need Key Alias Passphrase // // Get KeyStore Filename (filename set in associateKeyStoreActionPerformed) // if ( associateKeyStoreActionPerformed(evt, cryptoFile) != 0 ) { return; } // // Get KeyStore passphrase (passphrase set in authDialog) // (2 = KeyStore, 3 = Key, 6 = KeyStore+Key) // new AuthDialog(frame, true, 2, cryptoFile); // Was the Auth Dialog action canceled if ( StateObject.getFileChooserCancel() ) { StateObject.setFileChooserCancel(false); return; } // // Get Key Alias (alias set in KeySelectorDialog) // new KeySelectorDialog (CreateFileDialog.this, frame, true, cryptoFile); // Was the Auth Dialog action canceled if ( StateObject.getFileChooserCancel() ) { StateObject.setFileChooserCancel(false); return; } // // Get Key Alias Passphrase (passphrase set in authDialog) // (2 = KeyStore, 3 = Key, 6 = KeyStore+Key) // new AuthDialog(frame, true, 3, cryptoFile); // Was the Auth Dialog action canceled if ( StateObject.getFileChooserCancel() ) { StateObject.setFileChooserCancel(false); return; } else { jButtonCreate.setEnabled(true); } } }); p5iconOpen2.setToolTipText("Locate Encryption Key"); p5SubPanel2.add(p5iconOpen2); JPanel p5SubPanel3 = new JPanel(flowLayoutLeft); p5.add(p5SubPanel3); JLabel p5Label3 = new JLabel("Key Alias in the KeyStore: "); p5SubPanel3.add(p5Label3); p5SubPanel3.add(keyAliasNameField, BorderLayout.WEST); keyAliasNameField.setEditable(false); keyAliasNameField.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { createFile(evt, cryptoFile); } } ); // p6 - Create & Cancel Buttons jButtonCreate.setMnemonic(KeyEvent.VK_R); Gui.enterPressesWhenFocused(jButtonCreate); jButtonCreate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // System.out.println("Creating..."); createFile(evt, cryptoFile); } }); p6.add(jButtonCreate); JButton jButtonCancel = new JButton("Cancel"); jButtonCancel.setMnemonic(KeyEvent.VK_C); Gui.enterPressesWhenFocused(jButtonCancel); jButtonCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // System.out.println("Canceling..."); createFileDialog.setVisible(false); createFileDialog.dispose(); } }); p6.add(jButtonCancel); ///////////////////////////////////////////////////////////// // Finish up createFileDialog.pack(); createFileDialog.setLocationRelativeTo(null); createFileDialog.setVisible(true); } void createFile(ActionEvent evt, CryptoFile cryptoFile) { boolean ret = false; // See if filename was provided manually (e.g. not using the JFileChooser) // If provided manually then cryptoFile.getFileName() will be *NULL* // if ( cryptoFile.getFileName() == null ) { // First, just see if there was *nothing* provided // if ( cryptoFileNameField.getText().equals("")) { // notify if file not specified JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Please provide a filename." + newline, "File name not provided", JOptionPane.WARNING_MESSAGE); return; } } if ( cryptoFile instanceof CryptoFileExternal ) { // The file should exist if ( ! new java.io.File( cryptoFileNameField.getText() ).exists() ) { // notify if specified but does not exist if (((CryptoFileExternal) cryptoFile).getEncryptedOutputFormat() == 1) { JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "This file to be encrypted does not exist." + newline, "File does not exist", JOptionPane.WARNING_MESSAGE); } else { JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "The directory to be encrypted does not exist." + newline, "Directory does not exist", JOptionPane.WARNING_MESSAGE); } return; } } // Check to see if file name was fully pathed // Yep, this section is redundant for External files - currently at least. // Pattern pattern = Pattern.compile("(.*)[/\\\\](.*)"); Matcher matcher = pattern.matcher( cryptoFileNameField.getText() ); if ( matcher.matches() ) { // File name has path info. // Encrypting a dir is special case, only the path exists. cryptoFile.setFullyPathedFileName( cryptoFileNameField.getText() ); // System.out.println("Fully pathed filename: " + cryptoFile.getFullyPathedFileName() ); // Manually provided file is fully pathed // System.out.println("Contains forward/back slashes: " + cryptoFileNameField.getText() ); cryptoFile.setFileName( matcher.group(2) ); // System.out.println("File Name Only : " + cryptoFile.getFileName() ); // Does the directory actually exist? pattern = Pattern.compile("(.*)" + cryptoFile.getFileName() ); matcher = pattern.matcher( cryptoFileNameField.getText() ); if( matcher.matches() ) { // Does this directory actually exist ? // System.out.println("Part 1: " + matcher.group(1) ); try { if ( ! new java.io.File( matcher.group(1) ).exists() ) { JFrame frame = new JFrame(); int n = JOptionPane.showOptionDialog( frame, "The directory provided does not exist." + newline + newline + matcher.group(1) + newline + newline + "Would you like to create it?" + newline + newline, "Directory does not exist", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {"Yes", "No"}, "No"); if ( n != 0 ) { // System.out.println("Canceling..."); return; } else { // System.out.println("Creating the directory..."); boolean success = (new File(matcher.group(1))).mkdirs(); if (success) { // System.out.println("Directory: " + matcher.group(1) + " created"); } else { JOptionPane.showMessageDialog( frame, "Unable to Create the Directory:" + newline + matcher.group(1) + newline + newline + "Please check the permissions or the path" + newline + "and try again.", "Unable to Create the Directory", JOptionPane.ERROR_MESSAGE); createFileDialog.setVisible(false); createFileDialog.dispose(); return; } } } } catch (Exception e) { System.out.println("Unable to get fully pathed filename: " + e); return; } } } else { // *NOT* fully pathed - prepend default path to Filename cryptoFile.setFullyPathedFileName( mGui.stateObject.getDefaultEncryptedFilePath() + cryptoFileNameField.getText()); // System.out.println("Fully pathed filename: " + cryptoFile.getFullyPathedFileName() ); // and Set the Filename cryptoFile.setFileName( cryptoFileNameField.getText() ); // System.out.println("Filename: " + cryptoFile.getFileName() ); } if ( cryptoFile instanceof CryptoFileExternal ) { CryptoFileExternal cryptoFileExternal = (CryptoFileExternal) cryptoFile; // Confirm that an destination was selected // if ( ( ! encryptToDefaultDir.isSelected() ) && ( ! encryptToSameDir.isSelected() ) && ( ! encryptToSelectedDir.isSelected() ) && ( ! encryptToRawDevice.isSelected() ) ) { // notify if output dir is not specified JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Please select a destination directory." + newline, "Destination directory not selected", JOptionPane.WARNING_MESSAGE); return; } // Confirm that (if needed) an output directory was specified // if ( ( encryptToSelectedDir.isSelected() ) && ( encryptToSelectedDirField.getText().equals("")) ) { // notify if file format is not specified JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Please select an output directory." + newline, "Output directory not selected", JOptionPane.WARNING_MESSAGE); return; } // Confirm that if a directory was provided , it exists // if ( encryptToSelectedDir.isSelected() ) { try { if ( ! new java.io.File( encryptToSelectedDirField.getText() ).exists() ) { JFrame frame = new JFrame(); int n = JOptionPane.showOptionDialog( frame, "The directory provided does not exist." + newline + newline + encryptToSelectedDirField.getText() + newline + newline + "Would you like to create it?" + newline + newline, "Directory does not exist", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {"Yes", "No"}, "No"); if ( n != 0 ) { // System.out.println("Canceling..."); return; } else { // System.out.println("Creating the directory..."); boolean success = (new File(encryptToSelectedDirField.getText())).mkdirs(); if (success) { // System.out.println("Directory: " + encryptToSelectedDirField.getText() + " created"); } else { JOptionPane.showMessageDialog( frame, "Unable to Create the Directory:" + newline + encryptToSelectedDirField.getText() + newline + newline + "Please check the permissions or the path" + newline + "and try again.", "Unable to Create the Directory", JOptionPane.ERROR_MESSAGE); createFileDialog.setVisible(false); createFileDialog.dispose(); return; } } } } catch (Exception e) { System.out.println("Unable to get fully pathed filename: " + e); return; } cryptoFileExternal.setEncFilePath( StateObject.pathToDisplay( encryptToSelectedDirField.getText(), true )); } if ( ( encryptToRawDevice.isSelected() ) && ( cryptoFileExternal.getEncFilePath() == null) ) { if ( encryptToRawDeviceField.getText().equals("") ) { // notify if output device is not specified JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Please select an output device." + newline, "Output device not selected", JOptionPane.WARNING_MESSAGE); return; } } // Confirm that a device file, if needed, is present // if ( encryptToRawDevice.isSelected()) { if ( ! new java.io.File(encryptToRawDeviceField.getText()).exists() ) { // notify if the specified output device does not exist JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "The output device does not exist." + newline, "Output device does not exist", JOptionPane.WARNING_MESSAGE); return; } else { cryptoFileExternal.setDeviceType( 1 ); } } // Confirm that an output format was selected // if (cryptoFileExternal.getEncryptedOutputFormat() == 1) { if ( ( ! encryptBase64.isSelected() ) && ( ! encryptBinary.isSelected() ) ) { // notify if file format is not specified JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Please select an output format." + newline, "Output format not selected", JOptionPane.WARNING_MESSAGE); return; } } else if (cryptoFileExternal.getEncryptedOutputFormat() == 2) { // Get compression level // // "compressionLevel.getSelectedItem()" returns type Object: need an int: cryptoFileExternal.setCompressionLevel( Integer.parseInt( (compressionLevel.getSelectedItem()).toString() ) ); // System.out.println("Compression level: " + cryptoFileExternal.getCompressionLevel() ); } else { // Should not get here System.out.println("Unknown CryptoFileExternal Output Format"); return; } } // Using default key? if ( useDefaultKeyCheckBox.isSelected() ) { cryptoFile.setKsName(mGui.stateObject.getDefaultKeyStore()); cryptoFile.setKeyAlias(mGui.stateObject.getDefaultKeyAlias()); } if (cryptoFile instanceof CryptoFileNative) { // Does the File currently exist? if ( new java.io.File( cryptoFile.getFullyPathedFileName()).exists() ) { JFrame frame = new JFrame(); int n = JOptionPane.showOptionDialog( frame, "A file with this name currently exits." + newline + "If you continue, the existing file will be overwritten." + newline + "Any data in the file will be lost." + newline + "Continue?", "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {"Yes", "No"}, "No"); if ( n != 0 ) { // System.out.println("Canceling..."); return; } } ret = new VerifyKeyStore(mGui).verifyLocation ( cryptoFile, 1 ); if (! ret) { if ( StateObject.getFileChooserCancel() ) { StateObject.setFileChooserCancel( false ); } else { // notify if failure JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Unable to proceed without a valid KeyStore." + mGui.newline + "Check the console for additional information.", "Unable to Verify the KeyStore", JOptionPane.WARNING_MESSAGE); } return; } // Get Key and KeyStore passphrase // (2 = KeyStore, 3 = Key, 6 = KeyStore+Key) // JFrame frame = new JFrame(); new AuthDialog(frame, true, 6, cryptoFile); if ( cryptoFile.getKsPass() == null ) { return; } if ( cryptoFile.getKeyPass() == null ) { return; } // System.out.println("Closing..."); createFileDialog.setVisible(false); createFileDialog.dispose(); // Ensure the filename has the .PDS extension pattern = Pattern.compile("(.+)\\.PDS", Pattern.CASE_INSENSITIVE); matcher = pattern.matcher( cryptoFileNameField.getText() ); if( ! matcher.matches()) { cryptoFile.setFullyPathedFileName( cryptoFile.getFullyPathedFileName() + ".PDS" ); cryptoFile.setFileName( cryptoFile.getFileName() + ".PDS"); } // System.out.println("Current filename is: " + cryptoFile.getFileName() ); // System.out.println("Current full path of filename is: " + cryptoFile.getFullyPathedFileName() ); // Create a file of type Native ret = createNewFileActionPerformed(evt, cryptoFile); if (ret) { mGui.saveMenuItem.setEnabled(true); mGui.saveAsMenuItem.setEnabled(true); mGui.closeMenuItem.setEnabled(true); mGui.iconSave.setEnabled(true); mGui.iconSave.repaint(); } } else if (cryptoFile instanceof CryptoFileExternal) { CryptoFileExternal cryptoFileExternal = (CryptoFileExternal) cryptoFile; // Set the Destination Directory // if ( encryptToDefaultDir.isSelected() ) { cryptoFileExternal.setEncFilePath( mGui.stateObject.getDefaultEncryptedFilePath() + cryptoFileExternal.getFileName() + ".PDS" ); // System.out.println("Default directory."); // System.out.println("Encrypting to: " + cryptoFileExternal.getEncFilePath()); } else if ( encryptToSameDir.isSelected() ) { cryptoFileExternal.setEncFilePath( cryptoFileExternal.getFullyPathedFileName() + ".PDS" ); // System.out.println("Same directory."); // System.out.println("Encrypting to: " + cryptoFileExternal.getEncFilePath()); } else if ( encryptToSelectedDir.isSelected() ) { cryptoFileExternal.setEncFilePath( cryptoFileExternal.getEncFilePath() + cryptoFileExternal.getFileName() + ".PDS" ); // System.out.println("Selected directory."); // System.out.println("Encrypting to: " + cryptoFileExternal.getEncFilePath()); } else if ( encryptToRawDevice.isSelected() ) { cryptoFileExternal.setEncFilePath( encryptToRawDeviceField.getText()); // System.out.println("Device file set to: " + cryptoFileExternal.getEncFilePath()); } else { // Should not get here - we've checked previously System.out.println("Unknown destination directory: " + cryptoFileExternal.getEncFilePath()); return; } // System.out.println("OutputFileFormat: " + cryptoFileExternal.getOutputFileFormat() ); if ( cryptoFileExternal.getEncryptedOutputFormat() != 2 ) { if ( encryptBase64.isSelected() ) { cryptoFileExternal.setEncryptedOutputFormat( 0 ); } else if ( encryptBinary.isSelected() ) { cryptoFileExternal.setEncryptedOutputFormat( 1 ); } else { // Should not get here - we've checked previously System.out.println("Unknown output file format: " + cryptoFileExternal.getEncryptedOutputFormat()); return; } } // System.out.println("OutputFileFormat: " + cryptoFileExternal.getOutputFileFormat() ); // Prompt before overwriting files - don't prompt for device files // if ( cryptoFileExternal.getDeviceType() == 0 ) {; // Does a file already exist where we want to write? try { if ( new java.io.File( cryptoFileExternal.getEncFilePath() ).exists() ) { JFrame frame = new JFrame(); int n = JOptionPane.showOptionDialog( frame, newline + "About to encrypt:" + newline + cryptoFile.getFullyPathedFileName() + newline + "to:" + newline + cryptoFileExternal.getEncFilePath() + newline + newline + "A file with this name currently exists. If you continue," + newline + "this file will be overwritten and any data in the file will be lost." + newline + newline + "Continue?", "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {"Yes", "No"}, "No"); if ( n != 0 ) { // System.out.println("Canceling..."); return; } } } catch (Exception e) { System.out.println("Unable to get fully pathed filename: " + e); return; } } ret = new VerifyKeyStore(mGui).verifyLocation ( cryptoFile, 1 ); if (! ret) { if ( StateObject.getFileChooserCancel() ) { StateObject.setFileChooserCancel( false ); } else { // notify if failure JFrame frame = new JFrame(); JOptionPane.showMessageDialog( frame, "Unable to proceed without a valid KeyStore." + mGui.newline + "Check the console for additional information.", "Unable to Verify the KeyStore", JOptionPane.WARNING_MESSAGE); } return; } // Get Key and KeyStore passphrase // (2 = KeyStore, 3 = Key, 6 = KeyStore+Key) // JFrame frame = new JFrame(); new AuthDialog(frame, true, 6, cryptoFile); if ( cryptoFile.getKsPass() == null ) { return; } if ( cryptoFile.getKeyPass() == null ) { return; } // System.out.println("Closing..."); createFileDialog.setVisible(false); createFileDialog.dispose(); // Encrypt job will be dispatched to a Thread - should return right away // mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (! new CryptoFileExternal().encryptFile( cryptoFileExternal ) ){ mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); // notify if failure JOptionPane.showMessageDialog( frame, "Error requesting encryption." + newline + "Check the console for additional information or try again.", "Error requesting encryption.", JOptionPane.ERROR_MESSAGE); } mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } /////////////////////////////////////////////////////////////////////// /** * Listeners for the CreateFileDialog inner class * */ /////////////////////////////////////////////////////////////////////// // // Get the File **NAME** // private void newCryptoFileActionPerformed(ActionEvent evt, int newFileType, CryptoFile cryptoFile) { final JFileChooser fileChooser; if (mGui.stateObject.getDefaultEncryptedFilePath() instanceof String) { // System.out.println( mGui.stateObject.getDefaultEncryptedFilePath() ); fileChooser = new JFileChooser ( mGui.stateObject.getDefaultEncryptedFilePath() ); } else { fileChooser = new JFileChooser ( mGui.runTimePath ); } fileChooser.setDialogTitle("New File"); fileChooser.setApproveButtonText("OK"); // newFileType (0 = Native File, 1 = External File, 2 = Directory) if ( newFileType == 0 ) { fileChooser.setDialogTitle( "File To Encrypt" ); FileNameExtensionFilter filterPDS = new FileNameExtensionFilter("Professional Data Security Files (PDS)", "PDS"); FileNameExtensionFilter filterJCEKS = new FileNameExtensionFilter("Java Cryptographic Extension (JCE) KeyStores (JCEKS)", "JCEKS"); FileNameExtensionFilter filterJKS = new FileNameExtensionFilter("Java KeyStores (JKS)", "JKS"); FileNameExtensionFilter filterKeyStores = new FileNameExtensionFilter( "Java KeyStores (JCEKS, JKS)", "JCEKS", "JKS"); fileChooser.addChoosableFileFilter( filterJKS ); fileChooser.addChoosableFileFilter( filterJCEKS ); fileChooser.addChoosableFileFilter( filterKeyStores ); fileChooser.addChoosableFileFilter( filterPDS ); } if ( newFileType == 2 ) { fileChooser.setDialogTitle( "Directory To Encrypt" ); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } int returnVal = fileChooser.showOpenDialog(createFileDialog); if ( returnVal == 0 ) { // Set the File name in the new CryptoFile object cryptoFile.setFullyPathedFileName( fileChooser.getSelectedFile().getPath() ); cryptoFile.setFileName( fileChooser.getSelectedFile().getName() ); // Ensure ".PDS" extension exists for Native files if ( cryptoFile instanceof CryptoFileNative ) { Pattern pattern = Pattern.compile("(.*).PDS", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher( cryptoFile.getFullyPathedFileName() ); if( ! matcher.matches()) { cryptoFile.setFullyPathedFileName( cryptoFile.getFullyPathedFileName() + ".PDS" ); cryptoFile.setFileName( fileChooser.getSelectedFile().getName() + ".PDS"); } } // Update the Gui cryptoFileNameField.setEnabled(true); cryptoFileNameField.requestFocus(); cryptoFileNameField.setText( cryptoFile.getFullyPathedFileName() ); cryptoFileNameField.setEnabled(true); cryptoFileNameField.repaint(); // System.out.print("New File: " + cryptoFile.getFullyPathedFileName() + newline); } else if ( returnVal == 1 ) { // System.out.print("Canceling..." + newline); } else { System.out.print("Error: " + returnVal + newline); } } // // Associate the CryptoFile with a Key in a KeyStore // private int associateKeyStoreActionPerformed(ActionEvent evt, CryptoFile cryptoFile) { int returnVal; JFileChooser fileChooser; if ( mGui.stateObject.getDefaultKeyStoreDir() != null ) { fileChooser = new JFileChooser ( mGui.stateObject.getDefaultKeyStoreDir() ); } else { fileChooser = new JFileChooser ( mGui.runTimePath ); } fileChooser.setDialogTitle( "KeyStore Location" ); fileChooser.setApproveButtonText("Select"); FileNameExtensionFilter filterPDS = new FileNameExtensionFilter("Professional Data Security Files (PDS)", "PDS"); FileNameExtensionFilter filterJCEKS = new FileNameExtensionFilter("Java Cryptographic Extension (JCE) KeyStores (JCEKS)", "JCEKS"); FileNameExtensionFilter filterJKS = new FileNameExtensionFilter("Java KeyStores (JKS)", "JKS"); FileNameExtensionFilter filterKeyStores = new FileNameExtensionFilter("Java KeyStores (JCEKS, JKS)", "JCEKS", "JKS"); fileChooser.addChoosableFileFilter( filterJKS ); fileChooser.addChoosableFileFilter( filterJCEKS ); fileChooser.addChoosableFileFilter( filterPDS ); fileChooser.addChoosableFileFilter(filterKeyStores); returnVal = fileChooser.showOpenDialog(createFileDialog); if ( returnVal == 0 ) { // Set the KeyStore name in the new CryptoFile object cryptoFile.setKsName( fileChooser.getSelectedFile().getPath() ); // System.out.println("KeyStore Name: " + cryptoFile.getKsName()); // Update the Gui keyStoreNameField.setText( cryptoFile.getKsName() ); keyStoreNameField.repaint(); // System.out.print("KeyStore: " + cryptoFile.getKsName() + newline); } else if ( returnVal == 1 ) { // System.out.print("Canceling..." + newline); } else { System.out.print("Error: " + returnVal + newline); } return returnVal; } // // Create the file // private boolean createNewFileActionPerformed (ActionEvent evt, CryptoFile cryptoFile) { JFrame frame = new JFrame(); // System.out.println("Creating new encrypted file..."); // Checks (file name, key store, key) if ( cryptoFile.getFullyPathedFileName() == null ) { // notify if failure JOptionPane.showMessageDialog( frame, "File name cannot be empty.", "File Name", JOptionPane.WARNING_MESSAGE); return false; } if ( cryptoFile.getKsName() == null ) { // notify if failure JOptionPane.showMessageDialog( frame, "KeyStore cannot be empty.", "KeyStore Name", JOptionPane.WARNING_MESSAGE); return false; } if ( cryptoFile.getKeyAlias() == null ) { // notify if failure JOptionPane.showMessageDialog( frame, "Key alias cannot be empty.", "Key Alias", JOptionPane.WARNING_MESSAGE); return false; } // Does the directory where the file to be created exist? // Conditions where this might not be true: // 1. FileChooser is not used and a bogus fully pathed file name is provided. // 2. Only a file name is provided, and the default file path is unavailable // - the path has been deleted, moved or never existed // - the path was on an unmounted drive (such as a thumb drive) // // Find the directory path only Pattern pattern = Pattern.compile("(.*)[/\\\\](.*)"); Matcher matcher = pattern.matcher( cryptoFile.getFullyPathedFileName() ); if ( matcher.matches() ) { // System.out.println("Directory is: " + matcher.group(1) ); // Check to see if the directory exists if ( ! new java.io.File( matcher.group(1) ).exists() ) { // notify if failure JOptionPane.showMessageDialog( frame, "The directory to contain the new file:" + newline + newline + matcher.group(1) + newline + newline + "does not exist." + newline + newline + "Please select a different directory for this file." + newline + newline, "Key Alias", JOptionPane.WARNING_MESSAGE); return false; } } // Create the new CryptoFile // System.out.println("About to create: " + cryptoFile.getFullyPathedFileName()); mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (! new CryptoEngine().encrypt ( cryptoFile ) ) { mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); // notify if failure JOptionPane.showMessageDialog( frame, "Error creating the new file." + newline + "Retry using different credentials or" + newline + "check the console for additional information.", "Error Creating File", JOptionPane.ERROR_MESSAGE); return false; } mGui.mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); // Display the editor pane if (cryptoFile instanceof CryptoFileNative) { cryptoFile = (CryptoFileNative) cryptoFile; // System.out.println("Internal frame count is: " + desktopPane.getAllFrames().length); JInternalFrame internalFrame = (JInternalFrame) new MyInternalFrame( mGui, cryptoFile ); // System.out.println("Internal frame count is: " + desktopPane.getAllFrames().length); // Close it manually, allowing for the CANCEL option internalFrame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE); internalFrame.setSize(500, 300); internalFrame.setLocation( 20*mGui.desktopPane.getAllFrames().length, 30*mGui.desktopPane.getAllFrames().length ); mGui.desktopPane.add( internalFrame ); final UndoManager undo = new UndoManager(); // This listens for and reports caret movements. final class CaretListenerLabel extends JLabel implements CaretListener { public CaretListenerLabel(String label) { super(label); } // Might not be invoked from the event dispatch thread. public void caretUpdate(CaretEvent e) { } } // This one listens for edits that can be undone. final class MyUndoableEditListener implements UndoableEditListener { public void undoableEditHappened(UndoableEditEvent e) { // Remember the edit and update the menus. undo.addEdit(e.getEdit()); mGui.undoAction.updateUndoState(); mGui.redoAction.updateRedoState(); } } // Create the Editor final JEditorPane editorPane = new JEditorPane(); // And this one listens for any changes to the document. final class MyDocumentListener implements DocumentListener { public void insertUpdate(DocumentEvent e) { ((MyDefaultStyledDocument) editorPane.getDocument()).setDocumentChanged( true ); } public void removeUpdate(DocumentEvent e) { ((MyDefaultStyledDocument) editorPane.getDocument()).setDocumentChanged( true ); } public void changedUpdate(DocumentEvent e) { ((MyDefaultStyledDocument) editorPane.getDocument()).setDocumentChanged( true ); } } editorPane.putClientProperty("editor", editorPane); editorPane.setPreferredSize(new Dimension(450,250)); editorPane.setEditable(true); editorPane.setEditorKit( new StyledEditorKit() ); editorPane.setCaretPosition(0); editorPane.getDocument().addUndoableEditListener(new MyUndoableEditListener()); editorPane.addCaretListener(new CaretListenerLabel("")); editorPane.putClientProperty("undo", undo); editorPane.setDocument(((CryptoFileNative) cryptoFile).getActiveDocument()); editorPane.getDocument().addDocumentListener(new MyDocumentListener()); editorPane.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { StateObject.setEditorInFocus(editorPane); mGui.undoAction.updateUndoState(); mGui.redoAction.updateRedoState(); } public void focusLost(FocusEvent e) { } }); // Add ScrollBars JScrollPane scrollPane = new JScrollPane(editorPane); // And Activate editorPane.addNotify(); scrollPane.addNotify(); // Add Editor to Internal Frame internalFrame.getContentPane().add( scrollPane, BorderLayout.CENTER ); // And show... internalFrame.toFront(); internalFrame.setVisible(true); } return true; } }