IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Java Discussion :

Automatiser des signatures numériques


Sujet :

Java

  1. #1
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut Automatiser des signatures numériques
    Bonjour à tous,

    Suite à ce sujet : http://www.developpez.net/forums/d14...e/#post7769992

    J'ai avancer et je pense m'approcher d'un fonctionnement "brut" mais ça ne fonctionne pas

    Pour résumer je dois modifier une application (JSignPDF), open source, qui signe les document pdf numériquement avec une clé de cryptage de tel sorte à ce que la signature soit faite automatiquement dés qu'un nouveau document arrive dans un répertoire. Le fonctionnement de base est que l'on doit renseigner "manuellement" le fichier d'entrée et sortie à l'application pour ensuite lancer celle-ci : perte de temps.

    Bref, j'ai réussi à utiliser l'API Path de JAVA : j'arrive à savoir lorsqu'il y a un nouveau fichier et récupérer son nom, chemin et indiquer à l'appli "de base" le nom/chemin des nouveaux fichiers d'entrées/sorties. Suite à la détection d'un nouveau fichier j'appelle la méthode pour signer un fichier PDF. Je pensais que ça aller fonctionner mais toujours pas.

    Voici le code de la classe que j'ai ajouter :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    public class test {
     
    	public static void main(String[] args)
    	{
    		// TODO Auto-generated method stub
    try {
     
    		BasicSignerOptions Infiletest = new BasicSignerOptions();     // On appelle la classe basicsigneroptions
    		Path chemin = Paths.get(Chemin1);    //on prend le chemin complet du fichier infile
                    Path cheminout = Paths.get(Chemin2);  // on prend le chemin complet du fichier outfile qui viens d'être signer manuellement
    // Le futur but sera de tout d'abord signer un document "manuellement" avec l'appli pour avoir un répertoire d'entrée et de sortie à utiliser
     
    		final Path dir = chemin.getParent();        // on prend le répertoire du fichier infile
                    Path dirout = cheminout.getParent();      // on prend le répertoire du fichier outfile
     
    		WatchService watcher = FileSystems.getDefault().newWatchService();
     
    		WatchKey key = dir.register(watcher,
    	    		StandardWatchEventKinds.ENTRY_CREATE);
     
     
    		for (;;) {
     
     
     
    		    try {
    		        key = watcher.take();
    		    } catch (InterruptedException x) {
    		        return;
    		    }
     
    		    for (WatchEvent<?> event: key.pollEvents()) {
    		        WatchEvent.Kind<?> kind = event.kind();
     
     
    		        WatchEvent<Path> ev = (WatchEvent<Path>)event;
    		        Path filename = ev.context();
                    String type = Files.probeContentType(filename); 
    		        try {
    		            Path child = dir.resolve(filename);
    		            if (!Files.probeContentType(child).equals("application/pdf")) {		          
    		                System.err.format("New file '%s'" +
    		                    " is not a pdf application file.%n", filename);
    		                continue;		               		              
    		           }
    		        } catch (IOException x) {
    		            System.err.println(x);
     
    		            continue;
    		        }
     
    System.out.println("Le fichier est : " + dir+ "\\" + filename ); //Le fichier est : C:\Users\avidegrain\Desktop\repertoire_1\test.pdf
    
    Path FileOut = Paths.get(dirout+ "\\" + filename);
    System.out.println("Le fichier Out est : " + FileOut); //Le fichier Out est : C:\Users\avidegrain\Desktop\repertoire_2\test.pdf
    
    Path FileIn = Paths.get(dir+ "\\" + filename);
    System.out.println("Le fichier In est : " + FileIn); //Le fichier In est : C:\Users\avidegrain\Desktop\repertoire_1\test.pdf
    
    BasicSignerOptions options = new BasicSignerOptions();
    options.setInFile(FileIn.toString()); //BasicSignerOptions.InFile=C:\Users\avidegrain\Desktop\repertoire_1\test.pdf
    options.setOutFile(FileOut.toString()); // BasicSignerOptions.OutFile= C:\Users\avidegrain\Desktop\repertoire_2\test.pdf
    SignerLogic sl = new SignerLogic(options);
    sl.signFile(); //On signe => ECHEC.
    
    //Les print me permettent de vérifier les chemins lors du lancement de l'appli
     
    		    }
     
    		    boolean valid = key.reset();
    		    if (!valid) {
    		        break;
    		    }
    		}
    } catch (IOException x) {
    	    System.err.println(x);
    	}
     
    }
    	public String FileOut;
    	public String FileIn;
    	public int eventest;                           // Ici on rend les variables public pour les utiliser dans d'autre classe
    }
    Et voici mon message d'erreur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : null
    INFO  Lecture de la clé privée
    ERROR L'application a rencontré un problème.
    java.lang.NullPointerException
    	at sun.security.provider.JavaKeyStore$JKS.convertAlias(JavaKeyStore.java:57)
    	at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:118)
    	at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:55)
    	at java.security.KeyStore.getKey(KeyStore.java:1011)
    	at net.sf.jsignpdf.utils.KeyStoreUtils.getPkInfo(KeyStoreUtils.java:428)
    	at net.sf.jsignpdf.SignerLogic.signFile(SignerLogic.java:136)
    	at net.sf.jsignpdf.test.main(test.java:141)
    INFO  Opération terminée. Echec de la signature du fichier PDF.
    Voilà, et me voilà bloquer de nouveau Pourtant j'ai l'impression de presque obtenir un fonctionnement "brut", c'est d'autant plus rageant :p

  2. #2
    Membre actif
    Homme Profil pro
    Inscrit en
    Septembre 2013
    Messages
    149
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Septembre 2013
    Messages : 149
    Par défaut
    Comme le dit le message d'erreur, tu as une NullPointerException car:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    INFO  Utiliser un alias pour la clé : null
    Il faut que dans ton code tu fasse en sorte que l'alias pour ta clé ne soit pas null.
    Pourrait-tu fournir le code de KeyStoreUtils.java et SignerLogic.java s'il te plait?

  3. #3
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Code de la classe keystore :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    package java.security;
     
    import java.io.*;
    import java.net.URI;
    import java.security.cert.Certificate;
    import java.security.cert.X509Certificate;
    import java.security.cert.CertificateException;
    import java.security.spec.AlgorithmParameterSpec;
    import java.util.*;
    import javax.crypto.SecretKey;
     
    import javax.security.auth.DestroyFailedException;
    import javax.security.auth.callback.*;
     
    /**
     * This class represents a storage facility for cryptographic
     * keys and certificates.
     *
     * <p> A {@code KeyStore} manages different types of entries.
     * Each type of entry implements the {@code KeyStore.Entry} interface.
     * Three basic {@code KeyStore.Entry} implementations are provided:
     *
     * <ul>
     * <li><b>KeyStore.PrivateKeyEntry</b>
     * <p> This type of entry holds a cryptographic {@code PrivateKey},
     * which is optionally stored in a protected format to prevent
     * unauthorized access.  It is also accompanied by a certificate chain
     * for the corresponding public key.
     *
     * <p> Private keys and certificate chains are used by a given entity for
     * self-authentication. Applications for this authentication include software
     * distribution organizations which sign JAR files as part of releasing
     * and/or licensing software.
     *
     * <li><b>KeyStore.SecretKeyEntry</b>
     * <p> This type of entry holds a cryptographic {@code SecretKey},
     * which is optionally stored in a protected format to prevent
     * unauthorized access.
     *
     * <li><b>KeyStore.TrustedCertificateEntry</b>
     * <p> This type of entry contains a single public key {@code Certificate}
     * belonging to another party. It is called a <i>trusted certificate</i>
     * because the keystore owner trusts that the public key in the certificate
     * indeed belongs to the identity identified by the <i>subject</i> (owner)
     * of the certificate.
     *
     * <p>This type of entry can be used to authenticate other parties.
     * </ul>
     *
     * <p> Each entry in a keystore is identified by an "alias" string. In the
     * case of private keys and their associated certificate chains, these strings
     * distinguish among the different ways in which the entity may authenticate
     * itself. For example, the entity may authenticate itself using different
     * certificate authorities, or using different public key algorithms.
     *
     * <p> Whether aliases are case sensitive is implementation dependent. In order
     * to avoid problems, it is recommended not to use aliases in a KeyStore that
     * only differ in case.
     *
     * <p> Whether keystores are persistent, and the mechanisms used by the
     * keystore if it is persistent, are not specified here. This allows
     * use of a variety of techniques for protecting sensitive (e.g., private or
     * secret) keys. Smart cards or other integrated cryptographic engines
     * (SafeKeyper) are one option, and simpler mechanisms such as files may also
     * be used (in a variety of formats).
     *
     * <p> Typical ways to request a KeyStore object include
     * relying on the default type and providing a specific keystore type.
     *
     * <ul>
     * <li>To rely on the default type:
     * <pre>
     *    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
     * </pre>
     * The system will return a keystore implementation for the default type.
     *
     * <li>To provide a specific keystore type:
     * <pre>
     *      KeyStore ks = KeyStore.getInstance("JKS");
     * </pre>
     * The system will return the most preferred implementation of the
     * specified keystore type available in the environment. <p>
     * </ul>
     *
     * <p> Before a keystore can be accessed, it must be
     * {@link #load(java.io.InputStream, char[]) loaded}.
     * <pre>
     *    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
     *
     *    // get user password and file input stream
     *    char[] password = getPassword();
     *
     *    try (FileInputStream fis = new FileInputStream("keyStoreName")) {
     *        ks.load(fis, password);
     *    }
     * </pre>
     *
     * To create an empty keystore using the above {@code load} method,
     * pass {@code null} as the {@code InputStream} argument.
     *
     * <p> Once the keystore has been loaded, it is possible
     * to read existing entries from the keystore, or to write new entries
     * into the keystore:
     * <pre>
     *    KeyStore.ProtectionParameter protParam =
     *        new KeyStore.PasswordProtection(password);
     *
     *    // get my private key
     *    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
     *        ks.getEntry("privateKeyAlias", protParam);
     *    PrivateKey myPrivateKey = pkEntry.getPrivateKey();
     *
     *    // save my secret key
     *    javax.crypto.SecretKey mySecretKey;
     *    KeyStore.SecretKeyEntry skEntry =
     *        new KeyStore.SecretKeyEntry(mySecretKey);
     *    ks.setEntry("secretKeyAlias", skEntry, protParam);
     *
     *    // store away the keystore
     *    try (FileOutputStream fos = new FileOutputStream("newKeyStoreName")) {
     *        ks.store(fos, password);
     *    }
     * </pre>
     *
     * Note that although the same password may be used to
     * load the keystore, to protect the private key entry,
     * to protect the secret key entry, and to store the keystore
     * (as is shown in the sample code above),
     * different passwords or other protection parameters
     * may also be used.
     *
     * <p> Every implementation of the Java platform is required to support
     * the following standard {@code KeyStore} type:
     * <ul>
     * <li>{@code PKCS12}</li>
     * </ul>
     * This type is described in the <a href=
     * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
     * KeyStore section</a> of the
     * Java Cryptography Architecture Standard Algorithm Name Documentation.
     * Consult the release documentation for your implementation to see if any
     * other types are supported.
     *
     * @author Jan Luehe
     *
     * @see java.security.PrivateKey
     * @see javax.crypto.SecretKey
     * @see java.security.cert.Certificate
     *
     * @since 1.2
     */
     
    public class KeyStore {
     
        /*
         * Constant to lookup in the Security properties file to determine
         * the default keystore type.
         * In the Security properties file, the default keystore type is given as:
         * <pre>
         * keystore.type=jks
         * </pre>
         */
        private static final String KEYSTORE_TYPE = "keystore.type";
     
        // The keystore type
        private String type;
     
        // The provider
        private Provider provider;
     
        // The provider implementation
        private KeyStoreSpi keyStoreSpi;
     
        // Has this keystore been initialized (loaded)?
        private boolean initialized = false;
     
        /**
         * A marker interface for {@code KeyStore}
         * {@link #load(KeyStore.LoadStoreParameter) load}
         * and
         * {@link #store(KeyStore.LoadStoreParameter) store}
         * parameters.
         *
         * @since 1.5
         */
        public static interface LoadStoreParameter {
            /**
             * Gets the parameter used to protect keystore data.
             *
             * @return the parameter used to protect keystore data, or null
             */
            public ProtectionParameter getProtectionParameter();
        }
     
        /**
         * A marker interface for keystore protection parameters.
         *
         * <p> The information stored in a {@code ProtectionParameter}
         * object protects the contents of a keystore.
         * For example, protection parameters may be used to check
         * the integrity of keystore data, or to protect the
         * confidentiality of sensitive keystore data
         * (such as a {@code PrivateKey}).
         *
         * @since 1.5
         */
        public static interface ProtectionParameter { }
     
        /**
         * A password-based implementation of {@code ProtectionParameter}.
         *
         * @since 1.5
         */
        public static class PasswordProtection implements
                    ProtectionParameter, javax.security.auth.Destroyable {
     
            private final char[] password;
            private final String protectionAlgorithm;
            private final AlgorithmParameterSpec protectionParameters;
            private volatile boolean destroyed = false;
     
            /**
             * Creates a password parameter.
             *
             * <p> The specified {@code password} is cloned before it is stored
             * in the new {@code PasswordProtection} object.
             *
             * @param password the password, which may be {@code null}
             */
            public PasswordProtection(char[] password) {
                this.password = (password == null) ? null : password.clone();
                this.protectionAlgorithm = null;
                this.protectionParameters = null;
            }
     
            /**
             * Creates a password parameter and specifies the protection algorithm
             * and associated parameters to use when encrypting a keystore entry.
             * <p>
             * The specified {@code password} is cloned before it is stored in the
             * new {@code PasswordProtection} object.
             *
             * @param password the password, which may be {@code null}
             * @param protectionAlgorithm the encryption algorithm name, for
             *     example, {@code PBEWithHmacSHA256AndAES_256}.
             *     See the Cipher section in the <a href=
             * "{@docRoot}/../technotes/guides/security/StandardNames.html#Cipher">
             * Java Cryptography Architecture Standard Algorithm Name
             * Documentation</a>
             *     for information about standard encryption algorithm names.
             * @param protectionParameters the encryption algorithm parameter
             *     specification, which may be {@code null}
             * @exception NullPointerException if {@code protectionAlgorithm} is
             *     {@code null}
             *
             * @since 1.8
             */
            public PasswordProtection(char[] password, String protectionAlgorithm,
                AlgorithmParameterSpec protectionParameters) {
                if (protectionAlgorithm == null) {
                    throw new NullPointerException("invalid null input");
                }
                this.password = (password == null) ? null : password.clone();
                this.protectionAlgorithm = protectionAlgorithm;
                this.protectionParameters = protectionParameters;
            }
     
            /**
             * Gets the name of the protection algorithm.
             * If none was set then the keystore provider will use its default
             * protection algorithm. The name of the default protection algorithm
             * for a given keystore type is set using the
             * {@code 'keystore.<type>.keyProtectionAlgorithm'} security property.
             * For example, the
             * {@code keystore.PKCS12.keyProtectionAlgorithm} property stores the
             * name of the default key protection algorithm used for PKCS12
             * keystores. If the security property is not set, an
             * implementation-specific algorithm will be used.
             *
             * @return the algorithm name, or {@code null} if none was set
             *
             * @since 1.8
             */
            public String getProtectionAlgorithm() {
                return protectionAlgorithm;
            }
     
            /**
             * Gets the parameters supplied for the protection algorithm.
             *
             * @return the algorithm parameter specification, or {@code  null},
             *     if none was set
             *
             * @since 1.8
             */
            public AlgorithmParameterSpec getProtectionParameters() {
                return protectionParameters;
            }
     
            /**
             * Gets the password.
             *
             * <p>Note that this method returns a reference to the password.
             * If a clone of the array is created it is the caller's
             * responsibility to zero out the password information
             * after it is no longer needed.
             *
             * @see #destroy()
             * @return the password, which may be {@code null}
             * @exception IllegalStateException if the password has
             *              been cleared (destroyed)
             */
            public synchronized char[] getPassword() {
                if (destroyed) {
                    throw new IllegalStateException("password has been cleared");
                }
                return password;
            }
     
            /**
             * Clears the password.
             *
             * @exception DestroyFailedException if this method was unable
             *      to clear the password
             */
            public synchronized void destroy() throws DestroyFailedException {
                destroyed = true;
                if (password != null) {
                    Arrays.fill(password, ' ');
                }
            }
     
            /**
             * Determines if password has been cleared.
             *
             * @return true if the password has been cleared, false otherwise
             */
            public synchronized boolean isDestroyed() {
                return destroyed;
            }
        }
     
        /**
         * A ProtectionParameter encapsulating a CallbackHandler.
         *
         * @since 1.5
         */
        public static class CallbackHandlerProtection
                implements ProtectionParameter {
     
            private final CallbackHandler handler;
     
            /**
             * Constructs a new CallbackHandlerProtection from a
             * CallbackHandler.
             *
             * @param handler the CallbackHandler
             * @exception NullPointerException if handler is null
             */
            public CallbackHandlerProtection(CallbackHandler handler) {
                if (handler == null) {
                    throw new NullPointerException("handler must not be null");
                }
                this.handler = handler;
            }
     
            /**
             * Returns the CallbackHandler.
             *
             * @return the CallbackHandler.
             */
            public CallbackHandler getCallbackHandler() {
                return handler;
            }
     
        }
     
        /**
         * A marker interface for {@code KeyStore} entry types.
         *
         * @since 1.5
         */
        public static interface Entry {
     
            /**
             * Retrieves the attributes associated with an entry.
             * <p>
             * The default implementation returns an empty {@code Set}.
             *
             * @return an unmodifiable {@code Set} of attributes, possibly empty
             *
             * @since 1.8
             */
            public default Set<Attribute> getAttributes() {
                return Collections.<Attribute>emptySet();
            }
     
            /**
             * An attribute associated with a keystore entry.
             * It comprises a name and one or more values.
             *
             * @since 1.8
             */
            public interface Attribute {
                /**
                 * Returns the attribute's name.
                 *
                 * @return the attribute name
                 */
                public String getName();
     
                /**
                 * Returns the attribute's value.
                 * Multi-valued attributes encode their values as a single string.
                 *
                 * @return the attribute value
                 */
                public String getValue();
            }
        }
     
        /**
         * A {@code KeyStore} entry that holds a {@code PrivateKey}
         * and corresponding certificate chain.
         *
         * @since 1.5
         */
        public static final class PrivateKeyEntry implements Entry {
     
            private final PrivateKey privKey;
            private final Certificate[] chain;
            private final Set<Attribute> attributes;
     
            /**
             * Constructs a {@code PrivateKeyEntry} with a
             * {@code PrivateKey} and corresponding certificate chain.
             *
             * <p> The specified {@code chain} is cloned before it is stored
             * in the new {@code PrivateKeyEntry} object.
             *
             * @param privateKey the {@code PrivateKey}
             * @param chain an array of {@code Certificate}s
             *      representing the certificate chain.
             *      The chain must be ordered and contain a
             *      {@code Certificate} at index 0
             *      corresponding to the private key.
             *
             * @exception NullPointerException if
             *      {@code privateKey} or {@code chain}
             *      is {@code null}
             * @exception IllegalArgumentException if the specified chain has a
             *      length of 0, if the specified chain does not contain
             *      {@code Certificate}s of the same type,
             *      or if the {@code PrivateKey} algorithm
             *      does not match the algorithm of the {@code PublicKey}
             *      in the end entity {@code Certificate} (at index 0)
             */
            public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain) {
                this(privateKey, chain, Collections.<Attribute>emptySet());
            }
     
            /**
             * Constructs a {@code PrivateKeyEntry} with a {@code PrivateKey} and
             * corresponding certificate chain and associated entry attributes.
             *
             * <p> The specified {@code chain} and {@code attributes} are cloned
             * before they are stored in the new {@code PrivateKeyEntry} object.
             *
             * @param privateKey the {@code PrivateKey}
             * @param chain an array of {@code Certificate}s
             *      representing the certificate chain.
             *      The chain must be ordered and contain a
             *      {@code Certificate} at index 0
             *      corresponding to the private key.
             * @param attributes the attributes
             *
             * @exception NullPointerException if {@code privateKey}, {@code chain}
             *      or {@code attributes} is {@code null}
             * @exception IllegalArgumentException if the specified chain has a
             *      length of 0, if the specified chain does not contain
             *      {@code Certificate}s of the same type,
             *      or if the {@code PrivateKey} algorithm
             *      does not match the algorithm of the {@code PublicKey}
             *      in the end entity {@code Certificate} (at index 0)
             *
             * @since 1.8
             */
            public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain,
               Set<Attribute> attributes) {
     
                if (privateKey == null || chain == null || attributes == null) {
                    throw new NullPointerException("invalid null input");
                }
                if (chain.length == 0) {
                    throw new IllegalArgumentException
                                    ("invalid zero-length input chain");
                }
     
                Certificate[] clonedChain = chain.clone();
                String certType = clonedChain[0].getType();
                for (int i = 1; i < clonedChain.length; i++) {
                    if (!certType.equals(clonedChain[i].getType())) {
                        throw new IllegalArgumentException
                                    ("chain does not contain certificates " +
                                    "of the same type");
                    }
                }
                if (!privateKey.getAlgorithm().equals
                            (clonedChain[0].getPublicKey().getAlgorithm())) {
                    throw new IllegalArgumentException
                                    ("private key algorithm does not match " +
                                    "algorithm of public key in end entity " +
                                    "certificate (at index 0)");
                }
                this.privKey = privateKey;
     
                if (clonedChain[0] instanceof X509Certificate &&
                    !(clonedChain instanceof X509Certificate[])) {
     
                    this.chain = new X509Certificate[clonedChain.length];
                    System.arraycopy(clonedChain, 0,
                                    this.chain, 0, clonedChain.length);
                } else {
                    this.chain = clonedChain;
                }
     
                this.attributes =
                    Collections.unmodifiableSet(new HashSet<>(attributes));
            }
     
            /**
             * Gets the {@code PrivateKey} from this entry.
             *
             * @return the {@code PrivateKey} from this entry
             */
            public PrivateKey getPrivateKey() {
                return privKey;
            }
     
            /**
             * Gets the {@code Certificate} chain from this entry.
             *
             * <p> The stored chain is cloned before being returned.
             *
             * @return an array of {@code Certificate}s corresponding
             *      to the certificate chain for the public key.
             *      If the certificates are of type X.509,
             *      the runtime type of the returned array is
             *      {@code X509Certificate[]}.
             */
            public Certificate[] getCertificateChain() {
                return chain.clone();
            }
     
            /**
             * Gets the end entity {@code Certificate}
             * from the certificate chain in this entry.
             *
             * @return the end entity {@code Certificate} (at index 0)
             *      from the certificate chain in this entry.
             *      If the certificate is of type X.509,
             *      the runtime type of the returned certificate is
             *      {@code X509Certificate}.
             */
            public Certificate getCertificate() {
                return chain[0];
            }
     
            /**
             * Retrieves the attributes associated with an entry.
             * <p>
             *
             * @return an unmodifiable {@code Set} of attributes, possibly empty
             *
             * @since 1.8
             */
            @Override
            public Set<Attribute> getAttributes() {
                return attributes;
            }
     
            /**
             * Returns a string representation of this PrivateKeyEntry.
             * @return a string representation of this PrivateKeyEntry.
             */
            public String toString() {
                StringBuilder sb = new StringBuilder();
                sb.append("Private key entry and certificate chain with "
                    + chain.length + " elements:\r\n");
                for (Certificate cert : chain) {
                    sb.append(cert);
                    sb.append("\r\n");
                }
                return sb.toString();
            }
     
        }
     
        /**
         * A {@code KeyStore} entry that holds a {@code SecretKey}.
         *
         * @since 1.5
         */
        public static final class SecretKeyEntry implements Entry {
     
            private final SecretKey sKey;
            private final Set<Attribute> attributes;
     
            /**
             * Constructs a {@code SecretKeyEntry} with a
             * {@code SecretKey}.
             *
             * @param secretKey the {@code SecretKey}
             *
             * @exception NullPointerException if {@code secretKey}
             *      is {@code null}
             */
            public SecretKeyEntry(SecretKey secretKey) {
                if (secretKey == null) {
                    throw new NullPointerException("invalid null input");
                }
                this.sKey = secretKey;
                this.attributes = Collections.<Attribute>emptySet();
            }
     
            /**
             * Constructs a {@code SecretKeyEntry} with a {@code SecretKey} and
             * associated entry attributes.
             *
             * <p> The specified {@code attributes} is cloned before it is stored
             * in the new {@code SecretKeyEntry} object.
             *
             * @param secretKey the {@code SecretKey}
             * @param attributes the attributes
             *
             * @exception NullPointerException if {@code secretKey} or
             *     {@code attributes} is {@code null}
             *
             * @since 1.8
             */
            public SecretKeyEntry(SecretKey secretKey, Set<Attribute> attributes) {
     
                if (secretKey == null || attributes == null) {
                    throw new NullPointerException("invalid null input");
                }
                this.sKey = secretKey;
                this.attributes =
                    Collections.unmodifiableSet(new HashSet<>(attributes));
            }
     
            /**
             * Gets the {@code SecretKey} from this entry.
             *
             * @return the {@code SecretKey} from this entry
             */
            public SecretKey getSecretKey() {
                return sKey;
            }
     
            /**
             * Retrieves the attributes associated with an entry.
             * <p>
             *
             * @return an unmodifiable {@code Set} of attributes, possibly empty
             *
             * @since 1.8
             */
            @Override
            public Set<Attribute> getAttributes() {
                return attributes;
            }
     
            /**
             * Returns a string representation of this SecretKeyEntry.
             * @return a string representation of this SecretKeyEntry.
             */
            public String toString() {
                return "Secret key entry with algorithm " + sKey.getAlgorithm();
            }
        }
     
        /**
         * A {@code KeyStore} entry that holds a trusted
         * {@code Certificate}.
         *
         * @since 1.5
         */
        public static final class TrustedCertificateEntry implements Entry {
     
            private final Certificate cert;
            private final Set<Attribute> attributes;
     
            /**
             * Constructs a {@code TrustedCertificateEntry} with a
             * trusted {@code Certificate}.
             *
             * @param trustedCert the trusted {@code Certificate}
             *
             * @exception NullPointerException if
             *      {@code trustedCert} is {@code null}
             */
            public TrustedCertificateEntry(Certificate trustedCert) {
                if (trustedCert == null) {
                    throw new NullPointerException("invalid null input");
                }
                this.cert = trustedCert;
                this.attributes = Collections.<Attribute>emptySet();
            }
     
            /**
             * Constructs a {@code TrustedCertificateEntry} with a
             * trusted {@code Certificate} and associated entry attributes.
             *
             * <p> The specified {@code attributes} is cloned before it is stored
             * in the new {@code TrustedCertificateEntry} object.
             *
             * @param trustedCert the trusted {@code Certificate}
             * @param attributes the attributes
             *
             * @exception NullPointerException if {@code trustedCert} or
             *     {@code attributes} is {@code null}
             *
             * @since 1.8
             */
            public TrustedCertificateEntry(Certificate trustedCert,
               Set<Attribute> attributes) {
                if (trustedCert == null || attributes == null) {
                    throw new NullPointerException("invalid null input");
                }
                this.cert = trustedCert;
                this.attributes =
                    Collections.unmodifiableSet(new HashSet<>(attributes));
            }
     
            /**
             * Gets the trusted {@code Certficate} from this entry.
             *
             * @return the trusted {@code Certificate} from this entry
             */
            public Certificate getTrustedCertificate() {
                return cert;
            }
     
            /**
             * Retrieves the attributes associated with an entry.
             * <p>
             *
             * @return an unmodifiable {@code Set} of attributes, possibly empty
             *
             * @since 1.8
             */
            @Override
            public Set<Attribute> getAttributes() {
                return attributes;
            }
     
            /**
             * Returns a string representation of this TrustedCertificateEntry.
             * @return a string representation of this TrustedCertificateEntry.
             */
            public String toString() {
                return "Trusted certificate entry:\r\n" + cert.toString();
            }
        }
     
        /**
         * Creates a KeyStore object of the given type, and encapsulates the given
         * provider implementation (SPI object) in it.
         *
         * @param keyStoreSpi the provider implementation.
         * @param provider the provider.
         * @param type the keystore type.
         */
        protected KeyStore(KeyStoreSpi keyStoreSpi, Provider provider, String type)
        {
            this.keyStoreSpi = keyStoreSpi;
            this.provider = provider;
            this.type = type;
        }
     
        /**
         * Returns a keystore object of the specified type.
         *
         * <p> This method traverses the list of registered security Providers,
         * starting with the most preferred Provider.
         * A new KeyStore object encapsulating the
         * KeyStoreSpi implementation from the first
         * Provider that supports the specified type is returned.
         *
         * <p> Note that the list of registered providers may be retrieved via
         * the {@link Security#getProviders() Security.getProviders()} method.
         *
         * @param type the type of keystore.
         * See the KeyStore section in the <a href=
         * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
         * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
         * for information about standard keystore types.
         *
         * @return a keystore object of the specified type.
         *
         * @exception KeyStoreException if no Provider supports a
         *          KeyStoreSpi implementation for the
         *          specified type.
         *
         * @see Provider
         */
        public static KeyStore getInstance(String type)
            throws KeyStoreException
        {
            try {
                Object[] objs = Security.getImpl(type, "KeyStore", (String)null);
                return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
            } catch (NoSuchAlgorithmException nsae) {
                throw new KeyStoreException(type + " not found", nsae);
            } catch (NoSuchProviderException nspe) {
                throw new KeyStoreException(type + " not found", nspe);
            }
        }
     
        /**
         * Returns a keystore object of the specified type.
         *
         * <p> A new KeyStore object encapsulating the
         * KeyStoreSpi implementation from the specified provider
         * is returned.  The specified provider must be registered
         * in the security provider list.
         *
         * <p> Note that the list of registered providers may be retrieved via
         * the {@link Security#getProviders() Security.getProviders()} method.
         *
         * @param type the type of keystore.
         * See the KeyStore section in the <a href=
         * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
         * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
         * for information about standard keystore types.
         *
         * @param provider the name of the provider.
         *
         * @return a keystore object of the specified type.
         *
         * @exception KeyStoreException if a KeyStoreSpi
         *          implementation for the specified type is not
         *          available from the specified provider.
         *
         * @exception NoSuchProviderException if the specified provider is not
         *          registered in the security provider list.
         *
         * @exception IllegalArgumentException if the provider name is null
         *          or empty.
         *
         * @see Provider
         */
        public static KeyStore getInstance(String type, String provider)
            throws KeyStoreException, NoSuchProviderException
        {
            if (provider == null || provider.length() == 0)
                throw new IllegalArgumentException("missing provider");
            try {
                Object[] objs = Security.getImpl(type, "KeyStore", provider);
                return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
            } catch (NoSuchAlgorithmException nsae) {
                throw new KeyStoreException(type + " not found", nsae);
            }
        }
     
        /**
         * Returns a keystore object of the specified type.
         *
         * <p> A new KeyStore object encapsulating the
         * KeyStoreSpi implementation from the specified Provider
         * object is returned.  Note that the specified Provider object
         * does not have to be registered in the provider list.
         *
         * @param type the type of keystore.
         * See the KeyStore section in the <a href=
         * "{@docRoot}/../technotes/guides/security/StandardNames.html#KeyStore">
         * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
         * for information about standard keystore types.
         *
         * @param provider the provider.
         *
         * @return a keystore object of the specified type.
         *
         * @exception KeyStoreException if KeyStoreSpi
         *          implementation for the specified type is not available
         *          from the specified Provider object.
         *
         * @exception IllegalArgumentException if the specified provider is null.
         *
         * @see Provider
         *
         * @since 1.4
         */
        public static KeyStore getInstance(String type, Provider provider)
            throws KeyStoreException
        {
            if (provider == null)
                throw new IllegalArgumentException("missing provider");
            try {
                Object[] objs = Security.getImpl(type, "KeyStore", provider);
                return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
            } catch (NoSuchAlgorithmException nsae) {
                throw new KeyStoreException(type + " not found", nsae);
            }
        }
     
        /**
         * Returns the default keystore type as specified by the
         * {@code keystore.type} security property, or the string
         * {@literal "jks"} (acronym for {@literal "Java keystore"})
         * if no such property exists.
         *
         * <p>The default keystore type can be used by applications that do not
         * want to use a hard-coded keystore type when calling one of the
         * {@code getInstance} methods, and want to provide a default keystore
         * type in case a user does not specify its own.
         *
         * <p>The default keystore type can be changed by setting the value of the
         * {@code keystore.type} security property to the desired keystore type.
         *
         * @return the default keystore type as specified by the
         * {@code keystore.type} security property, or the string {@literal "jks"}
         * if no such property exists.
         * @see java.security.Security security properties
         */
        public final static String getDefaultType() {
            String kstype;
            kstype = AccessController.doPrivileged(new PrivilegedAction<String>() {
                public String run() {
                    return Security.getProperty(KEYSTORE_TYPE);
                }
            });
            if (kstype == null) {
                kstype = "jks";
            }
            return kstype;
        }
     
        /**
         * Returns the provider of this keystore.
         *
         * @return the provider of this keystore.
         */
        public final Provider getProvider()
        {
            return this.provider;
        }
     
        /**
         * Returns the type of this keystore.
         *
         * @return the type of this keystore.
         */
        public final String getType()
        {
            return this.type;
        }
     
        /**
         * Returns the key associated with the given alias, using the given
         * password to recover it.  The key must have been associated with
         * the alias by a call to {@code setKeyEntry},
         * or by a call to {@code setEntry} with a
         * {@code PrivateKeyEntry} or {@code SecretKeyEntry}.
         *
         * @param alias the alias name
         * @param password the password for recovering the key
         *
         * @return the requested key, or null if the given alias does not exist
         * or does not identify a key-related entry.
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         * @exception NoSuchAlgorithmException if the algorithm for recovering the
         * key cannot be found
         * @exception UnrecoverableKeyException if the key cannot be recovered
         * (e.g., the given password is wrong).
         */
        public final Key getKey(String alias, char[] password)
            throws KeyStoreException, NoSuchAlgorithmException,
                UnrecoverableKeyException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetKey(alias, password);
        }
     
        /**
         * Returns the certificate chain associated with the given alias.
         * The certificate chain must have been associated with the alias
         * by a call to {@code setKeyEntry},
         * or by a call to {@code setEntry} with a
         * {@code PrivateKeyEntry}.
         *
         * @param alias the alias name
         *
         * @return the certificate chain (ordered with the user's certificate first
         * followed by zero or more certificate authorities), or null if the given alias
         * does not exist or does not contain a certificate chain
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final Certificate[] getCertificateChain(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetCertificateChain(alias);
        }
     
        /**
         * Returns the certificate associated with the given alias.
         *
         * <p> If the given alias name identifies an entry
         * created by a call to {@code setCertificateEntry},
         * or created by a call to {@code setEntry} with a
         * {@code TrustedCertificateEntry},
         * then the trusted certificate contained in that entry is returned.
         *
         * <p> If the given alias name identifies an entry
         * created by a call to {@code setKeyEntry},
         * or created by a call to {@code setEntry} with a
         * {@code PrivateKeyEntry},
         * then the first element of the certificate chain in that entry
         * is returned.
         *
         * @param alias the alias name
         *
         * @return the certificate, or null if the given alias does not exist or
         * does not contain a certificate.
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final Certificate getCertificate(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetCertificate(alias);
        }

  4. #4
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Suite de la classe keystore :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     /**
         * Returns the creation date of the entry identified by the given alias.
         *
         * @param alias the alias name
         *
         * @return the creation date of this entry, or null if the given alias does
         * not exist
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final Date getCreationDate(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetCreationDate(alias);
        }
     
        /**
         * Assigns the given key to the given alias, protecting it with the given
         * password.
         *
         * <p>If the given key is of type {@code java.security.PrivateKey},
         * it must be accompanied by a certificate chain certifying the
         * corresponding public key.
         *
         * <p>If the given alias already exists, the keystore information
         * associated with it is overridden by the given key (and possibly
         * certificate chain).
         *
         * @param alias the alias name
         * @param key the key to be associated with the alias
         * @param password the password to protect the key
         * @param chain the certificate chain for the corresponding public
         * key (only required if the given key is of type
         * {@code java.security.PrivateKey}).
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded), the given key cannot be protected, or this operation fails
         * for some other reason
         */
        public final void setKeyEntry(String alias, Key key, char[] password,
                                      Certificate[] chain)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            if ((key instanceof PrivateKey) &&
                (chain == null || chain.length == 0)) {
                throw new IllegalArgumentException("Private key must be "
                                                   + "accompanied by certificate "
                                                   + "chain");
            }
            keyStoreSpi.engineSetKeyEntry(alias, key, password, chain);
        }
     
        /**
         * Assigns the given key (that has already been protected) to the given
         * alias.
         *
         * <p>If the protected key is of type
         * {@code java.security.PrivateKey}, it must be accompanied by a
         * certificate chain certifying the corresponding public key. If the
         * underlying keystore implementation is of type {@code jks},
         * {@code key} must be encoded as an
         * {@code EncryptedPrivateKeyInfo} as defined in the PKCS #8 standard.
         *
         * <p>If the given alias already exists, the keystore information
         * associated with it is overridden by the given key (and possibly
         * certificate chain).
         *
         * @param alias the alias name
         * @param key the key (in protected format) to be associated with the alias
         * @param chain the certificate chain for the corresponding public
         *          key (only useful if the protected key is of type
         *          {@code java.security.PrivateKey}).
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded), or if this operation fails for some other reason.
         */
        public final void setKeyEntry(String alias, byte[] key,
                                      Certificate[] chain)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineSetKeyEntry(alias, key, chain);
        }
     
        /**
         * Assigns the given trusted certificate to the given alias.
         *
         * <p> If the given alias identifies an existing entry
         * created by a call to {@code setCertificateEntry},
         * or created by a call to {@code setEntry} with a
         * {@code TrustedCertificateEntry},
         * the trusted certificate in the existing entry
         * is overridden by the given certificate.
         *
         * @param alias the alias name
         * @param cert the certificate
         *
         * @exception KeyStoreException if the keystore has not been initialized,
         * or the given alias already exists and does not identify an
         * entry containing a trusted certificate,
         * or this operation fails for some other reason.
         */
        public final void setCertificateEntry(String alias, Certificate cert)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineSetCertificateEntry(alias, cert);
        }
     
        /**
         * Deletes the entry identified by the given alias from this keystore.
         *
         * @param alias the alias name
         *
         * @exception KeyStoreException if the keystore has not been initialized,
         * or if the entry cannot be removed.
         */
        public final void deleteEntry(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineDeleteEntry(alias);
        }
     
        /**
         * Lists all the alias names of this keystore.
         *
         * @return enumeration of the alias names
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final Enumeration<String> aliases()
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineAliases();
        }
     
        /**
         * Checks if the given alias exists in this keystore.
         *
         * @param alias the alias name
         *
         * @return true if the alias exists, false otherwise
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final boolean containsAlias(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineContainsAlias(alias);
        }
     
        /**
         * Retrieves the number of entries in this keystore.
         *
         * @return the number of entries in this keystore
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final int size()
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineSize();
        }
     
        /**
         * Returns true if the entry identified by the given alias
         * was created by a call to {@code setKeyEntry},
         * or created by a call to {@code setEntry} with a
         * {@code PrivateKeyEntry} or a {@code SecretKeyEntry}.
         *
         * @param alias the alias for the keystore entry to be checked
         *
         * @return true if the entry identified by the given alias is a
         * key-related entry, false otherwise.
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final boolean isKeyEntry(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineIsKeyEntry(alias);
        }
     
        /**
         * Returns true if the entry identified by the given alias
         * was created by a call to {@code setCertificateEntry},
         * or created by a call to {@code setEntry} with a
         * {@code TrustedCertificateEntry}.
         *
         * @param alias the alias for the keystore entry to be checked
         *
         * @return true if the entry identified by the given alias contains a
         * trusted certificate, false otherwise.
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final boolean isCertificateEntry(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineIsCertificateEntry(alias);
        }
     
        /**
         * Returns the (alias) name of the first keystore entry whose certificate
         * matches the given certificate.
         *
         * <p> This method attempts to match the given certificate with each
         * keystore entry. If the entry being considered was
         * created by a call to {@code setCertificateEntry},
         * or created by a call to {@code setEntry} with a
         * {@code TrustedCertificateEntry},
         * then the given certificate is compared to that entry's certificate.
         *
         * <p> If the entry being considered was
         * created by a call to {@code setKeyEntry},
         * or created by a call to {@code setEntry} with a
         * {@code PrivateKeyEntry},
         * then the given certificate is compared to the first
         * element of that entry's certificate chain.
         *
         * @param cert the certificate to match with.
         *
         * @return the alias name of the first entry with a matching certificate,
         * or null if no such entry exists in this keystore.
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         */
        public final String getCertificateAlias(Certificate cert)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetCertificateAlias(cert);
        }
     
        /**
         * Stores this keystore to the given output stream, and protects its
         * integrity with the given password.
         *
         * @param stream the output stream to which this keystore is written.
         * @param password the password to generate the keystore integrity check
         *
         * @exception KeyStoreException if the keystore has not been initialized
         * (loaded).
         * @exception IOException if there was an I/O problem with data
         * @exception NoSuchAlgorithmException if the appropriate data integrity
         * algorithm could not be found
         * @exception CertificateException if any of the certificates included in
         * the keystore data could not be stored
         */
        public final void store(OutputStream stream, char[] password)
            throws KeyStoreException, IOException, NoSuchAlgorithmException,
                CertificateException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineStore(stream, password);
        }
     
        /**
         * Stores this keystore using the given {@code LoadStoreParameter}.
         *
         * @param param the {@code LoadStoreParameter}
         *          that specifies how to store the keystore,
         *          which may be {@code null}
         *
         * @exception IllegalArgumentException if the given
         *          {@code LoadStoreParameter}
         *          input is not recognized
         * @exception KeyStoreException if the keystore has not been initialized
         *          (loaded)
         * @exception IOException if there was an I/O problem with data
         * @exception NoSuchAlgorithmException if the appropriate data integrity
         *          algorithm could not be found
         * @exception CertificateException if any of the certificates included in
         *          the keystore data could not be stored
         *
         * @since 1.5
         */
        public final void store(LoadStoreParameter param)
                    throws KeyStoreException, IOException,
                    NoSuchAlgorithmException, CertificateException {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineStore(param);
        }
     
        /**
         * Loads this KeyStore from the given input stream.
         *
         * <p>A password may be given to unlock the keystore
         * (e.g. the keystore resides on a hardware token device),
         * or to check the integrity of the keystore data.
         * If a password is not given for integrity checking,
         * then integrity checking is not performed.
         *
         * <p>In order to create an empty keystore, or if the keystore cannot
         * be initialized from a stream, pass {@code null}
         * as the {@code stream} argument.
         *
         * <p> Note that if this keystore has already been loaded, it is
         * reinitialized and loaded again from the given input stream.
         *
         * @param stream the input stream from which the keystore is loaded,
         * or {@code null}
         * @param password the password used to check the integrity of
         * the keystore, the password used to unlock the keystore,
         * or {@code null}
         *
         * @exception IOException if there is an I/O or format problem with the
         * keystore data, if a password is required but not given,
         * or if the given password was incorrect. If the error is due to a
         * wrong password, the {@link Throwable#getCause cause} of the
         * {@code IOException} should be an
         * {@code UnrecoverableKeyException}
         * @exception NoSuchAlgorithmException if the algorithm used to check
         * the integrity of the keystore cannot be found
         * @exception CertificateException if any of the certificates in the
         * keystore could not be loaded
         */
        public final void load(InputStream stream, char[] password)
            throws IOException, NoSuchAlgorithmException, CertificateException
        {
            keyStoreSpi.engineLoad(stream, password);
            initialized = true;
        }
     
        /**
         * Loads this keystore using the given {@code LoadStoreParameter}.
         *
         * <p> Note that if this KeyStore has already been loaded, it is
         * reinitialized and loaded again from the given parameter.
         *
         * @param param the {@code LoadStoreParameter}
         *          that specifies how to load the keystore,
         *          which may be {@code null}
         *
         * @exception IllegalArgumentException if the given
         *          {@code LoadStoreParameter}
         *          input is not recognized
         * @exception IOException if there is an I/O or format problem with the
         *          keystore data. If the error is due to an incorrect
         *         {@code ProtectionParameter} (e.g. wrong password)
         *         the {@link Throwable#getCause cause} of the
         *         {@code IOException} should be an
         *         {@code UnrecoverableKeyException}
         * @exception NoSuchAlgorithmException if the algorithm used to check
         *          the integrity of the keystore cannot be found
         * @exception CertificateException if any of the certificates in the
         *          keystore could not be loaded
         *
         * @since 1.5
         */
        public final void load(LoadStoreParameter param)
                    throws IOException, NoSuchAlgorithmException,
                    CertificateException {
     
            keyStoreSpi.engineLoad(param);
            initialized = true;
        }
     
        /**
         * Gets a keystore {@code Entry} for the specified alias
         * with the specified protection parameter.
         *
         * @param alias get the keystore {@code Entry} for this alias
         * @param protParam the {@code ProtectionParameter}
         *          used to protect the {@code Entry},
         *          which may be {@code null}
         *
         * @return the keystore {@code Entry} for the specified alias,
         *          or {@code null} if there is no such entry
         *
         * @exception NullPointerException if
         *          {@code alias} is {@code null}
         * @exception NoSuchAlgorithmException if the algorithm for recovering the
         *          entry cannot be found
         * @exception UnrecoverableEntryException if the specified
         *          {@code protParam} were insufficient or invalid
         * @exception UnrecoverableKeyException if the entry is a
         *          {@code PrivateKeyEntry} or {@code SecretKeyEntry}
         *          and the specified {@code protParam} does not contain
         *          the information needed to recover the key (e.g. wrong password)
         * @exception KeyStoreException if the keystore has not been initialized
         *          (loaded).
         * @see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
         *
         * @since 1.5
         */
        public final Entry getEntry(String alias, ProtectionParameter protParam)
                    throws NoSuchAlgorithmException, UnrecoverableEntryException,
                    KeyStoreException {
     
            if (alias == null) {
                throw new NullPointerException("invalid null input");
            }
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetEntry(alias, protParam);
        }
     
        /**
         * Saves a keystore {@code Entry} under the specified alias.
         * The protection parameter is used to protect the
         * {@code Entry}.
         *
         * <p> If an entry already exists for the specified alias,
         * it is overridden.
         *
         * @param alias save the keystore {@code Entry} under this alias
         * @param entry the {@code Entry} to save
         * @param protParam the {@code ProtectionParameter}
         *          used to protect the {@code Entry},
         *          which may be {@code null}
         *
         * @exception NullPointerException if
         *          {@code alias} or {@code entry}
         *          is {@code null}
         * @exception KeyStoreException if the keystore has not been initialized
         *          (loaded), or if this operation fails for some other reason
         *
         * @see #getEntry(String, KeyStore.ProtectionParameter)
         *
         * @since 1.5
         */
        public final void setEntry(String alias, Entry entry,
                            ProtectionParameter protParam)
                    throws KeyStoreException {
            if (alias == null || entry == null) {
                throw new NullPointerException("invalid null input");
            }
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            keyStoreSpi.engineSetEntry(alias, entry, protParam);
        }
     
        /**
         * Determines if the keystore {@code Entry} for the specified
         * {@code alias} is an instance or subclass of the specified
         * {@code entryClass}.
         *
         * @param alias the alias name
         * @param entryClass the entry class
         *
         * @return true if the keystore {@code Entry} for the specified
         *          {@code alias} is an instance or subclass of the
         *          specified {@code entryClass}, false otherwise
         *
         * @exception NullPointerException if
         *          {@code alias} or {@code entryClass}
         *          is {@code null}
         * @exception KeyStoreException if the keystore has not been
         *          initialized (loaded)
         *
         * @since 1.5
         */
        public final boolean
            entryInstanceOf(String alias,
                            Class<? extends KeyStore.Entry> entryClass)
            throws KeyStoreException
        {
     
            if (alias == null || entryClass == null) {
                throw new NullPointerException("invalid null input");
            }
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineEntryInstanceOf(alias, entryClass);
        }
     
        /**
         * A description of a to-be-instantiated KeyStore object.
         *
         * <p>An instance of this class encapsulates the information needed to
         * instantiate and initialize a KeyStore object. That process is
         * triggered when the {@linkplain #getKeyStore} method is called.
         *
         * <p>This makes it possible to decouple configuration from KeyStore
         * object creation and e.g. delay a password prompt until it is
         * needed.
         *
         * @see KeyStore
         * @see javax.net.ssl.KeyStoreBuilderParameters
         * @since 1.5
         */
        public static abstract class Builder {
     
            // maximum times to try the callbackhandler if the password is wrong
            static final int MAX_CALLBACK_TRIES = 3;
     
            /**
             * Construct a new Builder.
             */
            protected Builder() {
                // empty
            }
     
            /**
             * Returns the KeyStore described by this object.
             *
             * @return the {@code KeyStore} described by this object
             * @exception KeyStoreException if an error occurred during the
             *   operation, for example if the KeyStore could not be
             *   instantiated or loaded
             */
            public abstract KeyStore getKeyStore() throws KeyStoreException;
     
            /**
             * Returns the ProtectionParameters that should be used to obtain
             * the {@link KeyStore.Entry Entry} with the given alias.
             * The {@code getKeyStore} method must be invoked before this
             * method may be called.
             *
             * @return the ProtectionParameters that should be used to obtain
             *   the {@link KeyStore.Entry Entry} with the given alias.
             * @param alias the alias of the KeyStore entry
             * @throws NullPointerException if alias is null
             * @throws KeyStoreException if an error occurred during the
             *   operation
             * @throws IllegalStateException if the getKeyStore method has
             *   not been invoked prior to calling this method
             */
            public abstract ProtectionParameter getProtectionParameter(String alias)
                throws KeyStoreException;
     
            /**
             * Returns a new Builder that encapsulates the given KeyStore.
             * The {@linkplain #getKeyStore} method of the returned object
             * will return {@code keyStore}, the {@linkplain
             * #getProtectionParameter getProtectionParameter()} method will
             * return {@code protectionParameters}.
             *
             * <p> This is useful if an existing KeyStore object needs to be
             * used with Builder-based APIs.
             *
             * @return a new Builder object
             * @param keyStore the KeyStore to be encapsulated
             * @param protectionParameter the ProtectionParameter used to
             *   protect the KeyStore entries
             * @throws NullPointerException if keyStore or
             *   protectionParameters is null
             * @throws IllegalArgumentException if the keyStore has not been
             *   initialized
             */
            public static Builder newInstance(final KeyStore keyStore,
                    final ProtectionParameter protectionParameter) {
                if ((keyStore == null) || (protectionParameter == null)) {
                    throw new NullPointerException();
                }
                if (keyStore.initialized == false) {
                    throw new IllegalArgumentException("KeyStore not initialized");
                }
                return new Builder() {
                    private volatile boolean getCalled;
     
                    public KeyStore getKeyStore() {
                        getCalled = true;
                        return keyStore;
                    }
     
                    public ProtectionParameter getProtectionParameter(String alias)
                    {
                        if (alias == null) {
                            throw new NullPointerException();
                        }
                        if (getCalled == false) {
                            throw new IllegalStateException
                                ("getKeyStore() must be called first");
                        }
                        return protectionParameter;
                    }
                };
            }
     
            /**
             * Returns a new Builder object.
             *
             * <p>The first call to the {@link #getKeyStore} method on the returned
             * builder will create a KeyStore of type {@code type} and call
             * its {@link KeyStore#load load()} method.
             * The {@code inputStream} argument is constructed from
             * {@code file}.
             * If {@code protection} is a
             * {@code PasswordProtection}, the password is obtained by
             * calling the {@code getPassword} method.
             * Otherwise, if {@code protection} is a
             * {@code CallbackHandlerProtection}, the password is obtained
             * by invoking the CallbackHandler.
             *
             * <p>Subsequent calls to {@link #getKeyStore} return the same object
             * as the initial call. If the initial call to failed with a
             * KeyStoreException, subsequent calls also throw a
             * KeyStoreException.
             *
             * <p>The KeyStore is instantiated from {@code provider} if
             * non-null. Otherwise, all installed providers are searched.
             *
             * <p>Calls to {@link #getProtectionParameter getProtectionParameter()}
             * will return a {@link KeyStore.PasswordProtection PasswordProtection}
             * object encapsulating the password that was used to invoke the
             * {@code load} method.
             *
             * <p><em>Note</em> that the {@link #getKeyStore} method is executed
             * within the {@link AccessControlContext} of the code invoking this
             * method.
             *
             * @return a new Builder object
             * @param type the type of KeyStore to be constructed
             * @param provider the provider from which the KeyStore is to
             *   be instantiated (or null)
             * @param file the File that contains the KeyStore data
             * @param protection the ProtectionParameter securing the KeyStore data
             * @throws NullPointerException if type, file or protection is null
             * @throws IllegalArgumentException if protection is not an instance
             *   of either PasswordProtection or CallbackHandlerProtection; or
             *   if file does not exist or does not refer to a normal file
             */
            public static Builder newInstance(String type, Provider provider,
                    File file, ProtectionParameter protection) {
                if ((type == null) || (file == null) || (protection == null)) {
                    throw new NullPointerException();
                }
                if ((protection instanceof PasswordProtection == false) &&
                    (protection instanceof CallbackHandlerProtection == false)) {
                    throw new IllegalArgumentException
                    ("Protection must be PasswordProtection or " +
                     "CallbackHandlerProtection");
                }
                if (file.isFile() == false) {
                    throw new IllegalArgumentException
                        ("File does not exist or it does not refer " +
                         "to a normal file: " + file);
                }
                return new FileBuilder(type, provider, file, protection,
                    AccessController.getContext());
            }
     
            private static final class FileBuilder extends Builder {
     
                private final String type;
                private final Provider provider;
                private final File file;
                private ProtectionParameter protection;
                private ProtectionParameter keyProtection;
                private final AccessControlContext context;
     
                private KeyStore keyStore;
     
                private Throwable oldException;
     
                FileBuilder(String type, Provider provider, File file,
                        ProtectionParameter protection,
                        AccessControlContext context) {
                    this.type = type;
                    this.provider = provider;
                    this.file = file;
                    this.protection = protection;
                    this.context = context;
                }
     
                public synchronized KeyStore getKeyStore() throws KeyStoreException
                {
                    if (keyStore != null) {
                        return keyStore;
                    }
                    if (oldException != null) {
                        throw new KeyStoreException
                            ("Previous KeyStore instantiation failed",
                             oldException);
                    }
                    PrivilegedExceptionAction<KeyStore> action =
                            new PrivilegedExceptionAction<KeyStore>() {
                        public KeyStore run() throws Exception {
                            if (protection instanceof CallbackHandlerProtection == false) {
                                return run0();
                            }
                            // when using a CallbackHandler,
                            // reprompt if the password is wrong
                            int tries = 0;
                            while (true) {
                                tries++;
                                try {
                                    return run0();
                                } catch (IOException e) {
                                    if ((tries < MAX_CALLBACK_TRIES)
                                            && (e.getCause() instanceof UnrecoverableKeyException)) {
                                        continue;
                                    }
                                    throw e;
                                }
                            }
                        }
                        public KeyStore run0() throws Exception {
                            KeyStore ks;
                            if (provider == null) {
                                ks = KeyStore.getInstance(type);
                            } else {
                                ks = KeyStore.getInstance(type, provider);
                            }
                            InputStream in = null;
                            char[] password = null;
                            try {
                                in = new FileInputStream(file);
                                if (protection instanceof PasswordProtection) {
                                    password =
                                    ((PasswordProtection)protection).getPassword();
                                    keyProtection = protection;
                                } else {
                                    CallbackHandler handler =
                                        ((CallbackHandlerProtection)protection)
                                        .getCallbackHandler();
                                    PasswordCallback callback = new PasswordCallback
                                        ("Password for keystore " + file.getName(),
                                        false);
                                    handler.handle(new Callback[] {callback});
                                    password = callback.getPassword();
                                    if (password == null) {
                                        throw new KeyStoreException("No password" +
                                                                    " provided");
                                    }
                                    callback.clearPassword();
                                    keyProtection = new PasswordProtection(password);
                                }
                                ks.load(in, password);
                                return ks;
                            } finally {
                                if (in != null) {
                                    in.close();
                                }
                            }
                        }
                    };
                    try {
                        keyStore = AccessController.doPrivileged(action, context);
                        return keyStore;
                    } catch (PrivilegedActionException e) {
                        oldException = e.getCause();
                        throw new KeyStoreException
                            ("KeyStore instantiation failed", oldException);
                    }
                }
     
                public synchronized ProtectionParameter
                            getProtectionParameter(String alias) {
                    if (alias == null) {
                        throw new NullPointerException();
                    }
                    if (keyStore == null) {
                        throw new IllegalStateException
                            ("getKeyStore() must be called first");
                    }
                    return keyProtection;
                }
            }
     
            /**
             * Returns a new Builder object.
             *
             * <p>Each call to the {@link #getKeyStore} method on the returned
             * builder will return a new KeyStore object of type {@code type}.
             * Its {@link KeyStore#load(KeyStore.LoadStoreParameter) load()}
             * method is invoked using a
             * {@code LoadStoreParameter} that encapsulates
             * {@code protection}.
             *
             * <p>The KeyStore is instantiated from {@code provider} if
             * non-null. Otherwise, all installed providers are searched.
             *
             * <p>Calls to {@link #getProtectionParameter getProtectionParameter()}
             * will return {@code protection}.
             *
             * <p><em>Note</em> that the {@link #getKeyStore} method is executed
             * within the {@link AccessControlContext} of the code invoking this
             * method.
             *
             * @return a new Builder object
             * @param type the type of KeyStore to be constructed
             * @param provider the provider from which the KeyStore is to
             *   be instantiated (or null)
             * @param protection the ProtectionParameter securing the Keystore
             * @throws NullPointerException if type or protection is null
             */
            public static Builder newInstance(final String type,
                    final Provider provider, final ProtectionParameter protection) {
                if ((type == null) || (protection == null)) {
                    throw new NullPointerException();
                }
                final AccessControlContext context = AccessController.getContext();
                return new Builder() {
                    private volatile boolean getCalled;
                    private IOException oldException;
     
                    private final PrivilegedExceptionAction<KeyStore> action
                            = new PrivilegedExceptionAction<KeyStore>() {
     
                        public KeyStore run() throws Exception {
                            KeyStore ks;
                            if (provider == null) {
                                ks = KeyStore.getInstance(type);
                            } else {
                                ks = KeyStore.getInstance(type, provider);
                            }
                            LoadStoreParameter param = new SimpleLoadStoreParameter(protection);
                            if (protection instanceof CallbackHandlerProtection == false) {
                                ks.load(param);
                            } else {
                                // when using a CallbackHandler,
                                // reprompt if the password is wrong
                                int tries = 0;
                                while (true) {
                                    tries++;
                                    try {
                                        ks.load(param);
                                        break;
                                    } catch (IOException e) {
                                        if (e.getCause() instanceof UnrecoverableKeyException) {
                                            if (tries < MAX_CALLBACK_TRIES) {
                                                continue;
                                            } else {
                                                oldException = e;
                                            }
                                        }
                                        throw e;
                                    }
                                }
                            }
                            getCalled = true;
                            return ks;
                        }
                    };
     
                    public synchronized KeyStore getKeyStore()
                            throws KeyStoreException {
                        if (oldException != null) {
                            throw new KeyStoreException
                                ("Previous KeyStore instantiation failed",
                                 oldException);
                        }
                        try {
                            return AccessController.doPrivileged(action, context);
                        } catch (PrivilegedActionException e) {
                            Throwable cause = e.getCause();
                            throw new KeyStoreException
                                ("KeyStore instantiation failed", cause);
                        }
                    }
     
                    public ProtectionParameter getProtectionParameter(String alias)
                    {
                        if (alias == null) {
                            throw new NullPointerException();
                        }
                        if (getCalled == false) {
                            throw new IllegalStateException
                                ("getKeyStore() must be called first");
                        }
                        return protection;
                    }
                };
            }
     
        }
     
        static class SimpleLoadStoreParameter implements LoadStoreParameter {
     
            private final ProtectionParameter protection;
     
            SimpleLoadStoreParameter(ProtectionParameter protection) {
                this.protection = protection;
            }
     
            public ProtectionParameter getProtectionParameter() {
                return protection;
            }
        }
     
    }

  5. #5
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Et enfin code de la classe SignerLogic :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package net.sf.jsignpdf;
     
    import static net.sf.jsignpdf.Constants.*;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.Proxy;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.security.MessageDigest;
    import java.security.PrivateKey;
    import java.security.cert.Certificate;
    import java.security.cert.X509Certificate;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
     
    import net.sf.jsignpdf.crl.CRLInfo;
    import net.sf.jsignpdf.ssl.SSLInitializer;
    import net.sf.jsignpdf.types.HashAlgorithm;
    import net.sf.jsignpdf.types.PDFEncryption;
    import net.sf.jsignpdf.types.RenderMode;
    import net.sf.jsignpdf.types.ServerAuthentication;
    import net.sf.jsignpdf.utils.FontUtils;
    import net.sf.jsignpdf.utils.KeyStoreUtils;
     
    import org.apache.commons.lang3.ArrayUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.commons.lang3.text.StrSubstitutor;
    import org.apache.log4j.Logger;
     
    import com.lowagie.text.Font;
    import com.lowagie.text.Image;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.AcroFields;
    import com.lowagie.text.pdf.OcspClientBouncyCastle;
    import com.lowagie.text.pdf.PdfDate;
    import com.lowagie.text.pdf.PdfDictionary;
    import com.lowagie.text.pdf.PdfName;
    import com.lowagie.text.pdf.PdfPKCS7;
    import com.lowagie.text.pdf.PdfReader;
    import com.lowagie.text.pdf.PdfSignature;
    import com.lowagie.text.pdf.PdfSignatureAppearance;
    import com.lowagie.text.pdf.PdfStamper;
    import com.lowagie.text.pdf.PdfString;
    import com.lowagie.text.pdf.PdfWriter;
    import com.lowagie.text.pdf.TSAClientBouncyCastle;
     
    /**
     * Main logic of signer application. It uses iText to create signature in PDF.
     * 
     * @author Josef Cacek
     */
    public class SignerLogic implements Runnable {
     
    	private final static Logger LOGGER = Logger.getLogger(SignerLogic.class);
     
    	private final BasicSignerOptions options;
     
    	/**
             * Constructor with all necessary parameters.
             * 
             * @param anOptions
             *            options of signer
             */
    	public SignerLogic(final BasicSignerOptions anOptions) {
    		if (anOptions == null) {
    			throw new NullPointerException("Options has to be filled.");
    		}
    		options = anOptions;
    	}
     
    	/*
    	 * (non-Javadoc)
    	 * 
    	 * @see java.lang.Runnable#run()
    	 */
    	public void run() {
    		signFile();
    	}
     
    	/**
             * Signs a single file.
             * 
             * @return true when signing is finished succesfully, false otherwise
             */
    	public boolean signFile() {
     
     
    		final String outFile = options.getOutFileX();
     
     
    		if (!validateInOutFiles(options.getInFile(), outFile)) {
    			LOGGER.info(RES.get("console.skippingSigning"));
    			return false;
    		}
     
    		boolean finished = false;
    		Throwable tmpException = null;
    		FileOutputStream fout = null;
    		try {
    			SSLInitializer.init(options);
     
    			final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options);
    			final PrivateKey key = pkInfo.getKey();
    			final Certificate[] chain = pkInfo.getChain();
    			if (ArrayUtils.isEmpty(chain)) {
    				// the certificate was not found
    				LOGGER.info(RES.get("console.certificateChainEmpty"));
    				return false;
    			}
    			LOGGER.info(RES.get("console.createPdfReader", options.getInFile()));
    			PdfReader reader;
    			try {
    				reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
    			} catch (Exception e) {
    				try {
    					reader = new PdfReader(options.getInFile(), new byte[0]);
    				} catch (Exception e2) {
    					// try to read without password
    					reader = new PdfReader(options.getInFile());
    				}
    			}
     
    			LOGGER.info(RES.get("console.createOutPdf", outFile));
    			fout = new FileOutputStream(outFile);
     
    			final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX();
     
    			LOGGER.info(RES.get("console.createSignature"));
    			char tmpPdfVersion = '\0'; // default version - the same as input
    			if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) {
    				// this covers also problems with visible signatures (embedded
    				// fonts) in PDF 1.2, because the minimal version
    				// for hash algorithms is 1.3 (for SHA1)
    				if (options.isAppendX()) {
    					// if we are in append mode and version should be updated
    					// then return false (not possible)
    					LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode"));
    					return false;
    				}
    				tmpPdfVersion = hashAlgorithm.getPdfVersion();
    				LOGGER.info(RES.get("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()),
    						String.valueOf(tmpPdfVersion) }));
    			}
     
    			final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX());
    			if (!options.isAppendX()) {
    				// we are not in append mode, let's remove existing signatures
    				// (otherwise we're getting to troubles)
    				final AcroFields acroFields = stp.getAcroFields();
    				@SuppressWarnings("unchecked")
    				final List<String> sigNames = acroFields.getSignatureNames();
    				for (String sigName : sigNames) {
    					acroFields.removeField(sigName);
    				}
    			}
    			if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) {
    				LOGGER.info(RES.get("console.setEncryption"));
    				final int tmpRight = options.getRightPrinting().getRight()
    						| (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0)
    						| (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0)
    						| (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0)
    						| (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0)
    						| (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0)
    						| (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0);
    				switch (options.getPdfEncryption()) {
    				case PASSWORD:
    					stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight);
    					break;
    				case CERTIFICATE:
    					final X509Certificate encCert = KeyStoreUtils.loadCertificate(options.getPdfEncryptionCertFile());
    					if (encCert == null) {
    						LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile",
    								StringUtils.defaultString(options.getPdfEncryptionCertFile())));
    						return false;
    					}
    					if (!KeyStoreUtils.isEncryptionSupported(encCert)) {
    						LOGGER.error(RES
    								.get("console.pdfEncError.cantUseCertificate", encCert.getSubjectDN().getName()));
    						return false;
    					}
    					stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight },
    							PdfWriter.ENCRYPTION_AES_128);
    					break;
    				default:
    					LOGGER.error(RES.get("console.unsupportedEncryptionType"));
    					return false;
    				}
    			}
     
    			final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    			sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
    			final String reason = options.getReason();
    			if (StringUtils.isNotEmpty(reason)) {
    				LOGGER.info(RES.get("console.setReason", reason));
    				sap.setReason(reason);
    			}
    			final String location = options.getLocation();
    			if (StringUtils.isNotEmpty(location)) {
    				LOGGER.info(RES.get("console.setLocation", location));
    				sap.setLocation(location);
    			}
    			final String contact = options.getContact();
    			if (StringUtils.isNotEmpty(contact)) {
    				LOGGER.info(RES.get("console.setContact", contact));
    				sap.setContact(contact);
    			}
    			LOGGER.info(RES.get("console.setCertificationLevel"));
    			sap.setCertificationLevel(options.getCertLevelX().getLevel());
     
    			if (options.isVisible()) {
    				// visible signature is enabled
    				LOGGER.info(RES.get("console.configureVisible"));
    				LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers())));
    				sap.setAcro6Layers(options.isAcro6Layers());
     
    				final String tmpImgPath = options.getImgPath();
    				if (tmpImgPath != null) {
    					LOGGER.info(RES.get("console.createImage", tmpImgPath));
    					final Image img = Image.getInstance(tmpImgPath);
    					LOGGER.info(RES.get("console.setSignatureGraphic"));
    					sap.setSignatureGraphic(img);
    				}
    				final String tmpBgImgPath = options.getBgImgPath();
    				if (tmpBgImgPath != null) {
    					LOGGER.info(RES.get("console.createImage", tmpBgImgPath));
    					final Image img = Image.getInstance(tmpBgImgPath);
    					LOGGER.info(RES.get("console.setImage"));
    					sap.setImage(img);
    				}
    				LOGGER.info(RES.get("console.setImageScale"));
    				sap.setImageScale(options.getBgImgScale());
    				LOGGER.info(RES.get("console.setL2Text"));
    				final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN");
    				final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z").format(sap.getSignDate()
    						.getTime());
    				if (options.getL2Text() != null) {
    					final Map<String, String> replacements = new HashMap<String, String>();
    					replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer));
    					replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp);
    					replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location));
    					replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason));
    					replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact));
    					final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements);
    					sap.setLayer2Text(l2text);
    				} else {
    					final StringBuilder buf = new StringBuilder();
    					buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n');
    					buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp);
    					if (StringUtils.isNotEmpty(reason))
    						buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason);
    					if (StringUtils.isNotEmpty(location))
    						buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location);
    					sap.setLayer2Text(buf.toString());
    				}
    				if (FontUtils.getL2BaseFont() != null) {
    					sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize()));
    				}
    				LOGGER.info(RES.get("console.setL4Text"));
    				sap.setLayer4Text(options.getL4Text());
    				LOGGER.info(RES.get("console.setRender"));
    				RenderMode renderMode = options.getRenderMode();
    				if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) {
    					LOGGER.warn("Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY.");
    					LOGGER.info(RES.get("console.renderModeFallback"));
    					renderMode = RenderMode.DESCRIPTION_ONLY;
    				}
    				sap.setRender(renderMode.getRender());
    				LOGGER.info(RES.get("console.setVisibleSignature"));
    				sap.setVisibleSignature(
    						new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options.getPositionURX(),
    								options.getPositionURY()), options.getPage(), null);
    			}
     
    			LOGGER.info(RES.get("console.processing"));
    			final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    			if (!StringUtils.isEmpty(reason)) {
    				dic.setReason(sap.getReason());
    			}
    			if (!StringUtils.isEmpty(location)) {
    				dic.setLocation(sap.getLocation());
    			}
    			if (!StringUtils.isEmpty(contact)) {
    				dic.setContact(sap.getContact());
    			}
    			dic.setDate(new PdfDate(sap.getSignDate()));
    			sap.setCryptoDictionary(dic);
     
    			final Proxy tmpProxy = options.createProxy();
     
    			final CRLInfo crlInfo = new CRLInfo(options, chain);
     
    			// CRLs are stored twice in PDF c.f.
    			// PdfPKCS7.getAuthenticatedAttributeBytes
    			final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount());
    			final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    			exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    			sap.preClose(exc);
     
    			PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false);
    			InputStream data = sap.getRangeStream();
    			final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName());
    			byte buf[] = new byte[8192];
    			int n;
    			while ((n = data.read(buf)) > 0) {
    				messageDigest.update(buf, 0, n);
    			}
    			byte hash[] = messageDigest.digest();
    			Calendar cal = Calendar.getInstance();
    			byte[] ocsp = null;
    			if (options.isOcspEnabledX() && chain.length >= 2) {
    				LOGGER.info(RES.get("console.getOCSPURL"));
    				String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
    				if (StringUtils.isEmpty(url)) {
    					// get from options
    					LOGGER.info(RES.get("console.noOCSPURL"));
    					url = options.getOcspServerUrl();
    				}
    				if (!StringUtils.isEmpty(url)) {
    					LOGGER.info(RES.get("console.readingOCSP", url));
    					final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0],
    							(X509Certificate) chain[1], url);
    					ocspClient.setProxy(tmpProxy);
    					ocsp = ocspClient.getEncoded();
    				}
    			}
    			byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
    			sgn.update(sh, 0, sh.length);
     
    			TSAClientBouncyCastle tsc = null;
    			if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) {
    				LOGGER.info(RES.get("console.creatingTsaClient"));
    				if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) {
    					tsc = new TSAClientBouncyCastle(options.getTsaUrl(),
    							StringUtils.defaultString(options.getTsaUser()), StringUtils.defaultString(options
    									.getTsaPasswd()));
    				} else {
    					tsc = new TSAClientBouncyCastle(options.getTsaUrl());
     
    				}
    				tsc.setProxy(tmpProxy);
    				final String policyOid = options.getTsaPolicy();
    				if (StringUtils.isNotEmpty(policyOid)) {
    					LOGGER.info(RES.get("console.settingTsaPolicy", policyOid));
    					tsc.setPolicy(policyOid);
    				}
    			}
    			byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
     
    			if (contentEstimated + 2 < encodedSig.length) {
    				System.err.println("SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length);
    				throw new Exception("Not enough space");
    			}
     
    			byte[] paddedSig = new byte[contentEstimated];
    			System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
     
    			PdfDictionary dic2 = new PdfDictionary();
    			dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    			LOGGER.info(RES.get("console.closeStream"));
    			sap.close(dic2);
    			fout.close();
    			fout = null;
    			finished = true;
    		} catch (Exception e) {
    			LOGGER.error(RES.get("console.exception"), e);
    		} catch (OutOfMemoryError e) {
    			LOGGER.fatal(RES.get("console.memoryError"), e);
    		} finally {
    			if (fout != null) {
    				try {
    					fout.close();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
     
    			LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error")));
    			options.fireSignerFinishedEvent(tmpException);
    		}
    		return finished;
    	}
     
    	/**
             * Validates if input and output files are valid for signing.
             * 
             * @param inFile
             *            input file
             * @param outFile
             *            output file
             * @return true if valid, false otherwise
             */
    	private boolean validateInOutFiles(final String inFile, final String outFile) {
    		LOGGER.info(RES.get("console.validatingFiles"));
    		if (StringUtils.isEmpty(inFile) || StringUtils.isEmpty(outFile)) {
    			LOGGER.info(RES.get("console.fileNotFilled.error"));
    			return false;
    		}
    		final File tmpInFile = new File(inFile);
    		final File tmpOutFile = new File(outFile);
    		if (!(tmpInFile.exists() && tmpInFile.isFile() && tmpInFile.canRead())) {
    			LOGGER.info(RES.get("console.inFileNotFound.error"));
    			return false;
    		}
    		if (tmpInFile.getAbsolutePath().equals(tmpOutFile.getAbsolutePath())) {
    			LOGGER.info(RES.get("console.filesAreEqual.error"));
    			return false;
    		}
    		return true;
    	}
     
    }

  6. #6
    Membre actif
    Homme Profil pro
    Inscrit en
    Septembre 2013
    Messages
    149
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Septembre 2013
    Messages : 149
    Par défaut
    Selon le message d'erreur, le problème provient d'un mauvaise utilisation de
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
        public final Certificate[] getCertificateChain(String alias)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            return keyStoreSpi.engineGetCertificateChain(alias);
        }
    Cette méthode retourne alias mais alias est null dans ton code. C'est pour ça que la NullPointerException est générée.
    En plus:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
                    public ProtectionParameter getProtectionParameter(String alias)
                    {
                        if (alias == null) {
                            throw new NullPointerException();
                        }
    ...
    Tu envoie bien null à cette classe! Il faut que dans ton code, tu donne une valeur (de type String) à alias!
    Je n'ai trouvé aucune référence à cette variable dans ta classe. Il faut que tu lise mieux les classes que tu utilises!

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    * <p> Each entry in a keystore is identified by an "alias" string. In the
     * case of private keys and their associated certificate chains, these strings
     * distinguish among the different ways in which the entity may authenticate
     * itself. For example, the entity may authenticate itself using different
     * certificate authorities, or using different public key algorithms.
    La méthode qui t'intéresse est celle-ci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
        public final void setKeyEntry(String alias, Key key, char[] password,
                                      Certificate[] chain)
            throws KeyStoreException
        {
            if (!initialized) {
                throw new KeyStoreException("Uninitialized keystore");
            }
            if ((key instanceof PrivateKey) &&
                (chain == null || chain.length == 0)) {
                throw new IllegalArgumentException("Private key must be "
                                                   + "accompanied by certificate "
                                                   + "chain");
            }
            keyStoreSpi.engineSetKeyEntry(alias, key, password, chain);
        }
    Il faut que dans ton code, tu appelle cette méthode:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    KeyStoreUtils.setKeyEntry(<l'alias que tu as généré> , key , password , certificateChain);

  7. #7
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Ce que je comprend pas, c'est qu'il me demande un alias alors qu'en lançant l'application de base et en ne renseignant pas d'alias il le trouve tout seul

    Enfin bon, je vais essayer de le renseigner dans ma classe (surtout comprendre les 4 paramètres : qui ils sont et à quoi ils servent et comment les appeler)

  8. #8
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Pour commencer j'essaye simplement d'afficher/lister les alias existants

    le code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    System.out.println("la liste est : "+ks.aliases());
    Mais j'obtiens déjà une erreur qui est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Exception in thread "main" java.security.KeyStoreException: Uninitialized keystore
    	at java.security.KeyStore.aliases(KeyStore.java:1221)
    	at net.sf.jsignpdf.test.main(test.java:146)
    Et me voilà bloqué à cet endroit

  9. #9
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    766
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 766
    Par défaut
    Le fichier du keystore n'est pas chargé.


    Exemple :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ks.load(monfichierKeyStore, passwordDuKeyStore);

  10. #10
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    C'est ce que j'ai pensé mais je vois pas par quoi remplacer monfichierKeyStore et passwordDuKeyStore

    Enfin je sais pas comment on peut aller chercher ces informations

  11. #11
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    766
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 766
    Par défaut
    C'est l'InputStream du fichier et l'autre le mot de passe du fichier tout simplement.

  12. #12
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Ce que je voulais dire, c'est que je sais pas où se trouve le fichier et le mot de passe, je vais jeter un oeil sur les sources du programme

  13. #13
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    J'ai trouvé le fichier KeyStore, par défaut il se trouve ici : $JAVA_HOME/jre/lib/security/cacerts

    Là je test ce code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    		        
    File file = "$JAVA_HOME/jre/lib/security/cacerts" ;
    InputStream NomKS = new FileInputStream(file);
    char[] passwordDuKeyStore = null;
    ks.load(NomKS, passwordDuKeyStore);
    Sauf que ce que j'ai en rouge c'est pas bon, normal un File n'est pas un String

  14. #14
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    766
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 766
    Par défaut
    Ce fichier contient des certificats par défaut de la jre, le mot de passe est en principe changeit.
    Mais je doute que ce soit le but de votre programme d'utiliser ces certificats.

    Vous n'avez pas prévu d'utiliser le votre ?

  15. #15
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    		        BasicSignerOptions options = new BasicSignerOptions();
    		        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
     
    		        String file = "C:/Program Files (x86)/Java/jdk1.8.0/jre/lib/security/cacerts";
    		        InputStream NomKS = new FileInputStream(file);
    		        char[] passwordDuKeyStore = null;
    		        ks.load(NomKS, passwordDuKeyStore);
     
    		        System.out.println("la liste est : "+ks.aliases());
    Donc ce code-ci fonctionne, enfin ks.aliases() renvoie bien quelque chose qui est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    java.util.Hashtable$Enumerator@121714c
    Non le but est d'utiliser une clé "indépendante" de la jre, mais je voulais me servir de aliases() pour avoir sous les yeux tout les certificats utilisable pour pouvoir récupérer les informations du certificat que j'utiliserai pour la signature.
    Par informations je veut dire les arguments de :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    KeyStoreUtils.setKeyEntry(<l'alias que tu as généré> , key , password , certificateChain);
    Parce que j'ai le nom de l'alias mais pas le reste, et j'en ai besoin

    Sinon il y a un truc que je ne comprend pas, lorsque je lance le programme en fonctionnement "normal" : c'est-à-dire on a un menu on renseigne les infos nécessaires et on lance le programme ça fonctionne
    Mais lorsque j'appelle le code pour signer (signFile() ) dans ma propre classe : cela ne fonctionne pas, d'où le besoin de faire ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    KeyStoreUtils.setKeyEntry(<l'alias que tu as généré> , key , password , certificateChain);
    D'ou mon blocage actuel, j'ai besoin de récupérer toutes les informations nécessaires à cette méthode

  16. #16
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    766
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 766
    Par défaut
    Ca ne fonctionne pas car tu n'as visiblement pas construit ton propre certificat signé par un CA ou au pire auto-signé.

  17. #17
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Donc si ma classe s’exécute une fois l'application "initialisé", c'est-à-dire avec au moins un fichier signé, cela devrai fonctionné logiquement car

    Faut que je trouve comment "lancer/run" / exécuté ma classe une fois l'application en route, ou suite à une signature de fichier "manuel"

    Je viens de trouver la classe main() de l'application :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package net.sf.jsignpdf;
     
    import static net.sf.jsignpdf.Constants.*;
     
    import java.io.File;
    import java.io.FileFilter;
    import java.security.Provider;
    import java.security.Security;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
     
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
     
    import net.sf.jsignpdf.ssl.SSLInitializer;
    import net.sf.jsignpdf.utils.ConfigProvider;
    import net.sf.jsignpdf.utils.GuiUtils;
    import net.sf.jsignpdf.utils.KeyStoreUtils;
    import net.sf.jsignpdf.utils.PKCS11Utils;
     
    import org.apache.commons.cli.HelpFormatter;
    import org.apache.commons.cli.ParseException;
    import org.apache.commons.io.filefilter.AndFileFilter;
    import org.apache.commons.io.filefilter.FileFileFilter;
    import org.apache.commons.io.filefilter.WildcardFileFilter;
    import org.apache.commons.lang3.ArrayUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.log4j.Logger;
     
    /**
     * JSignPdf main class - it either process command line or if no argument is
     * given, sets system Look&Feel and creates SignPdfForm GUI.
     * 
     * @author Josef Cacek
     */
    public class Signer {
     
    	private final static Logger LOGGER = Logger.getLogger(Signer.class);
     
    	/**
             * Prints formatted help message (command line arguments).
             */
    	private static void printHelp() {
    		final HelpFormatter formatter = new HelpFormatter();
    		formatter.printHelp(
    				80,
    				"java -jar JSignPdf.jar [file1.pdf [file2.pdf ...]]",
    				RES.get("hlp.header"),
    				SignerOptionsFromCmdLine.OPTS,
    				NEW_LINE + RES.get("hlp.footer.exitCodes") + NEW_LINE + StringUtils.repeat("-", 80) + NEW_LINE
    						+ RES.get("hlp.footer.examples"), true);
    	}
     
    	/**
             * Main.
             * 
             * @param args
             */
    	public static void main(String[] args) {
    		try {
    			SSLInitializer.init();
    		} catch (Exception e) {
    			LOGGER.warn("Unable to re-configure SSL layer", e);
    		}
     
    		final String pkcs11ProviderName = PKCS11Utils.registerProvider(ConfigProvider.getInstance().getProperty(
    				"pkcs11config.path"));
     
    		traceInfo();
     
    		if (args != null && args.length > 0) {
    			final SignerOptionsFromCmdLine tmpOpts = new SignerOptionsFromCmdLine();
    			parseCommandLine(args, tmpOpts);
     
    			if (tmpOpts.isPrintVersion()) {
    				System.out.println("JSignPdf version " + VERSION);
    			}
    			if (tmpOpts.isPrintHelp()) {
    				printHelp();
    			}
    			if (tmpOpts.isListKeyStores()) {
    				LOGGER.info(RES.get("console.keystores"));
    				for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
    					System.out.println(tmpKsType);
    				}
    			}
    			if (tmpOpts.isListKeys()) {
    				final String[] tmpKeyAliases = KeyStoreUtils.getKeyAliases(tmpOpts);
    				LOGGER.info(RES.get("console.keys"));
    				// list certificate aliases in the keystore
    				for (String tmpCert : tmpKeyAliases) {
    					System.out.println(tmpCert);
    				}
    			}
    			if (ArrayUtils.isNotEmpty(tmpOpts.getFiles())
    					|| (!StringUtils.isEmpty(tmpOpts.getInFile()) && !StringUtils.isEmpty(tmpOpts.getOutFile()))) {
    				signFiles(tmpOpts);
    			} else {
    				final boolean tmpCommand = tmpOpts.isPrintVersion() || tmpOpts.isPrintHelp()
    						|| tmpOpts.isListKeyStores() || tmpOpts.isListKeys();
    				if (!tmpCommand) {
    					// no valid command provided - print help and exit
    					printHelp();
    					System.exit(EXIT_CODE_NO_COMMAND);
    				}
    			}
    		} else {
    			try {
    				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    			} catch (Exception e) {
    				System.err.println("Can't set Look&Feel.");
    			}
    			SignPdfForm tmpForm = new SignPdfForm(WindowConstants.EXIT_ON_CLOSE);
    			tmpForm.pack();
    			GuiUtils.center(tmpForm);
    			tmpForm.setVisible(true);
    		}
     
    		// some tokens/card-readers hangs during second usage of the program, they have to be unplugged and plugged again
    		// following code should prevent this issue
    		if (pkcs11ProviderName != null) {
    			Security.removeProvider(pkcs11ProviderName);
    			//we should wait a little bit to de-register provider correctly (is it a driver issue?)
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
     
    	/**
             * Writes info about security providers to the {@link Logger} instance. The
             * log-level for messages is TRACE.
             */
    	@SuppressWarnings({ "rawtypes", "unchecked" })
    	private static void traceInfo() {
    		if (LOGGER.isTraceEnabled()) {
    			try {
    				Provider[] aProvider = Security.getProviders();
    				for (int i = 0; i < aProvider.length; i++) {
    					Provider provider = aProvider[i];
    					LOGGER.trace("Provider " + (i + 1) + " : " + provider.getName() + " " + provider.getInfo() + " :");
    					List keyList = new ArrayList(provider.keySet());
    					try {
    						Collections.sort(keyList);
    					} catch (Exception e) {
    						LOGGER.trace("Provider's properties keys can't be sorted", e);
    					}
    					Iterator keyIterator = keyList.iterator();
    					while (keyIterator.hasNext()) {
    						String key = (String) keyIterator.next();
    						LOGGER.trace(key + ": " + provider.getProperty(key));
    					}
    					LOGGER.trace("------------------------------------------------");
    				}
    			} catch (Exception e) {
    				LOGGER.trace("Listing security providers failed", e);
    			}
    		}
    	}
     
    	/**
             * Sign the files
             * 
             * @param anOpts
             */
    	private static void signFiles(SignerOptionsFromCmdLine anOpts) {
    		final SignerLogic tmpLogic = new SignerLogic(anOpts);
    		if (ArrayUtils.isEmpty(anOpts.getFiles())) {
    			// we've used -lp (loadproperties) parameter
    			if (!tmpLogic.signFile()) {
    				System.exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
    			}
    			return;
    		}
    		int successCount = 0;
    		int failedCount = 0;
     
    		for (final String wildcardPath : anOpts.getFiles()) {
    			final File wildcardFile = new File(wildcardPath);
     
    			File[] inputFiles;
    			if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
    				final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
    				final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE, new WildcardFileFilter(
    						wildcardFile.getName()));
    				inputFiles = inputFolder.listFiles(fileFilter);
    				if (inputFiles == null) {
    					continue;
    				}
    			} else {
    				inputFiles = new File[] { wildcardFile };
    			}
    			for (File inputFile : inputFiles) {
    				final String tmpInFile = inputFile.getPath();
    				if (!inputFile.canRead()) {
    					failedCount++;
    					System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
    					continue;
    				}
    				anOpts.setInFile(tmpInFile);
    				String tmpNameBase = inputFile.getName();//variable nom d'entrée // saisie nom d'entrée
    				System.out.println("tmpNameBase est égal à :" + tmpNameBase );
    				String tmpSuffix = ".pdf";
    				if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
    					tmpSuffix = StringUtils.right(tmpNameBase, 4);
    					tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
    				}
    				final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
    				tmpName.append(anOpts.getOutPrefix());
    				tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
    				anOpts.setOutFile(tmpName.toString());
    				if (tmpLogic.signFile()) {
    					successCount++;
    				} else {
    					failedCount++;
    				}
     
    			}
    		}
    		if (failedCount > 0) {
    			System.exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
    		}
    	}
     
    	/**
             * Parses the command line. Exits with error exit code when parsing fails.
             * 
             * @param args
             * @param opts
             */
    	private static void parseCommandLine(String[] args, final SignerOptionsFromCmdLine opts) {
    		try {
    			opts.loadCmdLine(args);
    		} catch (ParseException exp) {
    			System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage());
    			System.exit(EXIT_CODE_PARSE_ERR);
    		}
    	}
    }

  18. #18
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Je vais essayer d'être plus clair (si possible ^^)

    Actuellement l'erreur viendrait du fait que le keystore s'initialise/load pas lorsque j'exécute le main de ma classe test et seulement elle (qui appelle la méthode signFile() lorsqu'un nouveau fichier est détecté)

    J'ai pour idée d'exécuté le main de ma classe test une fois que l'application est lancé et/ou une fois qu'un fichier est signé "manuellement". Normalement je n'aurais plus de problème de load/init ici car ma classe test sera exécuté après l'appli

    Mon problème : je sais pas comment faire ça :/ Le code de la classe main() de l'application est ci-dessus et je ne sais pas où appeler ma classe test dans ce code, ou si je dois faire un copié/coller et supprimer ma classe

    Voilà, j'espère que j'ai été plus clair :p

  19. #19
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Les modifications sont en rouge, voici la méthode main() de l'application
    J'ai donc ajouter mon code "tout simplement" à la suite de la méthode main()
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    package net.sf.jsignpdf;
    
    import static net.sf.jsignpdf.Constants.*;
    
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.StandardWatchEventKinds;
    import java.nio.file.WatchEvent;
    import java.nio.file.WatchKey;
    import java.nio.file.WatchService;
    import java.security.KeyStore;
    import java.security.Provider;
    import java.security.Security;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    
    import net.sf.jsignpdf.ssl.SSLInitializer;
    import net.sf.jsignpdf.utils.ConfigProvider;
    import net.sf.jsignpdf.utils.GuiUtils;
    import net.sf.jsignpdf.utils.KeyStoreUtils;
    import net.sf.jsignpdf.utils.PKCS11Utils;
    
    import org.apache.commons.cli.HelpFormatter;
    import org.apache.commons.cli.ParseException;
    import org.apache.commons.io.filefilter.AndFileFilter;
    import org.apache.commons.io.filefilter.FileFileFilter;
    import org.apache.commons.io.filefilter.WildcardFileFilter;
    import org.apache.commons.lang3.ArrayUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.log4j.Logger;
    
    /**
     * JSignPdf main class - it either process command line or if no argument is
     * given, sets system Look&Feel and creates SignPdfForm GUI.
     * 
     * @author Josef Cacek
     */
    public class Signer {
    
    	private final static Logger LOGGER = Logger.getLogger(Signer.class);
    
    	/**
    	 * Prints formatted help message (command line arguments).
    	 */
    	private static void printHelp() {
    		final HelpFormatter formatter = new HelpFormatter();
    		formatter.printHelp(
    				80,
    				"java -jar JSignPdf.jar [file1.pdf [file2.pdf ...]]",
    				RES.get("hlp.header"),
    				SignerOptionsFromCmdLine.OPTS,
    				NEW_LINE + RES.get("hlp.footer.exitCodes") + NEW_LINE + StringUtils.repeat("-", 80) + NEW_LINE
    						+ RES.get("hlp.footer.examples"), true);
    	}
    
    	/**
    	 * Main.
    	 * 
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		try {
    			SSLInitializer.init();
    		} catch (Exception e) {
    			LOGGER.warn("Unable to re-configure SSL layer", e);
    		}
    		     
    		final String pkcs11ProviderName = PKCS11Utils.registerProvider(ConfigProvider.getInstance().getProperty(
    				"pkcs11config.path"));
    
    		traceInfo();
    
    		if (args != null && args.length > 0) {
    			final SignerOptionsFromCmdLine tmpOpts = new SignerOptionsFromCmdLine();
    			parseCommandLine(args, tmpOpts);
    
    			if (tmpOpts.isPrintVersion()) {
    				System.out.println("JSignPdf version " + VERSION);
    			}
    			if (tmpOpts.isPrintHelp()) {
    				printHelp();
    			}
    			if (tmpOpts.isListKeyStores()) {
    				LOGGER.info(RES.get("console.keystores"));
    				for (String tmpKsType : KeyStoreUtils.getKeyStores()) {
    					System.out.println(tmpKsType);
    				}
    			}
    			if (tmpOpts.isListKeys()) {
    				final String[] tmpKeyAliases = KeyStoreUtils.getKeyAliases(tmpOpts);
    				LOGGER.info(RES.get("console.keys"));
    				// list certificate aliases in the keystore
    				for (String tmpCert : tmpKeyAliases) {
    					System.out.println(tmpCert);
    				}
    			}
    			if (ArrayUtils.isNotEmpty(tmpOpts.getFiles())
    					|| (!StringUtils.isEmpty(tmpOpts.getInFile()) && !StringUtils.isEmpty(tmpOpts.getOutFile()))) {
    				signFiles(tmpOpts);
    			} else {
    				final boolean tmpCommand = tmpOpts.isPrintVersion() || tmpOpts.isPrintHelp()
    						|| tmpOpts.isListKeyStores() || tmpOpts.isListKeys();
    				if (!tmpCommand) {
    					// no valid command provided - print help and exit
    					printHelp();
    					System.exit(EXIT_CODE_NO_COMMAND);
    				}
    			}
    		} else {
    			try {
    				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    			} catch (Exception e) {
    				System.err.println("Can't set Look&Feel.");
    			}
    			SignPdfForm tmpForm = new SignPdfForm(WindowConstants.EXIT_ON_CLOSE);
    			tmpForm.pack();
    			GuiUtils.center(tmpForm);
    			tmpForm.setVisible(true);
    		}
    		// some tokens/card-readers hangs during second usage of the program, they have to be unplugged and plugged again
    		// following code should prevent this issue
    		if (pkcs11ProviderName != null) {
    			Security.removeProvider(pkcs11ProviderName);
    			//we should wait a little bit to de-register provider correctly (is it a driver issue?)
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		
    			 
    			
    			Path chemin = Paths.get("C:/Users/avidegrain/Desktop/repertoire_1/test.pdf");  //on prend le nom du fichier infile
    			Path cheminout = Paths.get("C:/Users/avidegrain/Desktop/repertoire_2/test.pdf");
    			final Path dir = chemin.getParent();// on prend le répertoire du fichier infile
    	                Path dirout = cheminout.getParent();
    	        
    			WatchService watcher = FileSystems.getDefault().newWatchService();
                            WatchKey key = dir.register(watcher,
    		    		StandardWatchEventKinds.ENTRY_CREATE);
    						
    			for (;;) {
    			    // wait for key to be signaled			    
    			    try {
    			        key = watcher.take();
    			    } catch (InterruptedException x) {
    			        return;
    			    }
    			    
    			    for (WatchEvent<?> event: key.pollEvents()) {
    			        WatchEvent.Kind<?> kind = event.kind();
    	
    			        WatchEvent<Path> ev = (WatchEvent<Path>)event;
    			        Path filename = ev.context();
    	                String type = Files.probeContentType(filename); //On récupère l'extension du fichier
    			      
    			        try {
    			           
    			            Path child = dir.resolve(filename);
    			            if (!Files.probeContentType(child).equals("application/pdf")) {
    			            	 
    			                System.err.format("New file '%s'" +
    			                    " is not a pdf application file.%n", filename);
    			                continue;
           
    			           }
    			        } catch (IOException x) {
    			            System.err.println(x);
    			         
    			            continue;
    			        }
    
    			    
    			        System.out.println("Le fichier est : " + dir+ "\\" + filename );
    			        Path FileOut = Paths.get(dirout+ "\\" + filename);
    			        System.out.println("Le fichier Out est : " + FileOut);
    			        Path FileIn = Paths.get(dir+ "\\" + filename);
    			        System.out.println("Le fichier In est : " + FileIn);
    			        
      
    			        BasicSignerOptions options = new BasicSignerOptions();
    			        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    			        
    			        options.setInFile(FileIn.toString());
    			        options.setOutFile(FileOut.toString());
    			        
    			        SignerLogic sl = new SignerLogic(options);
    			        sl.run();
    
    
    			    }
    
    			    boolean valid = key.reset();
    			    if (!valid) {
    			        break;
    			    }
    			}
    		
    			
    			
    			
    			
    		}
    		
    	
    
    	/**
    	 * Writes info about security providers to the {@link Logger} instance. The
    	 * log-level for messages is TRACE.
    	 */
    	@SuppressWarnings({ "rawtypes", "unchecked" })
    	private static void traceInfo() {
    		if (LOGGER.isTraceEnabled()) {
    			try {
    				Provider[] aProvider = Security.getProviders();
    				for (int i = 0; i < aProvider.length; i++) {
    					Provider provider = aProvider[i];
    					LOGGER.trace("Provider " + (i + 1) + " : " + provider.getName() + " " + provider.getInfo() + " :");
    					List keyList = new ArrayList(provider.keySet());
    					try {
    						Collections.sort(keyList);
    					} catch (Exception e) {
    						LOGGER.trace("Provider's properties keys can't be sorted", e);
    					}
    					Iterator keyIterator = keyList.iterator();
    					while (keyIterator.hasNext()) {
    						String key = (String) keyIterator.next();
    						LOGGER.trace(key + ": " + provider.getProperty(key));
    					}
    					LOGGER.trace("------------------------------------------------");
    				}
    			} catch (Exception e) {
    				LOGGER.trace("Listing security providers failed", e);
    			}
    		}
    
    	}
    
    	/**
    	 * Sign the files
    	 * 
    	 * @param anOpts
    	 */
    	private static void signFiles(SignerOptionsFromCmdLine anOpts) {
    		final SignerLogic tmpLogic = new SignerLogic(anOpts);
    		if (ArrayUtils.isEmpty(anOpts.getFiles())) {
    			// we've used -lp (loadproperties) parameter
    			if (!tmpLogic.signFile()) {
    				System.exit(Constants.EXIT_CODE_ALL_SIG_FAILED);
    			}
    			return;
    		}
    		int successCount = 0;
    		int failedCount = 0;
    
    		for (final String wildcardPath : anOpts.getFiles()) {
    			final File wildcardFile = new File(wildcardPath);
    
    			File[] inputFiles;
    			if (StringUtils.containsAny(wildcardFile.getName(), '*', '?')) {
    				final File inputFolder = wildcardFile.getAbsoluteFile().getParentFile();
    				final FileFilter fileFilter = new AndFileFilter(FileFileFilter.FILE, new WildcardFileFilter(
    						wildcardFile.getName()));
    				inputFiles = inputFolder.listFiles(fileFilter);
    				if (inputFiles == null) {
    					continue;
    				}
    			} else {
    				inputFiles = new File[] { wildcardFile };
    			}
    			for (File inputFile : inputFiles) {
    				final String tmpInFile = inputFile.getPath();
    				if (!inputFile.canRead()) {
    					failedCount++;
    					System.err.println(RES.get("file.notReadable", new String[] { tmpInFile }));
    					continue;
    				}
    				anOpts.setInFile(tmpInFile);
    				String tmpNameBase = inputFile.getName();//variable nom d'entrée // saisie nom d'entrée
    				System.out.println("tmpNameBase est égal à :" + tmpNameBase );
    				String tmpSuffix = ".pdf";
    				if (StringUtils.endsWithIgnoreCase(tmpNameBase, tmpSuffix)) {
    					tmpSuffix = StringUtils.right(tmpNameBase, 4);
    					tmpNameBase = StringUtils.left(tmpNameBase, tmpNameBase.length() - 4);
    				}
    				final StringBuilder tmpName = new StringBuilder(anOpts.getOutPath());
    				tmpName.append(anOpts.getOutPrefix());
    				tmpName.append(tmpNameBase).append(anOpts.getOutSuffix()).append(tmpSuffix);
    				anOpts.setOutFile(tmpName.toString());
    				if (tmpLogic.signFile()) {
    					successCount++;
    				} else {
    					failedCount++;
    				}
    
    			}
    		}
    		if (failedCount > 0) {
    			System.exit(successCount > 0 ? Constants.EXIT_CODE_SOME_SIG_FAILED : Constants.EXIT_CODE_ALL_SIG_FAILED);
    		}
    	}
    
    	/**
    	 * Parses the command line. Exits with error exit code when parsing fails.
    	 * 
    	 * @param args
    	 * @param opts
    	 */
    	private static void parseCommandLine(String[] args, final SignerOptionsFromCmdLine opts) {
    		try {
    			opts.loadCmdLine(args);
    		} catch (ParseException exp) {
    			System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage());
    			System.exit(EXIT_CODE_PARSE_ERR);
    		}
    	}
    }
    Donc à la suite de ça je lance mon main, le menu jsignpdf s'affiche, je renseigne les fichiers et je fait une signature "manuelle" => ça fonctionne, une bonne chose déjà mon code ajouter ne fait pas dysfonctionner l'application

    Ensuite je glisse un fichier pdf dans mon répertoire, ce fichier est détecter et la signature commence ... mais échoue !
    Voici le déroulement vue de la console :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    DEBUG Relaxing SSL security.
    INFO  Lancement de PDF Signer
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : Sebastien GOUHIER
    INFO  Lecture de la clé privée
    INFO  Lecture de la chaîne de certification.
    INFO  Ouverture du fichier PDF
    INFO  Création du fichier PDF
    INFO  Signature
    INFO  Paramètre du niveau de certification
    INFO  Configuration de l'affichage de la signature
    INFO  Utiliser seulement les calques définis par Acrobat 6: true
    INFO  Echelle de l'image de fond
    INFO  Paramètre du calque 2 texte (description)
    INFO  Paramètre du calque 4 texte (état)
    INFO  Paramètre du mode de rendu
    INFO  Création de l'attache de signature, visible dans le document
    INFO  En cours d'exécution. Merci de patienter quelques instants.
    INFO  Fermeture du PDF
    INFO  Opération terminée. Signature du fichier PDF réussie.
    Le fichier est : C:\Users\avidegrain\Desktop\repertoire_1\automatisme_passion.pdf
    Le fichier Out est : C:\Users\avidegrain\Desktop\repertoire_2\automatisme_passion.pdf
    Le fichier In est : C:\Users\avidegrain\Desktop\repertoire_1\automatisme_passion.pdf
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : null
    INFO  Lecture de la clé privée
    ERROR L'application a rencontré un problème.
    java.lang.NullPointerException
    	at sun.security.provider.JavaKeyStore$JKS.convertAlias(JavaKeyStore.java:57)
    	at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:118)
    	at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:55)
    	at java.security.KeyStore.getKey(KeyStore.java:1011)
    	at net.sf.jsignpdf.utils.KeyStoreUtils.getPkInfo(KeyStoreUtils.java:428)
    	at net.sf.jsignpdf.SignerLogic.signFile(SignerLogic.java:138)
    	at net.sf.jsignpdf.SignerLogic.run(SignerLogic.java:113)
    	at net.sf.jsignpdf.Signer.main(Signer.java:235)
    INFO  Opération terminée. Echec de la signature du fichier PDF.
    C'est donc toujours la même erreur que précédemment, même si à coté le fonctionnement final que je souhaite avance, la surveillance d'un répertoire s'effectue bel et bien

  20. #20
    Membre confirmé
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    98
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 98
    Par défaut
    Voici le code de la console lorsque j'ai effectué différent essai de signature :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    DEBUG Relaxing SSL security. => Après ceci la fenêtre de configuration de JSignPDF s'ouvre
    
    A ce moment, je clique sur "Signer" et une autre console s'ouvre, lié à JSignPDF : la signature numérique commence
    INFO  Lancement de PDF Signer   
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : null
    INFO  Lecture de la clé privée
    INFO  Lecture de la chaîne de certification.
    INFO  No private key was found. Check the keystore settings (keystore type, filepath, password, key alias).
    INFO  Opération terminée. Echec de la signature du fichier PDF.
    
    Ici j'ai refermer la console et je relance la signature en branchant cette fois-ci la clé de sécurité au PC
    INFO  Lancement de PDF Signer
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : -Nom Prénom de la clé-
    INFO  Lecture de la clé privée
    INFO  Lecture de la chaîne de certification.
    INFO  Ouverture du fichier PDF
    INFO  Création du fichier PDF
    INFO  Signature
    INFO  Paramètre du niveau de certification
    INFO  Configuration de l'affichage de la signature
    INFO  Utiliser seulement les calques définis par Acrobat 6: true
    INFO  Echelle de l'image de fond
    INFO  Paramètre du calque 2 texte (description)
    INFO  Paramètre du calque 4 texte (état)
    INFO  Paramètre du mode de rendu
    INFO  Création de l'attache de signature, visible dans le document
    INFO  En cours d'exécution. Merci de patienter quelques instants.
    INFO  Fermeture du PDF
    INFO  Opération terminée. Signature du fichier PDF réussie.
    
    
    Cette fois-ci je ne referme pas la console pour que la détection de nouveau doc scrute le répertoire cible
    Le fichier est : C:\Users\avidegrain\Desktop\repertoire_1\automatisme_passion.pdf
    Le fichier Out est : C:\Users\avidegrain\Desktop\repertoire_2\automatisme_passion.pdf
    Le fichier In est : C:\Users\avidegrain\Desktop\repertoire_1\automatisme_passion.pdf
    INFO  Vérification des chemins des fichiers d'entrée/sortie
    INFO  Lecture de l'alias de la clé
    INFO  Utiliser un alias pour la clé : null
    INFO  Lecture de la clé privée
    ERROR L'application a rencontré un problème.
    java.lang.NullPointerException
    	at sun.security.provider.JavaKeyStore$JKS.convertAlias(JavaKeyStore.java:57)
    	at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:118)
    	at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:55)
    	at java.security.KeyStore.getKey(KeyStore.java:1011)
    	at net.sf.jsignpdf.utils.KeyStoreUtils.getPkInfo(KeyStoreUtils.java:428)
    	at net.sf.jsignpdf.SignerLogic.signFile(SignerLogic.java:138)
    	at net.sf.jsignpdf.SignerLogic.run(SignerLogic.java:113)
    	at net.sf.jsignpdf.Signer.main(Signer.java:275)
    INFO  Opération terminée. Echec de la signature du fichier PDF.
    En vert c'est la signature lorsqu'il n'y a pas de clé de sécurité privé branché sur le PC
    En bleu c'est la signature "normale" d'un document
    En rouge c'est la signature lorsqu'un fichier est détecter dans le répertoire cible

    Voilà, aucune différence notable mise à part le fait que la signature automatique ne ré-ouvre pas de console et n'affiche pas cette ligne :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    INFO  Lancement de PDF Signer
    Donc pour l'instant je vais chercher avec le débugger à chercher ou se trouve le code de la ligne précédente
    Ou alors je vais voir ci c'est pas le code de "scrutation" de répertoire qui est mal placé dans le main()
    Bref je sais plus trop ce que je fait

Discussions similaires

  1. Technique des signatures numériques de fichiers système
    Par bruce-willis dans le forum Windows
    Réponses: 2
    Dernier message: 22/07/2008, 16h32
  2. Signature numérique des macros
    Par marc56 dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 04/12/2007, 01h24
  3. Signature Numérique sur des Documents
    Par Myogtha dans le forum Sécurité
    Réponses: 1
    Dernier message: 03/10/2007, 17h05
  4. Signature numérique des messages sortants
    Par scenic29 dans le forum VBA Outlook
    Réponses: 3
    Dernier message: 03/10/2007, 16h38

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo