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

Sécurité Java Discussion :

Cryptage Decryptage asymetrique


Sujet :

Sécurité Java

  1. #1
    Membre confirmé
    Inscrit en
    Octobre 2005
    Messages
    102
    Détails du profil
    Informations forums :
    Inscription : Octobre 2005
    Messages : 102
    Par défaut Cryptage Decryptage asymetrique
    J'ai des paires de clés publique/privée généré en 4D.
    Je voudrais echanger des messages cryptés par mon programme 4D avec un autre programme JAVA.

    Quelqu'un pourrait me donner un exemple de code qui me montrerait comment utiliser ses clés dans mon code JAVA pour décrypter les messages.
    (Je n'ai aucune précision sur l'algo utilisé pour généré ces clés.)

    De façon général, un exemple de code JAVA utilisant un cryptage asymetrique (sans librairie tierce!!)

  2. #2
    Membre émérite Avatar de g_rare
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    608
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 608
    Par défaut
    Citation Envoyé par bslota
    un exemple de code JAVA utilisant un cryptage asymetrique (sans librairie tierce!!)
    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
    package toto;
     
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
     
    /**
     * Utilitaire de chiffrement/dechiffrement :
     * standards de calcul cryptographique "textuel",
     * par algorithmes symetriques (RSA '2048 bits' et/ou ElGamal '1024 bits')...
     * 
     * <!-- -------------------------------------------------- -->
     * 
     * </p>Exemple d'installation du fournisseur JCE (Java Cryptography Extension)
     * {@link http://www.bouncycastle.org Bouncy Castle} :
     * 
     * - Copier le fichier "bcprov-jdk14-131.jar" (source de l'implementation)
     * dans le repertoire $JAVA_HOME/jre/lib/ext (applications externes) ;
     * 
     * - Extraire tout fichier de l'archive "jce_policy-1_4_2.zip" (juridiction illimitee)
     * dans le repertoire $JAVA_HOME/jre/lib/security (parametrage systeme) ;
     * 
     * - Ajouter la ligne <pre>security.provider.6=org.bouncycastle.jce.provider.BouncyCastleProvider</pre>
     * dans le fichier $JAVA_HOME/jre/lib/security/java.security
     * <pre>
     * security.provider.1=sun.security.provider.Sun
     * security.provider.2=com.sun.net.ssl.internal.ssl.Provider
     * security.provider.3=com.sun.rsajca.Provider
     * security.provider.4=com.sun.crypto.provider.SunJCE
     * security.provider.5=sun.security.jgss.SunProvider
     * </pre> ;
     * 
     * - Verifier la nouvelle configuration avec la commande
     * <code>System.out.println(java.util.Arrays.asList(java.security.Security.getProviders()));</code>
     * .
     */
    public final class Asymetrique {
     
        /*
         * (de)chiffrement
         */
     
        /**
         * L'algorithme de chiffrement/dechiffrement asymetrique RSA ("Rivest, Shamir et Adleman"),
         * standardise par la {@link ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-1.asc PKCS#1 v1.5} ;
         * RSA utilise une pair cle publique-cle privee de 2048 bits (512 caracteres hexadecimaux),
         * en mode ECB ("Electronic Code Book") sans IV ("Initialization Vector") standardise par la {@link http://www.itl.nist.gov/fipspubs/fip81.htm FIPS 81},
         * avec remplissage 'OAEPwithSHA1andMGF1Padding' ("Optimal Asymmetric Encryption Padding with Mask Generation Function 1") standardise par la {@link ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-1v2.doc PKCS#1 v2.0}.
         * 
         * @see http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA 
         */
        public final static String ALGORITHME_RSA = "RSA/ECB/OAEPwithSHA1andMGF1Padding";
        // bloc : 214/256 bits
     
        /**
         * L'algorithme de chiffrement/dechiffrement asymetrique ElGamal (Taher Elgamal),
         * standardise par le {@link http://www.nullify.org/docs/elgamal.pdf A Public-Key Cryptosystem and a Signature Scheme Based on Discrete Logarithms} ;
         * ElGamal utilise une pair cle publique-cle privee de 1024 bits (256 caracteres hexadecimaux),
         * en mode ECB ("Electronic Code Book") sans IV ("Initialization Vector") standardise par la {@link http://www.itl.nist.gov/fipspubs/fip81.htm FIPS 81},
         * avec remplissage 'OAEPwithSHA1andMGF1Padding' ("Optimal Asymmetric Encryption Padding with Mask Generation Function 1") standardise par la {@link ftp://ftp.rsasecurity.com/pub/pkcs/doc/pkcs-1v2.doc PKCS#1 v2.0}.
         * 
         * @see http://java.sun.com/j2se/1.4.2/docs/guide/security/CryptoSpec.html#AppA
         */
        public final static String ALGORITHME_ELGAMAL = "ElGamal/ECB/OAEPwithSHA1andMGF1Padding";
        // bloc : 86/256 bits
     
        /**
         * Le nom (normalise) de l'algorithme de chiffrement/dechiffrement asymetrique,
         * par defaut si non-precise : de valeur "RSA/ECB/OAEPwithSHA1andMGF1Padding".
         */
        public final static String DEFAUT_ALGORITHME = ALGORITHME_RSA;
     
        /**
         * La longueur (en bits) des cles de chiffrement/dechiffrement asymetrique,
         * par defaut si non-renseigne : de valeur "2048".
         */
        public final static int DEFAUT_CLES = 2048;
     
        //    /**
        //     * Initialisation des fabriques de chiffrement/signature asymetrique (standards).
        //     */
        //    static {
        //        try {
        //            // RSA
        //            Cipher.getInstance(ALGORITHME_RSA);
        //            // ElGamal
        //            Cipher.getInstance(ALGORITHME_ELGAMAL);
        //        } catch (NoSuchAlgorithmException nsae) {
        //            nsae.printStackTrace();
        //        } catch (NoSuchPaddingException nspe) {
        //            nspe.printStackTrace();
        //        }
        //    }
     
        /*
         * pas d'instanciation
         */
        private Asymetrique() {
            // classe abstraite
        }
     
        /**
         * Renvoie une "paire de cles publique/privee" generee,
         * selon l'algorithme specifie (si disponible),
         * de longueur en parametre (2048 bits par defaut).
         */
        public static KeyPair genererCles(String fournisseur, String algorithme, int longueur)
            throws NoSuchAlgorithmException, NoSuchProviderException {
            KeyPair cles = null;
            // RSA 2048 bits par defaut
            String transformation = (algorithme == null) ? DEFAUT_ALGORITHME : algorithme;
            // 'transformation' = "<algorithm>/<mode>/<padding>"
            KeyPairGenerator fabrique =
                (fournisseur == null)
                    ? KeyPairGenerator.getInstance(Utilitaire.algoRacine(transformation))
                    : KeyPairGenerator.getInstance(Utilitaire.algoRacine(transformation), fournisseur);
            fabrique.initialize(longueur <= 0 ? DEFAUT_CLES : longueur); // RSA 2048 bits par defaut
            cles = fabrique.generateKeyPair();
            return cles;
        }
     
        /**
         * Renvoie la "cle publique",
         * au format 'X.509' v3 standardise par la {@link http://www.ietf.org/rfc/rfc3280.txt RFC 3280},
         * specifique (a la paire) des cles en parametre.
         * 
         * @see #genererCles(String, int)
         */
        public static byte[] clePublique(KeyPair cles) {
            PublicKey publique = cles.getPublic();
            return publique.getEncoded(); // X.509 format
        }
     
        /**
         * Renvoie la "cle privee",
         * au format 'PKCS#8' v1.2 standardise par le {@link ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-8.asc Private-Key Information Syntax Standard},
         * specifique (a la paire) des cles en parametre.
         * 
         * @see #genererCles(String, int)
         */
        public static byte[] clePrivee(KeyPair cles) {
            PrivateKey privee = cles.getPrivate();
            return privee.getEncoded(); // PKCS#8 format
        }
     
        /**
         * Renvoie la <code>PublicKey</code>,
         * selon l'algorithme specifie (si disponible),
         * pour la "cle publique" au format 'X.509' v3 en parametre.
         * 
         * @see #chiffrer(String, String, byte[], byte[])
         */
        public static PublicKey clePublique(String fournisseur, String algorithme, byte[] cle)
            throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
            PublicKey publique = null;
            // RSA 2048 bits par defaut
            String transformation = (algorithme == null) ? DEFAUT_ALGORITHME : algorithme;
            X509EncodedKeySpec x509 = new X509EncodedKeySpec(cle);
            // 'algorithm' = "<digest>with<encryption>and<mgf>"
            KeyFactory fabrique =
                (fournisseur == null)
                    ? KeyFactory.getInstance(Utilitaire.algoRacine(transformation))
                    : KeyFactory.getInstance(Utilitaire.algoRacine(transformation), fournisseur);
            publique = fabrique.generatePublic(x509); // X.509 format        
            return publique;
        }
     
        /**
         * Renvoie la <code>PrivateKey</code>,
         * selon l'algorithme specifie (si disponible),
         * pour la "cle privee" au format 'PKCS#8' v1.2 en parametre.
         * 
         * @see #dechiffrer(String, String, byte[], byte[])
         */
        public static PrivateKey clePrivee(String fournisseur, String algorithme, byte[] cle)
            throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
            PrivateKey privee = null;
            // RSA 2048 bits par defaut
            String transformation = (algorithme == null) ? DEFAUT_ALGORITHME : algorithme;
            PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(cle);
            // 'algorithm' = "<digest>with<encryption>and<mgf>"
            KeyFactory fabrique =
                (fournisseur == null)
                    ? KeyFactory.getInstance(Utilitaire.algoRacine(transformation))
                    : KeyFactory.getInstance(Utilitaire.algoRacine(transformation), fournisseur);
            privee = fabrique.generatePrivate(pkcs8); // PKCS#8 format
            return privee;
        }
     
        /**
         * Renvoie le resultat du "chiffrement",
         * selon l'algorithme specifie (si disponible),
         * et par la cle publique au format 'X.509' v3 en parametre,
         * d'un texte.
         * 
         * @see #clePublique(KeyPair)
         */
        public static byte[] chiffrer(
            String fournisseur,
            String algorithme,
            byte[] clePublique,
            byte[] texte)
            throws
                IllegalStateException,
                ShortBufferException,
                IllegalBlockSizeException,
                BadPaddingException,
                InvalidKeySpecException,
                InvalidKeyException,
                NoSuchAlgorithmException,
                NoSuchPaddingException,
                NoSuchProviderException {
            byte[] message = null;
            // RSA 2048 bits par defaut
            String transformation = (algorithme == null) ? DEFAUT_ALGORITHME : algorithme;
            Cipher fabrique =
                (fournisseur == null)
                    ? Cipher.getInstance(transformation)
                    : Cipher.getInstance(transformation, fournisseur);
            // 'transformation' = "<algorithm>/<mode>/<padding>"
            PublicKey x509 = clePublique(fournisseur, algorithme, clePublique);
            /**
            X509EncodedKeySpec publique = new X509EncodedKeySpec(clePublique);
            KeyFactory cle =
                (fournisseur == null)
                    ? KeyFactory.getInstance(Utilitaire.algoRacine(transformation))
                    : KeyFactory.getInstance(Utilitaire.algoRacine(transformation), fournisseur);
            PublicKey x509 = cle.generatePublic(publique);
            */
            fabrique.init(Cipher.ENCRYPT_MODE, x509);
            /*
             * fabrique.update(texte);
             * message = fabrique.doFinal();
             */
            int taille = fabrique.getBlockSize(); // valeur exacte en octets
            int blocs = (taille == 0) ? 1 : (int) Math.ceil((double) texte.length / taille); // sup(n)
            // valeur max en octets
            byte[] traitement = new byte[blocs * fabrique.getOutputSize(texte.length)];
            int longueur = 0;
            for (int i = 0; i < blocs; i++) {
                // traitement[longueur...] = crypt< texte[(i)*taille..(i+1)*taille] >
                longueur
                    += fabrique.doFinal(
                        texte,
                        i * taille,
                        (i == blocs - 1) ? texte.length - (i * taille) : taille,
                        traitement,
                        longueur);
            }
            message = new byte[longueur];
            System.arraycopy(traitement, 0, message, 0, message.length); // suppression des 0 inutiles
            //message = fabrique.doFinal(texte);
            return message;
        }
     
        /**
         * Renvoie le resultat du "dechiffrement",
         * selon l'algorithme specifie (si disponible),
         * et par la cle privee au format 'PKCS#8' v1.2 en parametre,
         * d'un texte.
         * 
         * @see #clePrivee(KeyPair)
         */
        public static byte[] dechiffrer(
            String fournisseur,
            String algorithme,
            byte[] clePrivee,
            byte[] texte)
            throws
                InvalidKeySpecException,
                InvalidKeyException,
                IllegalBlockSizeException,
                BadPaddingException,
                IllegalStateException,
                ShortBufferException,
                NoSuchAlgorithmException,
                NoSuchPaddingException,
                NoSuchProviderException {
            byte[] message = null;
            // RSA 2048 bits par defaut
            String transformation = (algorithme == null) ? DEFAUT_ALGORITHME : algorithme;
            Cipher fabrique =
                (fournisseur == null)
                    ? Cipher.getInstance(transformation)
                    : Cipher.getInstance(transformation, fournisseur);
            // 'transformation' = "<algorithm>/<mode>/<padding>"
            PrivateKey pkcs8 = clePrivee(fournisseur, algorithme, clePrivee);
            /**
            PKCS8EncodedKeySpec privee = new PKCS8EncodedKeySpec(clePrivee);
            KeyFactory cle =
                (fournisseur == null)
                    ? KeyFactory.getInstance(Utilitaire.algoRacine(transformation))
                    : KeyFactory.getInstance(Utilitaire.algoRacine(transformation), fournisseur);
            PrivateKey pkcs8 = cle.generatePrivate(privee);
            */
            fabrique.init(Cipher.DECRYPT_MODE, pkcs8);
            /*
             * fabrique.update(texte);
             * message = fabrique.doFinal();
             */
            int taille = fabrique.getBlockSize(); // valeur exacte en octets
            int blocs = (taille == 0) ? 1 : (int) Math.ceil((double) texte.length / taille); // sup(n)
            // valeur max en octets
            byte[] traitement = new byte[blocs * fabrique.getOutputSize(texte.length)];
            int longueur = 0;
            for (int i = 0; i < blocs; i++) {
                // traitement[longueur...] = decrypt< texte[(i)*taille..(i+1)*taille] >
                longueur
                    += fabrique.doFinal(
                        texte,
                        i * taille,
                        (i == blocs - 1) ? texte.length - (i * taille) : taille,
                        traitement,
                        longueur);
            }
            message = new byte[longueur];
            System.arraycopy(traitement, 0, message, 0, message.length); // suppression des 0 inutiles
            //message = fabrique.doFinal(texte);
            return message;
        }
     
        /*
        
        # ===================================
        # Example 10: A 2048-bit RSA Key Pair
        # ===================================
        
        # ------------------------------
        # Components of the RSA Key Pair
        # ------------------------------
        
        # RSA modulus n:
        ae 45 ed 56 01 ce c6 b8 cc 05 f8 03 93 5c 67 4d 
        db e0 d7 5c 4c 09 fd 79 51 fc 6b 0c ae c3 13 a8 
        df 39 97 0c 51 8b ff ba 5e d6 8f 3f 0d 7f 22 a4 
        02 9d 41 3f 1a e0 7e 4e be 9e 41 77 ce 23 e7 f5 
        40 4b 56 9e 4e e1 bd cf 3c 1f b0 3e f1 13 80 2d 
        4f 85 5e b9 b5 13 4b 5a 7c 80 85 ad ca e6 fa 2f 
        a1 41 7e c3 76 3b e1 71 b0 c6 2b 76 0e de 23 c1 
        2a d9 2b 98 08 84 c6 41 f5 a8 fa c2 6b da d4 a0 
        33 81 a2 2f e1 b7 54 88 50 94 c8 25 06 d4 01 9a 
        53 5a 28 6a fe b2 71 bb 9b a5 92 de 18 dc f6 00 
        c2 ae ea e5 6e 02 f7 cf 79 fc 14 cf 3b dc 7c d8 
        4f eb bb f9 50 ca 90 30 4b 22 19 a7 aa 06 3a ef 
        a2 c3 c1 98 0e 56 0c d6 4a fe 77 95 85 b6 10 76 
        57 b9 57 85 7e fd e6 01 09 88 ab 7d e4 17 fc 88 
        d8 f3 84 c4 e6 e7 2c 3f 94 3e 0c 31 c0 c4 a5 cc 
        36 f8 79 d8 a3 ac 9d 7d 59 86 0e aa da 6b 83 bb 
        
        # RSA public exponent e: 
        01 00 01 
        
        # RSA private exponent d: 
        05 6b 04 21 6f e5 f3 54 ac 77 25 0a 4b 6b 0c 85 
        25 a8 5c 59 b0 bd 80 c5 64 50 a2 2d 5f 43 8e 59 
        6a 33 3a a8 75 e2 91 dd 43 f4 8c b8 8b 9d 5f c0 
        d4 99 f9 fc d1 c3 97 f9 af c0 70 cd 9e 39 8c 8d 
        19 e6 1d b7 c7 41 0a 6b 26 75 df bf 5d 34 5b 80 
        4d 20 1a dd 50 2d 5c e2 df cb 09 1c e9 99 7b be 
        be 57 30 6f 38 3e 4d 58 81 03 f0 36 f7 e8 5d 19 
        34 d1 52 a3 23 e4 a8 db 45 1d 6f 4a 5b 1b 0f 10 
        2c c1 50 e0 2f ee e2 b8 8d ea 4a d4 c1 ba cc b2 
        4d 84 07 2d 14 e1 d2 4a 67 71 f7 40 8e e3 05 64 
        fb 86 d4 39 3a 34 bc f0 b7 88 50 1d 19 33 03 f1 
        3a 22 84 b0 01 f0 f6 49 ea f7 93 28 d4 ac 5c 43 
        0a b4 41 49 20 a9 46 0e d1 b7 bc 40 ec 65 3e 87 
        6d 09 ab c5 09 ae 45 b5 25 19 01 16 a0 c2 61 01 
        84 82 98 50 9c 1c 3b f3 a4 83 e7 27 40 54 e1 5e 
        97 07 50 36 e9 89 f6 09 32 80 7b 52 57 75 1e 79 
        
        # Prime p: 
        ec f5 ae cd 1e 55 15 ff fa cb d7 5a 28 16 c6 eb 
        f4 90 18 cd fb 46 38 e1 85 d6 6a 73 96 b6 f8 09 
        0f 80 18 c7 fd 95 cc 34 b8 57 dc 17 f0 cc 65 16 
        bb 13 46 ab 4d 58 2c ad ad 7b 41 03 35 23 87 b7 
        03 38 d0 84 04 7c 9d 95 39 b6 49 62 04 b3 dd 6e 
        a4 42 49 92 07 be c0 1f 96 42 87 ff 63 36 c3 98 
        46 58 33 68 46 f5 6e 46 86 18 81 c1 02 33 d2 17 
        6b f1 5a 5e 96 dd c7 80 bc 86 8a a7 7d 3c e7 69 
        
        # Prime q: 
        bc 46 c4 64 fc 6a c4 ca 78 3b 0e b0 8a 3c 84 1b 
        77 2f 7e 9b 2f 28 ba bd 58 8a e8 85 e1 a0 c6 1e 
        48 58 a0 fb 25 ac 29 99 90 f3 5b e8 51 64 c2 59 
        ba 11 75 cd d7 19 27 07 13 51 84 99 2b 6c 29 b7 
        46 dd 0d 2c ab e1 42 83 5f 7d 14 8c c1 61 52 4b 
        4a 09 94 6d 48 b8 28 47 3f 1c e7 6b 6c b6 88 6c 
        34 5c 03 e0 5f 41 d5 1b 5c 3a 90 a3 f2 40 73 c7 
        d7 4a 4f e2 5d 9c f2 1c 75 96 0f 3f c3 86 31 83 
        
        # p's CRT exponent dP: 
        c7 35 64 57 1d 00 fb 15 d0 8a 3d e9 95 7a 50 91 
        5d 71 26 e9 44 2d ac f4 2b c8 2e 86 2e 56 73 ff 
        6a 00 8e d4 d2 e3 74 61 7d f8 9f 17 a1 60 b4 3b 
        7f da 9c b6 b6 b7 42 18 60 98 15 f7 d4 5c a2 63 
        c1 59 aa 32 d2 72 d1 27 fa f4 bc 8c a2 d7 73 78 
        e8 ae b1 9b 0a d7 da 3c b3 de 0a e7 31 49 80 f6 
        2b 6d 4b 0a 87 5d 1d f0 3c 1b ae 39 cc d8 33 ef 
        6c d7 e2 d9 52 8b f0 84 d1 f9 69 e7 94 e9 f6 c1 
        
        # q's CRT exponent dQ: 
        26 58 b3 7f 6d f9 c1 03 0b e1 db 68 11 7f a9 d8 
        7e 39 ea 2b 69 3b 7e 6d 3a 2f 70 94 74 13 ee c6 
        14 2e 18 fb 8d fc b6 ac 54 5d 7c 86 a0 ad 48 f8 
        45 71 70 f0 ef b2 6b c4 81 26 c5 3e fd 1d 16 92 
        01 98 dc 2a 11 07 dc 28 2d b6 a8 0c d3 06 23 60 
        ba 3f a1 3f 70 e4 31 2f f1 a6 cd 6b 8f c4 cd 9c 
        5c 3d b1 7c 6d 6a 57 21 2f 73 ae 29 f6 19 32 7b 
        ad 59 b1 53 85 85 85 ba 4e 28 b6 0a 62 a4 5e 49 
        
        # CRT coefficient qInv: 
        6f 38 52 6b 39 25 08 55 34 ef 3e 41 5a 83 6e de 
        8b 86 15 8a 2c 7c bf ec cb 0b d8 34 30 4f ec 68 
        3b a8 d4 f4 79 c4 33 d4 34 16 e6 32 69 62 3c ea 
        10 07 76 d8 5a ff 40 1d 3f ff 61 0e e6 54 11 ce 
        3b 13 63 d6 3a 97 09 ee de 42 64 7c ea 56 14 93 
        d5 45 70 a8 79 c1 86 82 cd 97 71 0b 96 20 5e c3 
        11 17 d7 3b 5f 36 22 3f ad d6 e8 ba 90 dd 7c 0e 
        e6 1d 44 e1 63 25 1e 20 c7 f6 6e b3 05 11 7c b8
        
        # ----------------------------------
        # RSAES-OAEP Encryption Example 10.6
        # ----------------------------------
        
        # Message to be encrypted:
        ea f1 a7 3a 1b 0c 46 09 53 7d e6 9c d9 22 8b bc 
        fb 9a 8c a8 c6 c3 ef af 05 6f e4 a7 f4 63 4e d0 
        0b 7c 39 ec 69 22 d7 b8 ea 2c 04 eb ac 
        
        # Seed:
        9f 47 dd f4 2e 97 ee a8 56 a9 bd bc 71 4e b3 ac 
        22 f6 eb 32 
        
        # Encryption:
        2d 20 7a 73 43 2a 8f b4 c0 30 51 b3 f7 3b 28 a6 
        17 64 09 8d fa 34 c4 7a 20 99 5f 81 15 aa 68 16 
        67 9b 55 7e 82 db ee 58 49 08 c6 e6 97 82 d7 de 
        b3 4d bd 65 af 06 3d 57 fc a7 6a 5f d0 69 49 2f 
        d6 06 8d 99 84 d2 09 35 05 65 a6 2e 5c 77 f2 30 
        38 c1 2c b1 0c 66 34 70 9b 54 7c 46 f6 b4 a7 09 
        bd 85 ca 12 2d 74 46 5e f9 77 62 c2 97 63 e0 6d 
        bc 7a 9e 73 8c 78 bf ca 01 02 dc 5e 79 d6 5b 97 
        3f 28 24 0c aa b2 e1 61 a7 8b 57 d2 62 45 7e d8 
        19 5d 53 e3 c7 ae 9d a0 21 88 3c 6d b7 c2 4a fd 
        d2 32 2e ac 97 2a d3 c3 54 c5 fc ef 1e 14 6c 3a 
        02 90 fb 67 ad f0 07 06 6e 00 42 8d 2c ec 18 ce 
        58 f9 32 86 98 de fe f4 b2 eb 5e c7 69 18 fd e1 
        c1 98 cb b3 8b 7a fc 67 62 6a 9a ef ec 43 22 bf 
        d9 0d 25 63 48 1c 9a 22 1f 78 c8 27 2c 82 d1 b6 
        2a b9 14 e1 c6 9f 6a f6 ef 30 ca 52 60 db 4a 46 
        
        # =============================================
        
        */
     
        /**
         * Renvoie la "cle publique" (RSA par defaut),
         * au format 'X.509' v3 standardise par la {@link http://www.ietf.org/rfc/rfc3280.txt RFC 3280},
         * specifique (a la paire) des cles en parametre ;
         * retourne la la conversion hexadecimale de ses bits 'non-signes' (2 caracteres par octet).
         * 
         * @see #clePublique(KeyPair)
         */
        public static String clePubliquePaire(KeyPair cles) {
            // RSA 2048 bits par defaut
            byte[] cle = clePublique(cles);
            return Utilitaire.byteToHex(cle); // X.509 format
        }
     
        /**
         * Renvoie la "cle privee" (RSA par defaut),
         * au format 'PKCS#8' v1.2 standardise par le {@link ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-8.asc Private-Key Information Syntax Standard},
         * specifique (a la paire) des cles en parametre ;
         * retourne la la conversion hexadecimale de ses bits 'non-signes' (2 caracteres par octet).
         * 
         * @see #clePrivee(KeyPair)
         */
        public static String clePriveePaire(KeyPair cles) {
            // RSA 2048 bits par defaut
            byte[] cle = clePrivee(cles);
            return Utilitaire.byteToHex(cle); // PKCS#8 format
        }
     
        /**
         * Renvoie la <code>PublicKey</code>,
         * selon l'algorithme specifie (RSA par defaut),
         * pour la "cle publique" au format 'X.509' v3 en parametre ;
         * prend en parametre la conversion hexadecimale de ses bits 'non-signes' (2 caracteres par octet).
         * 
         * @see #clePublique(String, String, byte[])
         */
        public static PublicKey clePublique(String fournisseur, String algorithme, String cle)
            throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
            // RSA 2048 bits par defaut
            byte[] x509 = Utilitaire.hexToByte(cle);
            return clePublique(fournisseur, algorithme, x509);
        }
     
        /**
         * Renvoie la <code>PrivateKey</code>,
         * selon l'algorithme specifie (RSA par defaut),
         * pour la "cle privee" au format 'PKCS#8' v1.2 en parametre ;
         * prend en parametre la conversion hexadecimale de ses bits 'non-signes' (2 caracteres par octet).
         * 
         * @see #clePrivee(String, String, byte[])
         */
        public static PrivateKey clePrivee(String fournisseur, String algorithme, String cle)
            throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
            // RSA 2048 bits par defaut
            byte[] pkcs8 = Utilitaire.hexToByte(cle);
            return clePrivee(fournisseur, algorithme, pkcs8);
        }
     
        /**
         * Renvoie le resultat du "chiffrement",
         * selon l'algorithme specifie (RSA par defaut),
         * et par la cle publique au format 'X.509' v3 en parametre,
         * d'un texte ;
         * retourne la conversion hexadecimale de ses bits UTF-8 'non-signes' (2 caracteres par octet).
         * 
         * @see #chiffrer(String, byte[], byte[])
         */
        public static String chiffrer(
            String fournisseur,
            String algorithme,
            String clePublique,
            String texte)
            throws
                InvalidKeyException,
                IllegalStateException,
                ShortBufferException,
                IllegalBlockSizeException,
                BadPaddingException,
                InvalidKeySpecException,
                NoSuchAlgorithmException,
                NoSuchPaddingException,
                NoSuchProviderException,
                UnsupportedEncodingException {
            // RSA 2048 bits par defaut
            byte[] cryptage =
                chiffrer(
                    fournisseur,
                    algorithme,
                    Utilitaire.hexToByte(clePublique),
                    texte.getBytes("UTF-8"));
            // standard Unicode
            return Utilitaire.byteToHex(cryptage);
        }
     
        /**
         * Renvoie le resultat du "dechiffrement",
         * selon l'algorithme specifie (RSA par defaut),
         * et par la cle privee au format 'PKCS#8' v1.2 en parametre,
         * d'un texte ;
         * prend en parametre la conversion hexadecimale de ses bits UTF-8 'non-signes' (2 caracteres par octet).
         * 
         * @see #dechiffrer(String, byte[], byte[])
         */
        public static String dechiffrer(
            String fournisseur,
            String algorithme,
            String clePrivee,
            String texte)
            throws
                UnsupportedEncodingException,
                InvalidKeyException,
                InvalidKeySpecException,
                IllegalBlockSizeException,
                BadPaddingException,
                IllegalStateException,
                ShortBufferException,
                NoSuchAlgorithmException,
                NoSuchPaddingException,
                NoSuchProviderException {
            // RSA 2048 bits par defaut
            byte[] clair =
                dechiffrer(
                    fournisseur,
                    algorithme,
                    Utilitaire.hexToByte(clePrivee),
                    Utilitaire.hexToByte(texte));
            return new String(clair, "UTF-8"); // standard Unicode
        }
     
    }

  3. #3
    Membre émérite Avatar de g_rare
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    608
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 608

  4. #4
    Membre confirmé
    Inscrit en
    Octobre 2005
    Messages
    102
    Détails du profil
    Informations forums :
    Inscription : Octobre 2005
    Messages : 102
    Par défaut
    les sources de developpez.com que tu me donnes me plaise moyen.
    Je ne comprenais pas trop le truc de passer par un BigInteger et surtout le message dans l'entête qui dit que le message doit être plus court que la clé... bof!!

    Sinon ton exemple est pas mal mais il manque la classe Utilitaire et j'ai quand même l'impression qu'il faut la librairie tierce BouncyCastle!!

    Il n'existe pas de solution intégré dans le JDK pour ça??

  5. #5
    Membre émérite Avatar de g_rare
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    608
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 608
    Par défaut
    Voici la classe utilitaire :
    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
    package toto;
     
    /**
     * Utilitaire de cryptographie :
     * standards de constante et/ou methode
     * par "service" (hachage, signature, chiffrement symetrique, dechiffrement asymetrique)...
     */
    public final class Utilitaire {
     
        //    /**
        //     * Initialisation des fournisseurs cryptographiques (supplementaires).
        //     */
        //    static {
        //        // Bouncy Castle
        //        if (Security.getProvider("BC") == null) {
        //            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        //        }
        //    }
     
        /*
         * pas d'instanciation
         */
        private Utilitaire() {
            // classe abstraite
        }
     
        /**
         * Identifie le nom standard de la cryptographie (a la racine) du traitement en parametre.
         * 
         * @see http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#trans
         */
        public static String cryptoRacine(String traitement) {
            // 'algorithm' = "<digest>with<encryption>and<mgf>"
            int i = traitement.toLowerCase().indexOf("with");
            if (i == -1) {
                return traitement;
            }
            int j = traitement.toLowerCase().indexOf("and");
            return (j != -1) ? traitement.substring(i + 4, j) : traitement.substring(i + 4);
        }
     
        /**
         * Identifie le nom standard de l'algorithme (a la racine) de la transformation en parametre.
         * 
         * @see http://java.sun.com/j2se/1.4.2/docs/guide/security/jce/JCERefGuide.html#trans
         */
        public static String algoRacine(String transformation) {
            // 'transformation' = "<algorithm>/<mode>/<padding>"
            int i = transformation.indexOf('/');
            return (i != -1) ? transformation.substring(0, i) : transformation;
        }
     
        /**
         * Convertit des octets en leur representation hexadecimale (base 16),
         * chacun se retrouvant finalement 'non signe' et sur 2 caracteres.
         * 
         * @see http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
         */
        public static String byteToHex(byte[] bits) {
            if (bits == null) {
                return null;
            }
            StringBuffer hex = new StringBuffer(bits.length * 2); // encod(1_bit) => 2 digits
            for (int i = 0; i < bits.length; i++) {
                if (((int) bits[i] & 0xff) < 0x10) { // 0 < .. < 9
                    hex.append("0");
                }
                hex.append(Integer.toString((int) bits[i] & 0xff, 16)); // [(bit+256)%256]^16
            }
            return hex.toString();
        }
     
        /**
         * Convertit une representation d'hexadecimaux (base 16) en octets,
         * chacun étant initialement 'non signe' et sur 2 caracteres.
         * 
         * @see http://forum.java.sun.com/thread.jspa?threadID=659432
         */
        public static byte[] hexToByte(String bits) {
            if ((bits == null) || (bits.length() % 2 != 0)) { // pair [xy]
                return null;
            }
            byte[] bytes = new byte[bits.length() / 2]; // decod(2_digits) => 1 bit
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte) Integer.parseInt(bits.substring(2 * i, 2 * i + 2), 16); // |bit|^16
            }
            return bytes;
        }
     
    }
    Sinon en fonction de l'algorithme, il est supporté ou non selon la version du JDK (à travers le SunJCE provider).

    Pour info ; "Bouncy Castle" est juste un JCE provider cité dans les commentaires mais si ton algo est disponible dans le SunJCE de base alors tu n'auras besoin d'aucun autre supplémentaire.

  6. #6
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    Va voir dans le topic cintribuez, j'ai posté des classes qui cryptent et décryptent en RSA ou AES, ça se trouve ici.

    J'espère que ça t'aidera...

Discussions similaires

  1. Cryptage / decryptage xor
    Par deny dans le forum Débuter
    Réponses: 2
    Dernier message: 08/06/2008, 11h52
  2. Problème Cryptage / Decryptage
    Par Invité dans le forum C#
    Réponses: 6
    Dernier message: 19/05/2008, 16h51
  3. cryptage/decryptage, comment faire?
    Par bossun dans le forum Général Dotnet
    Réponses: 6
    Dernier message: 24/04/2008, 17h07
  4. Cryptage/Decryptage de String
    Par aswat dans le forum Sécurité
    Réponses: 12
    Dernier message: 27/08/2007, 16h05
  5. [VB]Cryptage/decryptage
    Par Tyrael62 dans le forum VB 6 et antérieur
    Réponses: 14
    Dernier message: 25/01/2006, 18h57

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