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 :

Cipher Input/Output Stream


Sujet :

Sécurité Java

  1. #1
    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 Cipher Input/Output Stream
    Salut à tous,

    voilà je voudrais écrire/lire des objets directement en crypté dans un fichier (pas els écrire en clair avec ObjectOuputStream puis tout crypter), et je me suis pour cela dirigé vers CipherOuput/InputStream.

    Mais ça n'écrit pas des objets, bien évidement, ça écrit des bytes. Ma question est comment faire pour les écrire directement en faisant un truc du style out.writeObject(monObjet) pour que ça marche "tout seul".

    Le code suivant par exemple ne fonctionne pas...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Cipher cipher = Cipher.getInstance("RSA");        
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
     
    CipherOutputStream crypter = new CipherOutputStream(new FileOutputStream(outputFileName), cipher);
    ObjectOutputStream out = new ObjectOutputStream(crypter);
     
    out.writeObject(monObjet);
     
    out.close();
    En fait ça écrit rien dans le fihcier (et évidement ça narrange pas la lecture ;-) ).


    Ma question est donc : comment, de cette manière, arriver à écrire / lire directement des objets en crypté?

  2. #2
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    A priori ton code devrait marcher.

    J'ai testé le code suivant :
    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
    Test t1 = new Test();
    Test t2 = new Test("cinq", 5);
     
    KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    pairgen.initialize(2048, random);
    KeyPair keyPair = pairgen.generateKeyPair();
     
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    CipherOutputStream crypter = new CipherOutputStream(new FileOutputStream("test.ciphered"), cipher);
    ObjectOutputStream out = new ObjectOutputStream(crypter);
    out.writeObject(t1);
    out.writeObject(t2);
    out.close();
     
    cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
    CipherInputStream decrypter = new CipherInputStream(new FileInputStream("test.ciphered"), cipher);
    ObjectInputStream in = new ObjectInputStream(decrypter);
    System.out.println(((Test) in.readObject()).toString());
    System.out.println(((Test) in.readObject()).toString());
    in.close();
    (Rq : exceptions non gérées) avec la classe Test
    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
    public class Test implements Serializable {
        private static final long serialVersionUID = 1L;
     
        private String label;
        private int value;
     
        public Test() {
            this("Test", 0);
        }
        public Test(String label, int value) {
            this.label = label;
            this.value = value;
        }
     
        public String toString() {
            return label + " " + value;
        }
    }
    Et cela marche. J'obtiens bien un fichier crypté, et la sortie standard m'affiche (désérialisation)
    Test 0
    cinq 5
    Peut-être que ton problème vient du type de ton objet à sérialiser ?
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  3. #3
    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
    Ben non ce que j'écris implémente bien Sérializable, aucune exception lancée à l'écriture... Mais j'écris rien dans le fichier...

    Donc à la lecture évidement j'ai une EOF mais c'est pas le problème.

  4. #4
    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
    Strange en effetça ton code fonctionne également chez moi (sans blague lol) mais pas celui de mon application...

    voici le code :

    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
     
    Student std = new Student("Romain","Aa123456", "adress", 20, 
                    new StudyYear(2, "Info", ""));
     
            ManagSys sys = new ManagSys();
     
            sys.addStudent(std);
            try
            {
     
                sys.save("ManagSys.mgsys", "public.key");
            }
            catch (InvalidKeyException ex)
            {
                ex.printStackTrace();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
            catch (ClassNotFoundException ex)
            {
                ex.printStackTrace();
            }
     
            ManagSys sys2 = ManagSys.load("ManagSys.mgsys", "private.key");
            System.out.println(sys2.getStudents().get(0));

    et le code de sauvegarde :
    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
     
    public void save(String outputFileName, String publicRSAKeyInputFileName) 
            throws IOException, ClassNotFoundException, InvalidKeyException    
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicRSAKeyInputFileName));
            Key publicKey = (Key)keyIn.readObject();
            keyIn.close();
     
            Cipher cipher = null;
            try
            {
                cipher = Cipher.getInstance("RSA");
            }
            catch(NoSuchAlgorithmException e)
            {}
            catch(NoSuchPaddingException e)
            {
                e.printStackTrace();
            }
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
     
            CipherOutputStream crypter = new CipherOutputStream(new FileOutputStream(outputFileName), cipher);
            ObjectOutputStream out = null;
            try
            {
                out =new ObjectOutputStream(crypter);
                out.writeObject(students);
                out.writeObject(teachers);
                out.writeObject(secretaries);
                out.writeObject(courses);
                out.writeObject(studyYears);
                out.writeObject(fiches);
            }
            finally
            {
                if(out != null)
                    out.close();
            }
    }

    et voilà, mais ça marche pas...

  5. #5
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    Les seules différences avec mon code de test sont :
    • la clé lue dans un fichier
    • le type des données sérialisées
    Il faudrait faire quelques essais pour essayer de localiser plus précisemment la cause du problème.
    • en utilisant une paire de clés générée aléatoirement (cf mon code test).
    • en ne sérialisant qu'un seul attribut à la fois (faire un essai pour students, un pour teachers, etc).
    A priori, les attributs à sérialiser de la classe Managsys semblent être des Lists. Les objets contenus dans ces Lists sont-ils bien Serializables ?
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  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
    L'utilisation de clés générées aléatoirement n'améliore rien.
    J'ai faut un essaie avec StudyYear, classe ne souffrant d'aucune dépendance avec d'autres classes de ma librairie.
    Je crée donc juste une StudyYear, et je l'écris avec le code que tu utilise, mais le résulatt est le même : un fichier de 0 ko et aucune exception...

  7. #7
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    Peux-tu poster le code de la classe StudyYear ?
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  8. #8
    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
    Bien sur

    E,n fait jai travaillé sur le problème et il s'avère que le problème vient de l'héritage entre mes classes. Voici les codes :

    Classe Entity dont StudyYear hérite :

    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
     
    //package database;
     
    import java.io.Serializable;
    import java.util.concurrent.locks.*;
     
    /**
     * This class models a Entity object
     */
    public abstract class Entity implements Serializable
    {
        private String name;
        private String desc;
        private String id;
        private Lock lock = new ReentrantLock();
     
        /**
         * Constructs an empty Entity
         */
        protected Entity()
        {
            this(null,null);
        }
     
        /**
         * Constructs an Entity object
         * @param name the name of the entity
         */
        public Entity(String name)
        {
            this(name, null);
        }
     
        /**
         * Constructs an Entity object
         * @param name the name of the entity
         * @param desc of smal description of the entity
         */
        public Entity(String name, String desc)
        {
            this.name = name;
            this.desc = desc;
        }
     
        /**
         * Gets the name of the entity
         * @return name the name
         */
        public String getName()
        {
            return name;
        }
     
        /**
         * Sets the name of the entity
         * @param name the new name
         */
        public void setName(String name)
        {
            this.name = name;
        }
     
        /**
         * Gets the description of the entity
         * @return desc the description
         */
        public String getDesc()
        {
            return desc;
        }
     
        /**
         * Sets the description of the entity
         * @param desc the new description
         */
        public void setDesc(String desc)
        {
            this.desc = desc;
        }
     
        /**
         * Gets the identification of the entity.
         * This id is generated automatically when an entity is created.
         * Each entity has a unique id
         * @return id the id
         */
        public String getId()
        {
            return id;
        }
     
        /**
         * Sets the id of the entity
         * @param new id the new id
         */
        protected void setId(String newId)
        {
            id = newId;
        }
     
        /**
         * Indicates whether some an other entity  is "equals to" this one.
         * @return true if it is, false else
         */
        public boolean equals(Entity other)
        {
            return id.equals(other.getId());
        }
     
        /**
         * Gets the lock
         * @return lock the lock
         */
        public Lock getLock()
        {
            return lock;
        }
    }

    Classe StudyYear :

    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
     
    //package database;
     
    import java.io.Serializable;
    import security.Securer;
     
    /**
     * This class models a StudyYear object
     */
    public class StudyYear extends Entity implements Serializable
    {
        private int year;
        private String section;
        private String option;
        private static int nbr = 1;
     
        public StudyYear()
        {}
     
        public StudyYear(int year, String section, String option, String id)
        {
            this.year = year;
            this.section = section;
            this.option = option;
            this.setId(id);
        }
     
        /**
         * Constructs a StudyYear object with initial values
         * @param year the year of the study year
         * @param section the section of the study year
         * @param option the option of the study year
         */
        public StudyYear(int year, String section, String option)
        {
            super();
            if(year == 0 || !Securer.isValidString(section))
                throw new IllegalArgumentException("Year or section cannot " +
                        "be null");
            this.year = year;
            this.section = section;
            if(option == null)
                option = "";
            else
                this.option = option;
            this.setId("yr" + nbr);
            nbr++;
     
     
            String name = ""+year;
            name += year == 1 ? "ère" : "ème";
            name += " " + section + ", option " + option;
            super.setName(name);
            super.setDesc("Study year " + name);
        }
     
        /**
         * Gets the year of the study year
         * @return  year the year of the study year
         */
        public int getYear()
        {
            super.getLock().lock();
            try
            {
                return year;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
     
        /**
         * Sets the year of a study year
         * @param year the new year
         */
        public void setYear(int year)
        {
            super.getLock().lock();
            try
            {
                this.year = year;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
     
        /**
         * Gets the section of the study year
         * @return  section the section of the study year
         */
        public String getSection()
        {
            super.getLock().lock();
            try
            {
                return section;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
     
        /**
         * Sets the section of a study year
         * @param section the new section
         */
        public void setSection(String section)
        {
            super.getLock().lock();
            try
            {
                this.section = section;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
     
        /**
         * Gets the option of the study year
         * @return  option the section of the option year
         */
        public String getOption()
        {
            super.getLock().lock();
            try
            {
                return option;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
     
        /**
         * Sets the option of a study year
         * @param option the new option
         */
        public void setOption(String option)
        {
            super.getLock().lock();
            try
            {
                this.option = option;
            }
            finally
            {
                super.getLock().unlock();
            }
        }
    }

    Et voici la classe de test vous l'avez, je la remets au cas où y aurait des modifs :
    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
     
    public class CryptTest2
    {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException, ClassNotFoundException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
        {
            StudyYear sty = new StudyYear(2,"Math","Informatique");
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(2048, random);
            KeyPair keyPair = pairgen.generateKeyPair();
     
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
            CipherOutputStream crypter = new CipherOutputStream(new FileOutputStream("stdy.crypted"), cipher);
            //FileOutputStream crypter = new FileOutputStream("stdy.crypted");
            ObjectOutputStream out = new ObjectOutputStream(crypter);
     
            out.writeObject(sty);
            out.close();             
       }
    }

    Je rapelle donc que le problème majeur est l'écriture / lecture des instances des sous-classes de Entity.

  9. #9
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    J'avoue ne pas savoir comment résoudre ce problème.
    La classe StudyYear se sérialise correctement en "mode normal" (sans cryptage) mais j'ai le même problème lors de l'utilisation du CipherOutputStream (fichier de sortie vide).

    Peut-être un rapport avec
    Citation Envoyé par Javadoc
    It is crucial for a programmer using this class not to use methods that are not defined or overriden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherOutputStream.
    mais là encore je confesse mon ignorance sur ce point .
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  10. #10
    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
    Oui, c'est ce que j'ai pensé aussi en regardant la doc : ObjectOutputStream prenant en paramètres un OutputStream et comme j'utilise pour cela un CipherOutputStream, il se peut que ObjectOutputStream appelle des méthode de OutputStream qui ne sont pas réimplémentées dans CipherOutputStream, rasion pour laquelle le crytage échoue, mais ce n'est qu'une supposition.

    Il est tout de même étrange que lorsqu'on supprime les liens d'héritage, StudyYear se sérialize correctement...

    Si quelqu'un a une idée, même si elle ne corrige pas le code, pour résoudre le problème initial, je suis à l'écoute.

  11. #11
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    Chose bizarre, la classe se sérialize correctement avec l'algorithme DES.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    StudyYear sty = new StudyYear(2,"Math","Informatique");
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    ObjectOutputStream oos = new ObjectOutputStream(new CipherOutputStream(new FileOutputStream(filename), cipher));
    oos.writeObject(sty);
    oos.close();
    Le problème semble donc venir de l'utilisation de l'algorithme RSA. Mais bon, je ne vois toujours pas le pourquoi du comment .
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  12. #12
    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
    Ca se sérialize même avec l'héritage? Parce quitte à changer d'algorithlme de cryptage ben c'est pas grave lol, je chercherai plus tard sur le RSA...

  13. #13
    Expert confirmé
    Avatar de le y@m's
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2005
    Messages
    2 636
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Février 2005
    Messages : 2 636
    Par défaut
    Apparement oui (tout du moins le fichier n'est pas vide mais je n'ai pas testé la désérialisation).
    Je ne répondrai à aucune question technique par MP.

    Pensez aux Tutoriels et aux FAQs avant de poster ;) (pour le java il y a aussi JavaSearch), n'oubliez pas non plus la fonction Rechercher.
    Enfin, quand une solution a été trouvée à votre problème
    pensez au tag :resolu:

    Cours Dvp : http://ydisanto.developpez.com
    Blog : http://yann-disanto.blogspot.com/
    Page perso : http://yann-disanto.fr

  14. #14
    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
    Cool alors, le seul problème c'est que le cryptage est symétrique... Pour changer ça : facile : je crypte la clé DES en RSA, j'obtiens ainsi deux clés. Je teste ça et je poste dès que c'est fait.

  15. #15
    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
    Pour ceux que ça interesse, on procède de la manière suivante :
    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
     
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecureRandom random = new SecureRandom();
    keygen.init(random);
    SecretKey key = keygen.generateKey();
     
    //emballe avec la clé publique RSA
    ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(keyFileName)); //keyFileName contient une clé publique RSA
    Key publicKey = (Key)keyIn.readObject();
    keyIn.close();
     
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.WRAP_MODE, publicKey);
    byte[] wrappedKey = cipher.wrap(key);
    DataOutputStream out = new DataOutputStream(new FileOutputStream(outputFileName));
    out.writeInt(wrappedKey.length);
    out.write(wrappedKey);

    RQ : dans mon cas, mes objets se sérialisent bien avec l'algorithme AES, bien plus sécurisé que le DES (AES symétrique aussi), j'emploie donc celui-là.

  16. #16
    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
    Bon, y a un stress dans l'emballage/déballage de la clé, impossible d'écrire tout dans le même fichier si j'utilise un CipherOutputStream (la clé dans le fichier serait cryptée deux fois), j'écris donc dans des fichiers séparés.

    Voici les classes :
    Stream output :
    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
     
    /*
     * SecureObjectOutputStream.java
     *
     * Created on 5 mai 2007, 11:04
     *
     */
     
    package security;
     
    import java.io.DataOutputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.security.InvalidKeyException;
    import java.security.Key;
    import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
     
    /**
     * This class models a SecureObjectOutputStream object that will be able to
     * @author Absil Romain
     */
    public class RSASecureObjectOutputStream
    {
        private SecretKey secretKey;
        private Key publicKey;
        private ObjectOutputStream out;
        private String cryptedAESKey;
     
        public RSASecureObjectOutputStream(String outputFileName, 
                String publicRSAKeyInputFileName, String cryptedAESKey)
            throws FileNotFoundException, IOException, ClassNotFoundException, 
                InvalidKeyException
        {
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(publicRSAKeyInputFileName));
            this.publicKey = (Key)keyIn.readObject();
            keyIn.close();
     
            this.cryptedAESKey = cryptedAESKey;
            this.publicKey = publicKey;
            this.cryptedAESKey = cryptedAESKey;
     
            KeyGenerator keygen = null;
            Cipher cipher = null;
     
            try
            {
                keygen = KeyGenerator.getInstance("AES");
                cipher = Cipher.getInstance("AES");
            } 
            catch (Exception ex)//jamais lancé
            {}
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            this.secretKey = keygen.generateKey();
     
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
     
            this.out = new ObjectOutputStream(
                    new CipherOutputStream(
                        new FileOutputStream(outputFileName), cipher));
     
        }
     
        public void writeObject(Object o) throws IOException
        {
            out.writeObject(o);
        }
     
        public void close() throws IOException
        {
            try
            {
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.WRAP_MODE, publicKey);
                byte[] wrappedKey = cipher.wrap(secretKey);
                DataOutputStream out = new DataOutputStream(new FileOutputStream(cryptedAESKey));
                out.write(wrappedKey);
                out.close();
            }
            catch(Exception e)//jamais lancé
            {}
     
            out.close();
        }
    }

    Stream input :
    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
     
    /*
     * SecureObjectInputStream.java
     *
     * Created on 5 mai 2007, 11:04
     *
     */
     
    package security;
     
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.security.InvalidKeyException;
    import java.security.PrivateKey;
    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.SecretKey;
     
    /**
     * This class models a SecureObjectInputStream object that will be able to
     * @author Absil Romain
     */
    public class RSASecureObjectInputStream
    {
        private SecretKey secretKey;
        private PrivateKey privateKey;
        private ObjectInputStream in;
     
        public RSASecureObjectInputStream(String inputFileName, 
                String privateRSAKeyInputFileName, String cryptedKey) 
                    throws FileNotFoundException, IOException, InvalidKeyException,
                        ClassNotFoundException
        {
            DataInputStream in = new DataInputStream(new FileInputStream(cryptedKey));
            File f = new File(cryptedKey);
            int length = (int)f.length();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);
     
            ObjectInputStream keyIn = new ObjectInputStream(
                    new FileInputStream(privateRSAKeyInputFileName));
     
            privateKey = (PrivateKey)keyIn.readObject();
            keyIn.close();
     
            try
            {
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.UNWRAP_MODE, privateKey);            
                this.secretKey = (SecretKey)cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
     
                cipher = Cipher.getInstance("AES");
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
                this.in = new ObjectInputStream(new CipherInputStream(new FileInputStream(inputFileName), cipher));
            }
            catch(Exception e)
            {}
        }
     
        public Object readObject() throws IOException, ClassNotFoundException
        {
            return in.readObject();
        }
     
        public void close() throws IOException
        {
            in.close();
        }
    }
    La lecture / écriture avec ces flux-là crypte et décrypte correctement tous mes objets.

    RQ : il doit y avoir un réél problème avec l'algorithme RSA, car écrire une clé AES avec Objectoutput(CipherOtpout) me fait des fichiers vides aussi...

  17. #17
    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
    J'ai posté les versions finale des streams d'encryption / decryption sous ce lien :

    http://www.developpez.net/forums/sho...86#post2061086

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Fusionner 3 fichiers via Input/Output Stream
    Par Mikiya dans le forum Collection et Stream
    Réponses: 21
    Dernier message: 10/03/2011, 09h38
  2. Input-Output Stream et réseau
    Par warseb dans le forum Entrée/Sortie
    Réponses: 3
    Dernier message: 27/02/2008, 20h36
  3. supprimer un output stream
    Par anasshb dans le forum Collection et Stream
    Réponses: 1
    Dernier message: 25/05/2007, 14h14
  4. erreur input output
    Par kanzarih dans le forum Entrée/Sortie
    Réponses: 1
    Dernier message: 05/11/2006, 00h40
  5. Problème input/output fichier
    Par nenekes dans le forum Cobol
    Réponses: 3
    Dernier message: 09/09/2006, 22h54

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