-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDFCrypt.java
More file actions
1624 lines (1565 loc) · 60.3 KB
/
Copy pathPDFCrypt.java
File metadata and controls
1624 lines (1565 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PDFCrypt is a lightweight graphical frontend for Apache PDFBox, the Java PDF library.
*
* Thsi example code allows users to encrypt or decrypt multiple PDF files through an
* intuitive graphical interface (without using the PDFBox's command line).
*
* Features:
*
* * AES-128 PDF encryption using Apache PDFBox
* * Batch processing of multiple PDF files
* * Drag & Drop support
* * Optional copy to another destination directory (e.g. USB drive)
* * Optional deletion of source files after processing
* * Automatic overwrite management
* * Multilingual interface
* * Fully compatible with the standard PDF security specification
*
* @author : Eric Normandin
* @date : july 2026
* @version : 1.0
*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JLayeredPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
//import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Locale;
import java.util.ResourceBundle.Control;
import java.util.PropertyResourceBundle;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.Component;
import java.awt.HeadlessException;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
//import java.awt.image.BufferedImage;
//import java.awt.TextField;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.NoSuchFileException;
//import java.time.format.DateTimeFormatter;
//import java.time.LocalDateTime;
import java.net.URL;
import java.net.URLConnection;
//import java.net.NetworkInterface;
/*******************
* Drag and Drop *
*******************/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
/*******************
* PDFbox *
*******************/
import org.apache.pdfbox.Loader;
//import org.apache.pdfbox.util.Version;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
public class PDFCrypt
{
private enum CryptoMode {
CRYPT, // Represents the "Encrypt" action
DECRYPT // Represents the "Decrypt" action
}
/*****************************
* CUSTOM PRIVATE PROPERTIES *
*****************************/
private final boolean DEBUG = false;
private static final int FRAME_SIZE_X = 600; // size x
private static final int FRAME_SIZE_Y = 510; // size y
private static final int btnShow_LOCATION_X = 420; // location x
private static final int btnShow_LOCATION_Y = 15; // location y
private static final int btnShow_SIZE_X = 140; // size height
private static final int btnShow_SIZE_Y = 40; // size width
private static final int btnOpen_LOCATION_X = 420; // location x
private static final int btnOpen_LOCATION_Y = 70; // location y
private static final int btnOpen_SIZE_X = 140; // size height
private static final int btnOpen_SIZE_Y = 40; // size width
private static final int btnSwap_LOCATION_X = 420; // location x
private static final int btnSwap_LOCATION_Y = 125; // location y
private static final int btnSwap_SIZE_X = 140; // size height
private static final int btnSwap_SIZE_Y = 40; // size width
private static final int btnSave_LOCATION_X = 420; // location x
private static final int btnSave_LOCATION_Y = 220; // location y
private static final int btnSave_SIZE_X = 140; // size height
private static final int btnSave_SIZE_Y = 40; // size width
private static final int btnRemove_LOCATION_X = 420; // location x
private static final int btnRemove_LOCATION_Y = 270; // location y
private static final int btnRemove_SIZE_X = 140; // size height
private static final int btnRemove_SIZE_Y = 40; // size width
private static final int btnEncrypt_LOCATION_X = 420; // location x
private static final int btnEncrypt_LOCATION_Y = 320; // location y
private static final int btnEncrypt_SIZE_X = 140; // size height
private static final int btnEncrypt_SIZE_Y = 40; // size width
private static final int btnDecrypt_LOCATION_X = 420; // location x
private static final int btnDecrypt_LOCATION_Y = 370; // location y
private static final int btnDecrypt_SIZE_X = 140; // size height
private static final int btnDecrypt_SIZE_Y = 40; // size width
private static final int btnQuit_LOCATION_X = 420; // location x
private static final int btnQuit_LOCATION_Y = 420; // location y
private static final int btnQuit_SIZE_X = 140; // size height
private static final int btnQuit_SIZE_Y = 40; // size width
private static final int txtPassword_LOCATION_X = 10; // location x
private static final int txtPassword_LOCATION_Y = 25; // location y
private static final int txtPassword_SIZE_X = 380; // size height
private static final int txtPassword_SIZE_Y = 30; // size width
private static final int txtPath_LOCATION_X = 10; // location x
private static final int txtPath_LOCATION_Y = 80; // location y
private static final int txtPath_SIZE_X = 380; // size height
private static final int txtPath_SIZE_Y = 30; // size width
private static final int txtPath2_LOCATION_X = 10; // location x
private static final int txtPath2_LOCATION_Y = 230; // location y
private static final int txtPath2_SIZE_X = 380; // size height
private static final int txtPath2_SIZE_Y = 30; // size width
private static final int fileList_LOCATION_X = 10; // location x
private static final int fileList_LOCATION_Y = 290; // location y
private static final int fileList_SIZE_X = 380; // size height
private static final int fileList_SIZE_Y = 170; // size width
private static final int cbDestPath_LOCATION_X = 10; // location x
private static final int cbDestPath_LOCATION_Y = 115; // location y
private static final int cbDestPath_SIZE_X = 280; // size height
private static final int cbDestPath_SIZE_Y = 30; // size width
private static final int cbDelFileSource_LOCATION_X = 10; // location x
private static final int cbDelFileSource_LOCATION_Y = 145; // location y
private static final int cbDelFileSource_SIZE_X = 280; // size height
private static final int cbDelFileSource_SIZE_Y = 30; // size width
private static final int cbOverWriteFileDest_LOCATION_X = 10; // location x
private static final int cbOverWriteFileDest_LOCATION_Y = 175; // location y
private static final int cbOverWriteFileDest_SIZE_X = 420; // size height
private static final int cbOverWriteFileDest_SIZE_Y = 30; // size width
private static final int MAX_PASSWORD_LENGTH = 32;
// All objects for the graphical user interface
private static JButton btnShow;
private static JButton btnOpen;
private static JButton btnSwap;
private static JButton btnSave;
private static JButton btnRemove;
private static JButton btnEncrypt;
private static JButton btnDecrypt;
private static JButton btnQuit;
private static JFrame frame;
private static JPasswordField txtPassword;
private static JLabel label1;
private static JTextField txtPath2;
private static JLabel label2;
private static JTextField txtPath;
private static JLabel label3;
private static JList<String> fileList;
private static JScrollPane listScrollPane;
private static JLabel label4;
private static JLabel myStatusBar;
private static JCheckBox cbDestPath;
private static JCheckBox cbDelFileSource;
private static JCheckBox cbOverWriteFileDest;
private static JLabel instruction;
/*****************************
* CUSTOM PRIVATE PROPERTIES *
*****************************/
private static int countdown = 0; // countdown in seconds
//private static int ouvrir_click = 0; // nombre de click sur le bouton ouvrir
private static String fileSeparator;
//private static String strPassword = "";
private static boolean preventUncrypt = false;
//private static final String newline = "\n";
private static boolean oneIsCrypted = false;
private static boolean oneIsUncrypted = false;
//private static ArrayList<String> arrayFile = new ArrayList<>();
private static Image icon = null;
private static String startPath = "";
private static String destPath = "";
private static String systemPath = "";
private static DefaultListModel<String> listModel = new DefaultListModel<>();
private static Locale defaultLocale = Locale.ENGLISH; //new Locale("en", "US");
private static Timer passwordTimer;
private static boolean passwordVisible = false;
/**************************
* CUSTOM PRIVATE METHODS *
**************************/
/**
* Prints a debug message on standard output if DEBUG mode is turned on.
*/
protected void debug(String message) {
if (DEBUG) {
System.out.println("[DEBUG] " + message);
}
}
/**
* Prints a debug message on standard output if DEBUG mode is turned on.
*/
protected void debug(String message, byte[] bytes) {
if (DEBUG) {
StringBuilder buffer = new StringBuilder("[DEBUG] ");
buffer.append(message);
buffer.append("[");
for (int i = 0; i < bytes.length; i++) {
buffer.append(bytes[i]);
buffer.append(i < bytes.length - 1 ? ", " : "]");
}
System.out.println(buffer.toString());
}
}
private static class PdfCryptoService {
public int encryptPDF(
String inputFilePath,
String outputFilePath,
char[] userPassword,
char[] ownerPassword) throws IOException {
try (PDDocument document = Loader.loadPDF(new File(inputFilePath))) {
// Load the PDF file
//PDDocument document = Loader.loadPDF(new File(inputFilePath));
// Create a protection policy with AES 128-bit
AccessPermission accessPermission = new AccessPermission();
//StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(
// String.copyValueOf(ownerPassword),
// String.copyValueOf(userPassword),
// accessPermission
//);
StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(
String.valueOf(ownerPassword),
String.valueOf(userPassword),
accessPermission
);
protectionPolicy.setEncryptionKeyLength(128); // AES 128-bit
protectionPolicy.setPermissions(accessPermission);
// Apply encryption to the document
document.protect(protectionPolicy);
// Delete the destination file if it already exists
Files.deleteIfExists(Paths.get(outputFilePath));
// Save the encrypted document
document.save(outputFilePath);
document.close(); // not necessary, the "try-with-resources" do it also.
return 0;
}
catch (NoSuchFileException e) {
//e.printStackTrace();
return 1;
}
catch (IOException e) {
//e.printStackTrace();
return 1;
}
catch (Exception e) {
//e.printStackTrace();
return 1;
}
}
public int decryptPDF(
String inputFilePath,
String outputFilePath,
char[] password) throws IOException {
//try (PDDocument document = Loader.loadPDF(new File(inputFilePath), String.copyValueOf(password))) {
try (PDDocument document = Loader.loadPDF(new File(inputFilePath), String.valueOf(password))) {
// Load the encrypted PDF document using Loader.loadPDF
//PDDocument document = Loader.loadPDF(new File(inputFilePath), password);
// Remove document protection
document.setAllSecurityToBeRemoved(true);
// Delete the destination file if it already exists
Files.deleteIfExists(Paths.get(outputFilePath));
// Save the decrypted document
document.save(outputFilePath);
document.close(); // not necessary, the "try-with-resources" do it also.
//Success
return 0;
}
catch (InvalidPasswordException e) {
//e.printStackTrace();
return 1;
}
catch (NoSuchFileException e) {
//e.printStackTrace();
return 1;
}
catch (IOException e) {
//e.printStackTrace();
return 1;
}
catch (Exception e) {
//e.printStackTrace();
return 1;
}
}
}
private static String getFromClipboard() {
String str = "";
// This represents the paste (Ctrl+V) operation
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
try
{
Transferable t = cb.getContents(null);
if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
str = (String) t.getTransferData(DataFlavor.stringFlavor);
return str;
}
catch (UnsupportedFlavorException | IOException ex) {
//System.out.println("");
//str = "";
return str;
}
//finally {
// //System.out.println("");
// return str;
//}
}
private void copyToClipboard(String text) {
// This represents the paste (Ctrl+X or Ctrl+C) operation
//StringSelection data = new StringSelection ("This is copied to the clipboard");
StringSelection data = new StringSelection (text);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Clipboard clipboard = toolkit.getSystemClipboard();
//ClipboardContent content = clipboard;
//data.setText(Text);
clipboard.setContents(data, data);
}
public static boolean pathMatchSpecEnd(String filePath, String pattern) {
int fileIndex = filePath.length() - 1;
int patternIndex = pattern.length() - 1;
while (fileIndex >= 0 && patternIndex >= 0) {
char c = pattern.charAt(patternIndex);
if (c == '*') {
patternIndex--;
if (patternIndex < 0) {
return true;
}
char nextChar = pattern.charAt(patternIndex);
while (fileIndex >= 0) {
if (Character.toLowerCase(filePath.charAt(fileIndex)) == Character.toLowerCase(nextChar)) {
break;
}
fileIndex--;
}
} else if (c != '?' && Character.toLowerCase(c) != Character.toLowerCase(filePath.charAt(fileIndex))) {
return false;
}
fileIndex--;
patternIndex--;
}
return fileIndex < 0 && patternIndex < 0;
}
// Listener for managing file drag and drop
private static class FileDropTargetListener implements DropTargetListener {
@Override
public void dragEnter(DropTargetDragEvent e) {
// Accept the Drag operation
e.acceptDrag(e.getDropAction());
}
@Override
public void dragOver(DropTargetDragEvent e) {
// Nothing to do here
}
@Override
public void dropActionChanged(DropTargetDragEvent e) {
// Nothing to do here
}
@Override
public void dragExit(DropTargetEvent e) {
// Nothing to do here
}
@Override
public void drop(DropTargetDropEvent e) {
boolean success = false;
if (!e.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
e.rejectDrop();
return;
}
try {
// Accept the Drop
e.acceptDrop(DnDConstants.ACTION_COPY);
// Retrieve the list of dropped files
Object transferData = e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
@SuppressWarnings("unchecked") // Remove the warning for the next line
List<File> droppedFiles = (List<File>) transferData;
if (!droppedFiles.isEmpty()) {
addFilesToList(droppedFiles);
}
success = true;
}
catch (UnsupportedFlavorException | IOException ex) {
//e.dropComplete(false);
ex.printStackTrace();
JOptionPane.showMessageDialog(null,
Messages.getString("error_drop_message") + " " + ex.getMessage(),
Messages.getString("error_drop_title"), JOptionPane.ERROR_MESSAGE);
}
finally {
e.dropComplete(success);
}
}
}
private static boolean addFilesToList(List<File> theseFiles) {
boolean warningDirectory = false;
boolean success = false;
// To prepare the search for files already present in the JList (connected to the listModel)
List<String> listCopy = new ArrayList<>();
// Copy of the listModel
for (int i = 0; i < listModel.getSize(); i++) {
listCopy.add(listModel.getElementAt(i));
}
// Multiple files can be dropped.
for (File file : theseFiles) {
if (!file.isDirectory()) {
// Process the dropped files
String thisPath = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - file.getName().length());
//String thisPath = file.getParent(); // The final separator is missing!
String thisFile = file.getName(); // File name only (without directory path)
if (listModel.getSize() > 0) {
if (!txtPath.getText().equalsIgnoreCase(thisPath)) {
if (!warningDirectory) {
JOptionPane.showMessageDialog(null,
Messages.getString("error_append_message"),
Messages.getString("error_append_title"), JOptionPane.INFORMATION_MESSAGE );
warningDirectory = true;
}
}
else {
if (file.exists() && pathMatchSpecEnd(thisFile, "*.pdf")) {
if (!listCopy.contains(thisFile)) {
// Add the file only if it is new.
listModel.addElement(thisFile);
listCopy.add(thisFile);
success = true;
}
}
}
}
else {
// Change the source directory for the new files
txtPath.setText(thisPath);
if (cbDestPath.isSelected()) txtPath2.setText(thisPath);
if (file.exists() && pathMatchSpecEnd(thisFile, "*.pdf")) {
txtPath.setText(thisPath);
listModel.addElement(thisFile);
listCopy.add(thisFile);
success = true;
}
}
}
}
oneIsCrypted = false;
oneIsUncrypted = false;
if (listModel.getSize() > 0) {
for (int i = 0; i < listModel.getSize(); i++) {
if (pathMatchSpecEnd(listModel.getElementAt(i), "*.crypt.pdf"))
oneIsCrypted = true;
else
oneIsUncrypted = true;
}
btnSwap.setEnabled(false);
btnRemove.setEnabled(true);
instruction.setVisible(false);
}
else {
if (!cbDestPath.isSelected()) btnSwap.setEnabled(true);
btnRemove.setEnabled(false);
instruction.setVisible(true);
}
if (oneIsUncrypted) btnEncrypt.setEnabled(true);
else btnEncrypt.setEnabled(false);
if (oneIsCrypted) btnDecrypt.setEnabled(true);
else btnDecrypt.setEnabled(false);
return success;
}
private static int processFiles(CryptoMode mode) {
int nbFiles = 0;
//System.out.println("btnEncrypt event ACTION_PERFORMED execute");
// get the password
char[] password = txtPassword.getPassword();
if (password.length < 4) {
JOptionPane.showMessageDialog(frame,
Messages.getString("error_pwd_message"),
Messages.getString("error_pwd_title"), JOptionPane.WARNING_MESSAGE);
return 0;
}
if (listModel.getSize() == 0) {
return 0;
}
else {
try {
boolean OneConverted = false;
if (mode == CryptoMode.CRYPT) preventUncrypt = false;
boolean[] successConvert = new boolean[listModel.getSize()];
for (int i = 0; i < listModel.getSize(); i++) {
String inputFile = txtPath.getText() + listModel.getElementAt(i);
String outputFile = txtPath2.getText() + listModel.getElementAt(i);
successConvert[i] = false;
if (inputFile.length() != 0) {
File inFile = new File(inputFile);
//File outFile = new File(outputFile);
// *** section PDF Encrypt/Decrypt ***
PdfCryptoService PdfCrypto = new PdfCryptoService();
if (inFile.exists() && !inFile.isDirectory()) {
if (mode == CryptoMode.CRYPT) {
if (pathMatchSpecEnd(inputFile, "*.pdf")) {
if (!pathMatchSpecEnd(inputFile, "*.crypt.pdf")) {
outputFile = outputFile.substring(0, outputFile.length() - 4) + ".crypt.pdf";
File outFile = new File(outputFile);
if (outFile.exists()) {
int answer;
if (cbOverWriteFileDest.isSelected()) answer = JOptionPane.YES_OPTION;
else {
answer = JOptionPane.showConfirmDialog(frame,Messages.getString("confirm_msg_1")
+ outputFile + Messages.getString("confirm_msg_2"),
Messages.getString("confirm_msg_title"), JOptionPane.YES_NO_CANCEL_OPTION);
}
switch (answer) {
case JOptionPane.YES_OPTION:
outFile.delete();
//JOptionPane.showMessageDialog(frame,str1, "PDF Encrypt", JOptionPane.INFORMATION_MESSAGE);
int retVal = PdfCrypto.encryptPDF(inputFile, outputFile, password, password);
if (retVal != 0)
JOptionPane.showMessageDialog(frame, Messages.getString("error_encrypt"),
Messages.getString("error_encrypt_title"), JOptionPane.WARNING_MESSAGE);
else {
successConvert[i] = true;
OneConverted = true;
nbFiles++;
}
break;
case JOptionPane.NO_OPTION:
//System.out.println("No");
break;
case JOptionPane.CANCEL_OPTION:
//System.out.println("Cancel");
break;
}
}
else {
int retVal = PdfCrypto.encryptPDF(inputFile, outputFile, password, password);
if (retVal != 0)
JOptionPane.showMessageDialog(frame, Messages.getString("error_encrypt"),
Messages.getString("error_encrypt_title"), JOptionPane.WARNING_MESSAGE);
else {
successConvert[i] = true;
OneConverted = true;
nbFiles++;
}
}
}
else { // only, copy input file to output path
File outFile = new File(outputFile);
Files.copy(inFile.toPath(), outFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
File outFile = new File(outputFile);
if (successConvert[i] && outFile.exists()) {
String element = listModel.getElementAt(i);
listModel.setElementAt(element.substring(0, element.length() - 4) + ".crypt.pdf", i);
if(cbDelFileSource.isSelected()) inFile.delete();
}
//else listModel.setElementAt("", i);
}
else { //(mode = DECRYPT)
//outputFile = outputFile.substring(0, outputFile.length() - 10) + ".pdf";
if (pathMatchSpecEnd(inputFile, "*.crypt.pdf")) {
outputFile = outputFile.substring(0, outputFile.length() - 10) + ".pdf";
File outFile = new File(outputFile);
if (outFile.exists()) {
int answer;
if (cbOverWriteFileDest.isSelected()) answer = JOptionPane.YES_OPTION;
else {
answer = JOptionPane.showConfirmDialog(frame,Messages.getString("confirm_msg_1")
+ outputFile + Messages.getString("confirm_msg_2"),
Messages.getString("confirm_msg_title"), JOptionPane.YES_NO_CANCEL_OPTION);
}
switch (answer) {
case JOptionPane.YES_OPTION:
outFile.delete();
//JOptionPane.showMessageDialog(frame,str1, "PDF Encrypt", JOptionPane.INFORMATION_MESSAGE);
int retVal = PdfCrypto.decryptPDF(inputFile, outputFile, password);
if (retVal != 0)
JOptionPane.showMessageDialog(frame, Messages.getString("error_decrypt"),
Messages.getString("error_decrypt_title"), JOptionPane.WARNING_MESSAGE);
else {
successConvert[i] = true;
OneConverted = true;
nbFiles++;
}
break;
case JOptionPane.NO_OPTION:
//System.out.println("No");
break;
case JOptionPane.CANCEL_OPTION:
//System.out.println("Cancel");
break;
}
}
else {
int retVal = PdfCrypto.decryptPDF(inputFile, outputFile, password);
if (retVal != 0)
JOptionPane.showMessageDialog(frame, Messages.getString("error_decrypt"),
Messages.getString("error_decrypt"), JOptionPane.WARNING_MESSAGE);
else {
successConvert[i] = true;
OneConverted = true;
nbFiles++;
}
}
}
File outFile = new File(outputFile);
if (successConvert[i] && outFile.exists()) {
String element = listModel.getElementAt(i);
listModel.setElementAt(element.substring(0, element.length() - 10) + ".pdf", i);
if(cbDelFileSource.isSelected()) inFile.delete();
}
//else listModel.setElementAt("" ,i);
if (successConvert[i]) preventUncrypt = true;
}
}
// *** end of section ***
}
}
Arrays.fill(password, '\0'); // erase variable password
// Refresh le listModel
String sTmp;
if (OneConverted) {
if (listModel.getSize() > 0) { // > 1) {
if(!cbDestPath.isSelected()) {
sTmp = txtPath.getText();
txtPath.setText(txtPath2.getText());
txtPath2.setText(sTmp);
}
List<String> listCopy = new ArrayList<>();
for (int i = 0; i < listModel.getSize(); i++) {
sTmp = listModel.getElementAt(i) ;
//if (sTmp != null && !sTmp.equals("")) listCopy.add(sTmp);
if (successConvert[i]) listCopy.add(sTmp);
}
oneIsCrypted = false;
oneIsUncrypted = false;
listModel.removeAllElements();
if (!listCopy.isEmpty()) {
for (int i = 0; i < listCopy.size(); i++) {
sTmp = listCopy.get(i);
listModel.addElement(sTmp);
if (pathMatchSpecEnd(sTmp, "*.crypt.pdf"))
oneIsCrypted = true;
else
oneIsUncrypted = true;
}
}
else if (!cbDestPath.isSelected()) btnSwap.setEnabled(true);
if (oneIsUncrypted) btnEncrypt.setEnabled(true);
else btnEncrypt.setEnabled(false);
if (oneIsCrypted) btnDecrypt.setEnabled(true);
else btnDecrypt.setEnabled(false);
if (listModel.isEmpty()) btnRemove.setEnabled(false);
else btnRemove.setEnabled(true);
}
else //if (listModel.getSize() == 0)
{
btnRemove.setEnabled(false);
btnEncrypt.setEnabled(false);
btnDecrypt.setEnabled(false);
if (!cbDestPath.isSelected()) btnSwap.setEnabled(true);
}
//else { // listModel.getSize() == 1
// ;
//}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return nbFiles;
}
/*************************************
* Class UTF8Control *
*************************************/
private static class UTF8Control extends Control {
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
}
}
/*****************************************
* Class Messages - METHODS & PROPERTIES *
*****************************************/
private static class Messages {
private static final String BUNDLE_NAME = "messages"; // file [messages.properties]
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, defaultLocale, new UTF8Control());
/**
* Get text string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
/*******************************************
* Class JStatusBar - METHODS & PROPERTIES *
*******************************************/
private static class JStatusBar extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel leftPanel;
private JPanel rightPanel;
public JStatusBar() {
createPartControl();
}
private static class SeparatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final Color leftColor;
private final Color rightColor;
public SeparatorPanel(Color leftColor, Color rightColor) {
this.leftColor = leftColor;
this.rightColor = rightColor;
setOpaque(false);
setPreferredSize(new Dimension(2, 18));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(leftColor);
g.drawLine(0, 0, 0, getHeight() - 1);
g.setColor(rightColor);
g.drawLine(1, 0, 1, getHeight() - 1);
}
}
private void createPartControl() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(10, 23));
leftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 3));
leftPanel.setOpaque(false);
add(leftPanel, BorderLayout.WEST);
rightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 5, 3));
rightPanel.setOpaque(false);
add(rightPanel, BorderLayout.EAST);
}
public void setLeftComponent(JComponent component) {
leftPanel.add(component);
}
public void addRightComponent(JComponent component) {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 0));
panel.add(new SeparatorPanel(Color.GRAY, Color.WHITE));
panel.add(component);
rightPanel.add(panel);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = 0;
g.setColor(new Color(156, 154, 140));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(196, 194, 183));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(218, 215, 201));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(233, 231, 217));
g.drawLine(0, y, getWidth(), y);
y = getHeight() - 3;
g.setColor(new Color(233, 232, 218));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(233, 231, 216));
g.drawLine(0, y, getWidth(), y);
y++;
g.setColor(new Color(221, 221, 220));
g.drawLine(0, y, getWidth(), y);
}
}
/********************
* createAndShowGUI *
********************/
private static void createAndShowGUI() {
frame = new JFrame();
String version = org.apache.pdfbox.util.Version.getVersion();
frame.setTitle(Messages.getString("main_title") + " - PDFbox v" + version);
// *** Place the window in the center of the user's screen
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
//frame.setSize(screenWidth / 2, screenHeight / 2);
//frame.setLocation(screenWidth / 4, screenHeight / 4);
//frame.setSize(300, 300);
//frame.setLocation(140, 70);
frame.setSize(FRAME_SIZE_X, FRAME_SIZE_Y);
//frame.setLocation((screenWidth - FRAME_SIZE_X) / 2, (screenHeight - FRAME_SIZE_Y) / 2);
//frame.pack(); // if layouts are used
frame.setLocationRelativeTo(null); // Place the window in the middle of the screen
// *** Enable drag and drop for the JFrame
new DropTarget(frame, new FileDropTargetListener());
//ImageIcon icon = new ImageIcon("/PDFCrypt.png");
//frame.setIconImage(icon.getImage());
// *** ICON file loading
// Loading the image from the JAR resources
//URL iconUrl = PDFCrypt.class.getClassLoader().getResource("PDFCrypt.png");
//frame.setIconImage(tk.getImage(iconUrl));
//System.out.println(iconUrl);
//Image icon = null;
try {
// Make sure the path is correct in relation to your project structure
URL iconURL = PDFCrypt.class.getResource("PDFCrypt.png");
if (iconURL != null) {
//Image icon = ImageIO.read(iconURL);
icon = ImageIO.read(iconURL);
} else {
System.err.println(Messages.getString("icon_failed"));
}
} catch (IOException e) {
e.printStackTrace();
}
if (icon != null) {
frame.setIconImage(icon);
}
//frame.setLayout(null);
frame.setLayout(new BorderLayout());
frame.setResizable(false);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//frame.setState(Frame.ICONIFIED);
//frame.setExtendedState(JFrame.ICONIFIED);
//frame.setState(Frame.NORMAL);
frame.setExtendedState(JFrame.NORMAL);
//frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_DEICONIFIED));
/*frame.addWindowListener(new WindowListener()
{
@Override
public void windowDeiconified(WindowEvent e)
{
if (JOptionPane.showConfirmDialog(null, "Are you sure you want to change state ?", "Confirm",
JOptionPane.OK_OPTION, 0, new ImageIcon("")) != 0) {
return;
}
frame.setExtendedState(JFrame.NORMAL);
}
});
*/
// *** Create the North JPanel
JPanel northPanel = new JPanel(null);
northPanel.setPreferredSize(new Dimension(FRAME_SIZE_X, FRAME_SIZE_Y - 30));
// Create the status bar
JStatusBar statusBar = new JStatusBar();
JLabel leftLabel = new JLabel("...");
statusBar.setLeftComponent(leftLabel);
// Create the text box for the password
txtPassword = new JPasswordField(MAX_PASSWORD_LENGTH)
{
//@Override
public void paste(){
// This represents a paste (Ctrl+V) operation.
this.setText(getFromClipboard());
}
};
txtPassword.setBounds(txtPassword_LOCATION_X, txtPassword_LOCATION_Y, txtPassword_SIZE_X, txtPassword_SIZE_Y);
// Change text font size
txtPassword.setFont(new Font("SansSerif",Font.PLAIN,14)); //(new Font("Serif",Font.BOLD,12));
//txtPassword.setEchoChar('\u26AB'); // Unicode character Medium Black Circle
txtPassword.setEchoChar('*');
// Change text font color
txtPassword.setBackground(Color.WHITE);
txtPassword.setForeground(Color.BLACK);
//frame.add(txtPassword); //Ajouter la zone de texte
label1 = new JLabel(Messages.getString("enter_password"));
label1.setBounds(txtPassword_LOCATION_X, txtPassword_LOCATION_Y - 25, txtPassword_SIZE_X, txtPassword_SIZE_Y);
label1.setLabelFor(txtPassword);
//frame.add(label1);
// *** url : https://www.geeksforgeeks.org/java-swing-jseparator-with-examples/
//JSeparator myLine = new JSeparator(JSeparator.HORIZONTAL);