| 1 package fr.jayasoft.ivy.util; 2 3 import java.io.BufferedReader ; 4 import java.io.File ; 5 import java.io.FileInputStream ; 6 import java.io.FileReader ; 7 import java.io.IOException ; 8 import java.io.InputStream ; 9 import java.security.MessageDigest ; 10 import java.security.NoSuchAlgorithmException ; 11 import java.util.HashMap ; 12 import java.util.Map ; 13 14 public class ChecksumHelper { 15 16 private static Map _algorithms = new HashMap (); 17 static { 18 _algorithms.put("md5", "MD5"); 19 _algorithms.put("sha1", "SHA-1"); 20 } 21 22 public static boolean check(File dest, File checksumFile, String algorithm) throws IOException { 23 String csFileContent = FileUtil.readEntirely(new BufferedReader (new FileReader (checksumFile))).trim().toLowerCase(); 24 String expected; 25 int spaceIndex = csFileContent.indexOf(' '); 26 if (spaceIndex != -1) { 27 expected = csFileContent.substring(0, spaceIndex); 28 } else { 29 expected = csFileContent; 30 } 31 32 String computed = computeAsString(dest, algorithm).trim().toLowerCase(); 33 return expected.equals(computed); 34 } 35 36 public static String computeAsString(File f, String algorithm) throws IOException { 37 return byteArrayToHexString(compute(f, algorithm)); 38 } 39 40 private static byte[] compute(File f, String algorithm) throws IOException { 41 InputStream is = new FileInputStream (f); 42 43 try { 44 MessageDigest md = getMessageDigest(algorithm); 45 md.reset(); 46 47 byte[] buf = new byte[2048]; 48 int len = 0; 49 while ((len = is.read(buf)) != -1) { 50 md.update(buf, 0, len); 51 } 52 return md.digest(); 53 } finally { 54 is.close(); 55 } 56 } 57 58 59 private static MessageDigest getMessageDigest(String algorithm) { 60 String mdAlgorithm = (String ) _algorithms.get(algorithm); 61 if (mdAlgorithm == null) { 62 throw new IllegalArgumentException ("unknown algorithm "+algorithm); 63 } 64 try { 65 return MessageDigest.getInstance(mdAlgorithm); 66 } catch (NoSuchAlgorithmException e) { 67 throw new IllegalArgumentException ("unknown algorithm "+algorithm); 68 } 69 } 70 71 72 private final static char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 74 79 public static String byteArrayToHexString(byte in[]) { 80 byte ch = 0x00; 81 82 if (in == null || in.length <= 0) { 83 return null; 84 } 85 86 StringBuffer out = new StringBuffer (in.length * 2); 87 88 for (int i = 0; i < in.length; i++) { 89 ch = (byte) (in[i] & 0xF0); ch = (byte) (ch >>> 4); ch = (byte) (ch & 0x0F); 93 out.append(CHARS[ (int) ch]); ch = (byte) (in[i] & 0x0F); out.append(CHARS[ (int) ch]); } 97 98 return out.toString(); 99 } 100 101 } 102 | Popular Tags |