1 18 19 package org.apache.tools.ant.types.selectors.modifiedselector; 20 21 22 import java.io.File ; 23 import java.io.FileInputStream ; 24 import java.security.DigestInputStream ; 25 import java.security.MessageDigest ; 26 import java.security.NoSuchAlgorithmException ; 27 import java.security.NoSuchProviderException ; 28 import org.apache.tools.ant.BuildException; 29 30 31 57 public class DigestAlgorithm implements Algorithm { 58 59 60 62 63 66 private String algorithm = "MD5"; 67 68 71 private String provider = null; 72 73 76 private MessageDigest messageDigest = null; 77 78 81 private int readBufferSize = 8 * 1024; 82 83 84 86 87 92 public void setAlgorithm(String algorithm) { 93 this.algorithm = algorithm; 94 } 95 96 97 102 public void setProvider(String provider) { 103 this.provider = provider; 104 } 105 106 107 108 public void initMessageDigest() { 109 if (messageDigest != null) { 110 return; 111 } 112 113 if ((provider != null) && !"".equals(provider) && !"null".equals(provider)) { 114 try { 115 messageDigest = MessageDigest.getInstance(algorithm, provider); 116 } catch (NoSuchAlgorithmException noalgo) { 117 throw new BuildException(noalgo); 118 } catch (NoSuchProviderException noprovider) { 119 throw new BuildException(noprovider); 120 } 121 } else { 122 try { 123 messageDigest = MessageDigest.getInstance(algorithm); 124 } catch (NoSuchAlgorithmException noalgo) { 125 throw new BuildException(noalgo); 126 } 127 } 128 } 129 130 131 133 134 138 public boolean isValid() { 139 return "SHA".equalsIgnoreCase(algorithm) || "MD5".equalsIgnoreCase(algorithm); 140 } 141 142 143 148 public String getValue(File file) { 150 initMessageDigest(); 151 String checksum = null; 152 try { 153 if (!file.canRead()) { 154 return null; 155 } 156 FileInputStream fis = null; 157 158 byte[] buf = new byte[readBufferSize]; 159 try { 160 messageDigest.reset(); 161 fis = new FileInputStream (file); 162 DigestInputStream dis = new DigestInputStream (fis, 163 messageDigest); 164 while (dis.read(buf, 0, readBufferSize) != -1) { 165 } 167 dis.close(); 168 fis.close(); 169 fis = null; 170 byte[] fileDigest = messageDigest.digest(); 171 StringBuffer checksumSb = new StringBuffer (); 172 for (int i = 0; i < fileDigest.length; i++) { 173 String hexStr = Integer.toHexString(0x00ff & fileDigest[i]); 174 if (hexStr.length() < 2) { 175 checksumSb.append("0"); 176 } 177 checksumSb.append(hexStr); 178 } 179 checksum = checksumSb.toString(); 180 } catch (Exception e) { 181 return null; 182 } 183 } catch (Exception e) { 184 return null; 185 } 186 return checksum; 187 } 188 189 190 194 public String toString() { 195 StringBuffer buf = new StringBuffer (); 196 buf.append("<DigestAlgorithm:"); 197 buf.append("algorithm=").append(algorithm); 198 buf.append(";provider=").append(provider); 199 buf.append(">"); 200 return buf.toString(); 201 } 202 } 203 | Popular Tags |