-
Notifications
You must be signed in to change notification settings - Fork 36
/
FileSHA256Caculater.java
94 lines (83 loc) · 2.26 KB
/
FileSHA256Caculater.java
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
package com.backend;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.utils.conf.AppConfig;
public class FileSHA256Caculater
{
public static final int BUFFERED_SIZE = 1024 * 128;
public static String calFileSha256(File f)
throws NoSuchAlgorithmException, IOException
{
if (f == null || !f.exists() || f.isDirectory())
{
return null;
}
MessageDigest md = MessageDigest
.getInstance(AppConfig.getInstance().getHashAlog());
InputStream in = null;
try
{
in = new BufferedInputStream(new FileInputStream(f));
byte buffer[] = new byte[BUFFERED_SIZE];
while (true)
{
int offset = 0;
boolean bcomplete = false;
while (offset < BUFFERED_SIZE)
{
int readlen = in.read(buffer, offset,
BUFFERED_SIZE - offset);
if (readlen < 0)
{
bcomplete = true;
break;
}
else
{
offset += readlen;
}
}
md.update(buffer, 0, offset);
if (bcomplete)
{
break;
}
}
return byte2hex(md.digest());
}
finally
{
if (in != null)
{
in.close();
}
}
}
private static String byte2hex(byte[] b)
{
if (b == null || b.length == 0)
{
return null;
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++)
{
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
{
hs = hs + "0" + stmp;
}
else
{
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
}