-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMD5Util.kt
53 lines (49 loc) · 1.59 KB
/
MD5Util.kt
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
package com.example.aqua.utils
import java.io.File
import java.io.FileInputStream
import java.security.MessageDigest
object MD5Util {
fun getFileMD5(path: String?): String? {
if (path.isNullOrEmpty()) {
return null
}
var digest: MessageDigest? = null
var fileIS: FileInputStream? = null
val buffer = ByteArray(1024)
var len = 0
try {
digest = MessageDigest.getInstance("MD5")
val oldF = File(path)
fileIS = FileInputStream(oldF)
while (fileIS.read(buffer).also { len = it } != -1) {
digest.update(buffer, 0, len)
}
} catch (e: Exception) {
e.printStackTrace()
return null
}finally {
fileIS?.close()
}
return bytesToHexString(digest?.digest())
}
fun bytesToHexString(src: ByteArray?): String? {
val result = StringBuilder("")
if (src?.isEmpty()==true) {
return null
}
src?.forEach {
var i = it.toInt()
//这里需要对b与0xff做位与运算,
//若b为负数,强制转换将高位位扩展,导致错误,
//故需要高位清零
val hexStr = Integer.toHexString(i and 0xff)
//若转换后的十六进制数字只有一位,
//则在前补"0"
if (hexStr.length == 1) {
result.append(0)
}
result.append(hexStr)
}
return result.toString()
}
}