浏览 11052 次
锁定老帖子 主题:java文件md5验证
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2007-08-07
File file = new File("d:/1.dat"); FileInputStream fs = new FileInputStream(file); BufferedInputStream bi = new BufferedInputStream(fs); ByteArrayOutputStream bo = new ByteArrayOutputStream(); byte[] b = new byte[bi.available()]; int i; while ((i = bi.read(b, 0, b.length)) != -1) { bo.write(b, 0, i); } bo.close(); System.out.print(Md5.MD5(new String(bo.toByteArray()))); public final static String MD5(String s) { char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try { byte[] strTemp = s.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } Md5.MD5就是通过string生成md5编码. 后来在网上下载了一个看文件的md5编码的软件,和我出来的结果不一样. 查询一些资料,好像应该是读文件签名或者认证的md5,如果文件比较大,也不可能把所有的文件数据读到内存. 如果读文件认证的md5或者文件hashcode的md5 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2007-08-07
你用800M以上的文件测试过这段代码没有????? |
|
返回顶楼 | |
发表时间:2007-08-07
备份一下我自己的代码:
import java.applet.*; import java.io.*; import java.security.*; public class HashFile { public static char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static void main(String[] args) throws Exception { String fileName = "D:\\programs\\Foxmail.rar"; String hashType = "MD5"; System.out.println(hashType + " == " + getHash(fileName, hashType)); hashType = "SHA1"; System.out.println(hashType + " == " + getHash(fileName, hashType)); hashType = "SHA-256"; System.out.println(hashType + " == " + getHash(fileName, hashType)); hashType = "SHA-384"; System.out.println(hashType + " == " + getHash(fileName, hashType)); hashType = "SHA-512"; System.out.println(hashType + " == " + getHash(fileName, hashType)); } public static String getHash(String fileName, String hashType) throws Exception { InputStream fis; fis = new FileInputStream(fileName); byte[] buffer = new byte[1024]; MessageDigest md5 = MessageDigest.getInstance(hashType); int numRead = 0; while ((numRead = fis.read(buffer)) > 0) { md5.update(buffer, 0, numRead); } fis.close(); return toHexString(md5.digest()); } public static String toHexString(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (int i = 0; i < b.length; i++) { sb.append(hexChar[(b[i] & 0xf0) >>> 4]); sb.append(hexChar[b[i] & 0x0f]); } return sb.toString(); } } |
|
返回顶楼 | |
发表时间:2007-08-07
谢谢楼上的代码,我知道我错在哪了
|
|
返回顶楼 | |