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 :

Création et lecture d'un fichier encrypté


Sujet :

Sécurité Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Mai 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2007
    Messages : 19
    Par défaut Création et lecture d'un fichier encrypté
    Bonjour,

    Je m'arrache les cheveux sur le problème suivant: je veux encrypter un fichier et, évidemment, j'aimerai pouvoir le relire... J'ai donc commencé par faire un testeur tout simple (comprendre: codage crabeurk) que voici (j'utilise la version 1.5):

    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
     
    import java.io.*;
    import java.lang.reflect.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
     
    public class test {
     
    	public static void main(String[] args) {
    		String s1 = "The quick brown fox jumps over the lazy dog.";
    		String s2;
     
    		try {
    			SecretKey key = null;
    			Cipher encryptor = null;
    			Cipher decryptor = null;
     
    			// Récuperer une clé à partir du mot de passe
    			try {
    				key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret( new PBEKeySpec("MotDePasse".toCharArray()));
    			} catch (InvalidKeySpecException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchAlgorithmException e1) {
    				e1.printStackTrace();
    			}
     
    			// Récupérer et initialiser l'encrypteur
    			try {
    				encryptor = Cipher.getInstance("PBEWithMD5AndDES");
    				encryptor.init(Cipher.ENCRYPT_MODE, key);
    			} catch (InvalidKeyException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchAlgorithmException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchPaddingException e1) {
    				e1.printStackTrace();
    			}
     
    			// Récupérer et initialiser le décrypteur
    			try {
    				decryptor = Cipher.getInstance("PBEWithMD5AndDES");
    				AlgorithmParameters decParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");
    				decParams.init(encryptor.getParameters().getEncoded());
    				decryptor.init(Cipher.DECRYPT_MODE, key, decParams);
    			} catch (InvalidKeyException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchAlgorithmException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchPaddingException e1) {
    				e1.printStackTrace();
    			} catch (InvalidAlgorithmParameterException e1) {
    				e1.printStackTrace();
    			}
     
    			// Créer le fichier encrypté et zipé
    			FileOutputStream fos = new FileOutputStream("test.ttt");
    			CipherOutputStream cipherOut = new CipherOutputStream(fos,encryptor);
    			ObjectOutputStream out = new ObjectOutputStream(cipherOut);
    			out.writeObject(s1);
    			out.close();
    			cipherOut.close();
    			fos.close();
     
    			// Relire le fichier
    			FileInputStream fis = new FileInputStream("test.ttt");
    			CipherInputStream cipherIn = new CipherInputStream(fis,decryptor);
    			ObjectInputStream in = new ObjectInputStream(cipherIn);
    			try {
    				s2 = (String) in.readObject();
    				in.close();
    				cipherIn.close();
    				fis.close();
     
    				System.out.println(s1);
    				System.out.println(s2);
    				if (s1.equals(s2)) {
    					System.out.println("Success!");
    				}
    				else {
    					System.out.println("Failed!");
    				}
    			} catch (ClassNotFoundException e) {
    				System.out.println("Failed!");
    				e.printStackTrace();
    			}
     
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    Jusque la tout fonctionne, j'ai bien mon fichier test.ttt et la chaine s2 est bien égale à la chaine s1.

    De là, j'ai donc dérivé deux méthodes (en statique pour faire rapide) pour enregistrer un object dans un fichier et pour le lire:
    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
     
    import java.io.*;
    import java.lang.reflect.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
     
    public class test {
     
    	public static void main(String[] args) {
    		String s1 = "The quick brown fox jumps over the lazy dog.";
    		String s2;
     
    		try {
    			SecretKey key = null;
     
    			// Récuperer une clé à partir du mot de passe
    			try {
    				key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret( new PBEKeySpec("MotDePasse".toCharArray()));
    			} catch (InvalidKeySpecException e1) {
    				e1.printStackTrace();
    			} catch (NoSuchAlgorithmException e1) {
    				e1.printStackTrace();
    			}
     
    			s2 = test.load("test.ttt", key);
    		}
    		catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
     
    	static public Cipher getEncryptor(SecretKey key)
    								throws	InvalidKeyException, 
    								NoSuchAlgorithmException, 
    								NoSuchPaddingException {
    		Cipher encryptor = Cipher.getInstance("PBEWithMD5AndDES");
    		encryptor.init(Cipher.ENCRYPT_MODE, key);
    		return encryptor;
    	}
     
    	static public Cipher getDecryptor(Cipher encryptor, SecretKey key)
    								throws	NoSuchAlgorithmException, 
    								NoSuchPaddingException,
    								InvalidKeyException,
    								InvalidAlgorithmParameterException,
    								IOException {
    		Cipher decryptor = Cipher.getInstance("PBEWithMD5AndDES");
    		AlgorithmParameters decParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");
    		decParams.init(encryptor.getParameters().getEncoded());
    		decryptor.init(Cipher.DECRYPT_MODE, key, decParams);
    		return decryptor;
    	}
     
    	static public Object load(String fileName, SecretKey key ) throws FileNotFoundException, IOException {
     
    		System.out.println("Load("+fileName+")");
    		for(byte b : key.getEncoded()) {
    			System.out.print((char)b);
    		}
    		System.out.println();
     
    		Object result = null;
    		Cipher decryptor = null;
    		try {
    			decryptor = getDecryptor(getEncryptor(key),key);
    		}
    		catch(Exception e) {
    			e.printStackTrace();
    		}
    		FileInputStream fichier = new FileInputStream(fileName);
    		CipherInputStream cipher = new CipherInputStream(fichier,decryptor);
    		ObjectInputStream ois = new ObjectInputStream(cipher);
    		try {
    			result = ois.readObject();
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		}
    		ois.close();
    		cipher.close();
    		fichier.close();
    		return result;
    	}
     
    	static public void save(Object o, String fileName, SecretKey key ) throws InvalidKeyException, FileNotFoundException, IOException {
     
    		System.out.println("Save");
    		for(byte b : key.getEncoded()) {
    			System.out.print((char)b);
    		}
    		System.out.println();
     
    		Cipher encryptor = null;
     
    		try {
    			encryptor = getEncryptor(key);
    		}
    		catch(Exception e) {
    			e.printStackTrace();
    		}
    		FileOutputStream fichier = new FileOutputStream(fileName);
    		CipherOutputStream cipher = new CipherOutputStream(fichier,encryptor);
    		ObjectOutputStream oos = new ObjectOutputStream(cipher);
    		oos.writeObject(o);
    		oos.close();
    		cipher.close();
    		fichier.close();
    	}
    Et là j'ai une exception:
    java.io.StreamCorruptedException: invalid stream header
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at test.load
    qui est levée sur l'ouverture du ObjectInputStream:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    		ObjectInputStream ois = new ObjectInputStream(cipher);
    Quelqu'un pourrait me donner une idée?

  2. #2
    Membre averti
    Profil pro
    Inscrit en
    Mai 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2007
    Messages : 19
    Par défaut
    Bon ok, j'ai trouvé pourquoi (même si j'ai pas encore trouvé le comment)... Donc pour décoder, il faut simplement que le décodeur soit initialisé avec les paramètres de l'encodeur. Or ces paramètres, bien que cachés par l'interface de la classe, vont au delà du simple mot de passe et peuvent être aléatoires. Donc si on crée une paire encodeur décodeur (comme c'est fait dans le premier cas), tout fonctionne, mais sinon, ca marche po!
    Il faudrait donc soit sauvegarder les paramètres dans le/un fichier, mais ca ne me plait pas, soit initialiser à la main l'ensemble des paramètres, mais la je sais pas encore comment faire...

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Mai 2007
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2007
    Messages : 19
    Par défaut
    La solution: Utiliser des paramètres fixes!

    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
     
    	static private final byte[] SALT  = new byte[] {0,0,0,0,0,0,0,0};
    	static private final int ITERATION = 3;
     
    	static public Cipher getEncryptor(SecretKey key)
    								throws	InvalidKeyException, 
    								NoSuchAlgorithmException, 
    								InvalidParameterSpecException,
    								InvalidAlgorithmParameterException,
    								NoSuchPaddingException {
    		AlgorithmParameters encParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");
    		encParams.init(new PBEParameterSpec(SALT,ITERATION));
    		Cipher encryptor = Cipher.getInstance("PBEWithMD5AndDES");
    		encryptor.init(Cipher.ENCRYPT_MODE, key,encParams);
    		return encryptor;
    	}
     
    	static public Cipher getDecryptor(Cipher encryptor, SecretKey key)
    								throws	NoSuchAlgorithmException, 
    								NoSuchPaddingException,
    								InvalidKeyException,
    								InvalidParameterSpecException,
    								InvalidAlgorithmParameterException,
    								IOException {
    		AlgorithmParameters decParams = AlgorithmParameters.getInstance("PBEWithMD5AndDES");
    		decParams.init(new PBEParameterSpec(SALT,ITERATION));
    		Cipher decryptor = Cipher.getInstance("PBEWithMD5AndDES");
    		decryptor.init(Cipher.DECRYPT_MODE, key, decParams);
    		return decryptor;
    	}
    Le reste du code ne change pas...

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

Discussions similaires

  1. [Débutant] Exception création / lecture d'un fichier
    Par Popi_ dans le forum C#
    Réponses: 3
    Dernier message: 25/02/2015, 11h43
  2. Création et lecture de fichier ini
    Par batmat86 dans le forum C++Builder
    Réponses: 4
    Dernier message: 06/12/2008, 23h46
  3. Réponses: 3
    Dernier message: 28/12/2007, 19h57
  4. [langage] Optimiser la lecture d'un fichier
    Par And_the_problem_is dans le forum Langage
    Réponses: 4
    Dernier message: 05/02/2003, 08h54
  5. [langage] Optimiser la lecture d'un fichier
    Par And_the_problem_is dans le forum Langage
    Réponses: 2
    Dernier message: 11/06/2002, 10h24

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