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 :

Appliquer la fonction de hachage MD5 à un texte


Sujet :

Sécurité Java

  1. #1
    Membre à l'essai
    Inscrit en
    Mars 2007
    Messages
    17
    Détails du profil
    Informations forums :
    Inscription : Mars 2007
    Messages : 17
    Points : 10
    Points
    10
    Par défaut Appliquer la fonction de hachage MD5 à un texte
    salut tout le monde,
    j'aimerai appliquer la fonction de hachage MD5 sur le contenu d'un fichier
    j'ai ce code:
    //ce code permet de crypter une chaine de caractères
    //en utilisant la fonction de hachage MD5
    //Utilise des classes de sécurité

    import java.security.*;

    public class MD5
    { /*
    * Encode la chaine passé en paramètre avec l’algorithme MD5
    * @param key : la chaine à encoder
    * @return la valeur (string) hexadécimale sur 32 bits
    */

    public static String encode (String key)
    {
    byte[] uniqueKey = key.getBytes();
    byte[] hash = null;

    //------------------------------------------------------------------------------------------------

    try
    {
    // on récupère un objet qui permettra de crypter la chaine
    hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
    }
    catch (NoSuchAlgorithmException e) {throw new Error("no MD5 support in this VM");}

    //-------------------------------------------------------------------------------------------------

    StringBuffer hashString = new StringBuffer();
    for (int i = 0; i < hash.length; ++i)
    {
    String hex = Integer.toHexString(hash[i]);
    if (hex.length() == 1)
    {
    hashString.append(0);
    hashString.append(hex.charAt(hex.length() - 1));
    }
    else {hashString.append(hex.substring(hex.length() - 2));}
    }
    return hashString.toString();
    }
    }
    ce code marche bien avec le nom du fichier donné comme parametre mais je veux l'appliquer sur le contenu du fichier;
    comment je peux pécuperer le contenu d'un fichier avec java?
    je sais que cette méthode traite un tableau de byte. mais je sais pas comment passer le contenu du fichier sous la forme d'un tableau de byte ?
    SVP celui qui peux me répondre qu'il se manifeste le plus vite possible
    merci

  2. #2
    Membre actif
    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Mars 2002
    Messages
    192
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Architecte de système d'information

    Informations forums :
    Inscription : Mars 2002
    Messages : 192
    Points : 252
    Points
    252
    Par défaut
    Voilà un exemple
    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
    package fr.brouillard.io;
     
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
     
    public class HashFile {
    	public static byte[] calculateHash(String fileName, MessageDigest md) throws IOException {
    		byte[] buf = new byte[1024];
     
    		InputStream is = null;
    		int bytesRead = 0;
    		try {
    			is = new FileInputStream(fileName);
    			bytesRead = is.read(buf);
     
    			while (bytesRead != -1) {
    				md.update(buf, 0, bytesRead);
    				bytesRead = is.read(buf);
    			}
     
    			return md.digest();
    		} finally {
    			if (is != null) {
    				try {
    					is.close();
    				} catch (IOException e) {}
    			}
    		}
    	}
     
    	public static class HexUtil {
    	  private final static char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    	  /**
              * Convert a byte[] array to readable string format. This makes the "hex" readable!
              * @return result String buffer in String format
              * @param in byte[] buffer to convert to string format
              */
    	    public static String byteArrayToHexString(byte in[]) {
    	        byte ch = 0x00;
     
    	        if (in == null || in.length <= 0) {
    	            return "";
    	        }
     
    	        StringBuffer out = new StringBuffer(in.length * 2);
     
    	        for (int i = 0; i < in.length; i++) {
    	            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
    	            ch = (byte) (ch >>> 4); // shift the bits down
    	            ch = (byte) (ch & 0x0F); // must do this is high order bit is on!
     
    	            out.append(CHARS[ (int) ch]); // convert the nibble to a String Character
    	            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
    	            out.append(CHARS[ (int) ch]); // convert the nibble to a String Character
    	        }
     
    	        return out.toString();
    	    }	
    	}
     
    	public static void main(String[] args) {
    		try {
    			System.out.println(HexUtil.byteArrayToHexString(HashFile.calculateHash("c:/temp/test.txt", MessageDigest.getInstance("MD5"))));
    			System.out.println(HexUtil.byteArrayToHexString(HashFile.calculateHash("c:/temp/test2.txt", MessageDigest.getInstance("MD5"))));
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    Quelques tips Java & autres : mon blog

  3. #3
    Nouveau Candidat au Club
    Homme Profil pro
    hi
    Inscrit en
    Mai 2011
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : hi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2011
    Messages : 1
    Points : 1
    Points
    1
    Par défaut 776ab6a7f41688235d817e1be5e7812b
    Citation Envoyé par McFoggy Voir le message
    Voilà un exemple
    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
    package fr.brouillard.io;
     
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
     
    public class HashFile {
    	public static byte[] calculateHash(String fileName, MessageDigest md) throws IOException {
    		byte[] buf = new byte[1024];
     
    		InputStream is = null;
    		int bytesRead = 0;
    		try {
    			is = new FileInputStream(fileName);
    			bytesRead = is.read(buf);
     
    			while (bytesRead != -1) {
    				md.update(buf, 0, bytesRead);
    				bytesRead = is.read(buf);
    			}
     
    			return md.digest();
    		} finally {
    			if (is != null) {
    				try {
    					is.close();
    				} catch (IOException e) {}
    			}
    		}
    	}
     
    	public static class HexUtil {
    	  private final static char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    	  /**
              * Convert a byte[] array to readable string format. This makes the "hex" readable!
              * @return result String buffer in String format
              * @param in byte[] buffer to convert to string format
              */
    	    public static String byteArrayToHexString(byte in[]) {
    	        byte ch = 0x00;
     
    	        if (in == null || in.length <= 0) {
    	            return "";
    	        }
     
    	        StringBuffer out = new StringBuffer(in.length * 2);
     
    	        for (int i = 0; i < in.length; i++) {
    	            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
    	            ch = (byte) (ch >>> 4); // shift the bits down
    	            ch = (byte) (ch & 0x0F); // must do this is high order bit is on!
     
    	            out.append(CHARS[ (int) ch]); // convert the nibble to a String Character
    	            ch = (byte) (in[i] & 0x0F); // Strip off low nibble
    	            out.append(CHARS[ (int) ch]); // convert the nibble to a String Character
    	        }
     
    	        return out.toString();
    	    }	
    	}
     
    	public static void main(String[] args) {
    		try {
    			System.out.println(HexUtil.byteArrayToHexString(HashFile.calculateHash("c:/temp/test.txt", MessageDigest.getInstance("MD5"))));
    			System.out.println(HexUtil.byteArrayToHexString(HashFile.calculateHash("c:/temp/test2.txt", MessageDigest.getInstance("MD5"))));
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }

Discussions similaires

  1. Réponses: 1
    Dernier message: 19/04/2006, 14h29
  2. [XSL]appliquer la fonction substring sur une valeur récupéré
    Par totoranky dans le forum XSL/XSLT/XPATH
    Réponses: 7
    Dernier message: 22/02/2006, 17h21
  3. [Oracle / Fonction hachage] Fonction de hachage SHA / MD5
    Par shaun_the_sheep dans le forum Oracle
    Réponses: 8
    Dernier message: 26/01/2006, 08h58
  4. Fonction de Hachage
    Par Schlada dans le forum C
    Réponses: 7
    Dernier message: 26/01/2003, 20h42
  5. Fonction de hachage
    Par killer crok dans le forum C
    Réponses: 12
    Dernier message: 02/10/2002, 09h48

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