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

Développement Web en Java Discussion :

Besoin d'aide pour RSA


Sujet :

Développement Web en Java

  1. #1
    Nouveau Candidat au Club
    Inscrit en
    Novembre 2010
    Messages
    1
    Détails du profil
    Informations forums :
    Inscription : Novembre 2010
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Besoin d'aide pour RSA
    Bonjour tout le monde , vu que c'est mon premier poste je vais en profiter pour me presenter brièvement :

    moi c'est Issam 21 ans etudiant en informatique

    mon problème est le suivant :

    j'ai fini de développer une application de cryptage/decryptage en RSA . la clé publique et privé est généré automatiquement en format 512 bit.
    je voudrais enduite implenter ce programme dans une application d'envoi et de réception de SMS en J2ME .
    Mais voila, vu que la clé change a chaque foie impossible de décrypter un message sur une autre application.

    la première solution serais d'utiliser un keystore pour sauvegarder mes clé mais son fonctionnement m'est complètement inconnu.

    la 2eme est que je force le choix des clés publiques et privée (solution idéale ) mais cela est-il possible ?

    voila le code en question
    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
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package myrsa;
    
    
    import java.io.*;
    import java.math.*;
    import javax.crypto.*;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import java.math.BigInteger;
    
    /**
     * permet un cryptage decryptage RSA
     * @author Issam
     */
    
    
    public class MyRsa {
    
    public final static int KEY_SIZE = 512; // [512..2048]
    private RSAPublicKey publicKey;
    private RSAPrivateKey privateKey;
    
    
    public MyRsa() {
    }
    
    public void generateKeyPair() {
    try {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(KEY_SIZE, new SecureRandom());
    KeyPair kp = keyPairGen.generateKeyPair();
    publicKey = (RSAPublicKey)kp.getPublic();
    
    privateKey = (RSAPrivateKey)kp.getPrivate();
    
    
    
    }
    catch (Exception e) {System.out.println(e);}
    }
    
    
    public RSAPublicKey getPublicKey() {
    return publicKey;
    }
    
    
    public byte[] getPublicKeyInBytes() {
    return publicKey.getEncoded();
    }
    
    
    public RSAPrivateKey getPrivateKey() {
    return privateKey;
    }
    
    
    public byte[] getPrivateKeyInBytes() {
    return privateKey.getEncoded();
    }
    
    
    public void setPublicKey(RSAPublicKey publicKey) {
    this.publicKey = publicKey;
    }
    
    
    public void setPublicKey(byte[] publicKeyData) {
    try {
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyData);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    publicKey = (RSAPublicKey)keyFactory.generatePublic(publicKeySpec);
    }
    catch (Exception e) {System.out.println(e);}
    }
    
    
    public void setPrivateKey(RSAPrivateKey privateKey) {
    this.privateKey = privateKey;
    }
    
    
    public void setPrivateKey(byte[] privateKeyData) {
    try {
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyData);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privateKey = (RSAPrivateKey)keyFactory.generatePrivate(privateKeySpec);
    }
    catch (Exception e) {System.out.println(e);}
    }
    
    
    
    
    public byte[] crypt(byte[] plaintext) {
    return crypt(new BigInteger(addOneByte(plaintext))).toByteArray();
    
    }
    
    
    public byte[] crypt(String plaintext) {
    return crypt(plaintext.getBytes());
    }
    
    
    public byte[] decryptInBytes(byte[] ciphertext) {
    return removeOneByte(decrypt(new BigInteger(ciphertext)).toByteArray());
    }
    
    
    public String decryptInString(byte[] ciphertext) {
    return new String(decryptInBytes(ciphertext));
    }
    
    
    /**
    * Cette méthode permet de tester le bon fonctionnement des autres.
    */
    public static void main(String[] args) {
    String plaintext = "voici le text";
    System.out.println("plaintext = " + plaintext);
    MyRsa rsa = new MyRsa();
    rsa.generateKeyPair();
    
    byte[] publicKey = rsa.getPublicKeyInBytes();
    byte[] privateKey = rsa.getPrivateKeyInBytes();
    byte[] ciphertext = rsa.crypt(plaintext);
    
    System.out.println("ciphertext = " + new BigInteger(ciphertext));
    
    
    
    //rsa.setPublicKey(publicKey);
    //rsa.setPrivateKey(privateKey);
    String plaintext2 = rsa.decryptInString(ciphertext);
    System.out.println("plaintext2 = " + plaintext2);
    if (!plaintext2.equals(plaintext)) System.out.println("Error: plaintext2 != plaintext");
    }
    
    
    private BigInteger crypt(BigInteger plaintext) {
    return plaintext.modPow(publicKey.getPublicExponent(), publicKey.getModulus());
    }
    
    
    private BigInteger decrypt(BigInteger ciphertext) {
    return ciphertext.modPow(privateKey.getPrivateExponent(), privateKey.getModulus());
    }
    
    
    /**
    * Ajoute un byte de valeur 1 au début du message afin d'éviter que ce dernier
    * ne corresponde pas à un nombre négatif lorsqu'il sera transformé en
    * BigInteger.
    */
    private static byte[] addOneByte(byte[] input) {
    byte[] result = new byte[input.length+1];
    result[0] = 1;
    for (int i = 0; i < input.length; i++) {
    result[i+1] = input[i];
    }
    return result;
    }
    
    
    /**
    * Retire le byte ajouté par la méthode addOneByte.
    */
    private static byte[] removeOneByte(byte[] input) {
    byte[] result = new byte[input.length-1];
    for (int i = 0; i < result.length; i++) {
    result[i] = input[i+1];
    }
    return result;
    }
    }
    merci d'avance.
    cordialement,

  2. #2
    Nouveau Candidat au Club
    Inscrit en
    Mars 2008
    Messages
    1
    Détails du profil
    Informations forums :
    Inscription : Mars 2008
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Fixer les private & public key
    Bonjour,
    Voici une façon pour fixer les deux clés private & public, et les sauvegarder physiquement


    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
      public void generateKeyPair() {
            try {
                KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
                keyPairGen.initialize(KEY_SIZE, new SecureRandom());
                KeyPair kp = keyPairGen.generateKeyPair();
                publicKey = (RSAPublicKey) kp.getPublic();
                privateKey = (RSAPrivateKey) kp.getPrivate();
     
                KeyFactory fact = KeyFactory.getInstance("RSA");
                RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                        RSAPublicKeySpec.class);
                RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                        RSAPrivateKeySpec.class);
     
                saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
                saveToFile("private.key", priv.getModulus(), priv
                        .getPrivateExponent());
     
     
            } catch (Exception e) {
                System.out.println(e);
            }
        }
     
      public void saveToFile(String fileName, BigInteger mod, BigInteger exp)
                throws IOException {
            ObjectOutputStream oout = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(fileName)));
            try {
                oout.writeObject(mod);
                oout.writeObject(exp);
            } catch (Exception e) {
                throw new IOException("Unexpected error", e);
            } finally {
                oout.close();
            }
        }
     
        PublicKey ReadPublicKeyFromFile(String keyFileName) throws IOException {
            InputStream in = RSACrypt.class.getClassLoader().getResourceAsStream(keyFileName);
            ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
                    in));
            try {
                BigInteger m = (BigInteger) oin.readObject();
                BigInteger e = (BigInteger) oin.readObject();
                RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
                KeyFactory fact = KeyFactory.getInstance("RSA");
                PublicKey pubKey = fact.generatePublic(keySpec);
                return pubKey;
            } catch (Exception e) {
                throw new RuntimeException("Spurious serialisation error", e);
            } finally {
                oin.close();
            }
        }
     
        public byte[] RSAEncrypt(byte[] data) throws InvalidKeyException,
                IOException, NoSuchAlgorithmException, NoSuchPaddingException,
                IllegalBlockSizeException, BadPaddingException {
            PublicKey pubKey = ReadPublicKeyFromFile("/chemain/public.key");
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] cipherData = cipher.doFinal(data);
            return cipherData;
        }
        PrivateKey ReadPrivateKeyFromFile(String keyFileName) throws IOException {
            InputStream in = RSACrypt.class.getClassLoader().getResourceAsStream(keyFileName);
            ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
                    in));
            try {
                BigInteger m = (BigInteger) oin.readObject();
                BigInteger e = (BigInteger) oin.readObject();
                RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
                KeyFactory fact = KeyFactory.getInstance("RSA");
                PrivateKey priKey = fact.generatePrivate(keySpec);
                return priKey;
            } catch (Exception e) {
                throw new RuntimeException("Spurious serialisation error", e);
            } finally {
                oin.close();
            }
        }
     
        public byte[] RSADecrypt(byte[] data) throws InvalidKeyException,
                IOException, NoSuchAlgorithmException, NoSuchPaddingException,
                IllegalBlockSizeException, BadPaddingException {
            PrivateKey priKey = ReadPrivateKeyFromFile("/chemin/private.key");
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] cipherData = cipher.doFinal(data);
            return cipherData;
        }
     
        public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
     
    //  Ces deux ligne ci-dessous sont utilisées une seule fois
    //  pour la création des deux clés privée et publique
    //        RSACrypt rsa = new RSACrypt();
    //        rsa.generateKeyPair();
    }

Discussions similaires

  1. Besoin d'aide pour utiliser RSA
    Par AsmCode dans le forum Sécurité
    Réponses: 1
    Dernier message: 26/08/2007, 19h11
  2. besoin d'aide pour le composant DBComboBox
    Par jane2002 dans le forum Bases de données
    Réponses: 8
    Dernier message: 28/02/2004, 19h01
  3. [Kylix] besoin d'aide pour installer kylix3
    Par Sph@x dans le forum EDI
    Réponses: 3
    Dernier message: 11/02/2004, 13h53
  4. [TP]besoin d'aide pour commandes inconnues
    Par Upal dans le forum Turbo Pascal
    Réponses: 15
    Dernier message: 03/10/2002, 10h48
  5. Besoin d'aide pour l'I.A. d'un puissance 4
    Par Anonymous dans le forum C
    Réponses: 2
    Dernier message: 25/04/2002, 17h05

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