mirror of
https://github.com/mamoe/mirai.git
synced 2025-03-31 11:50:09 +08:00
63 lines
1.9 KiB
Kotlin
63 lines
1.9 KiB
Kotlin
/*
|
|
* Copyright 2019-2020 Mamoe Technologies and contributors.
|
|
*
|
|
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
|
|
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
|
|
*
|
|
* https://github.com/mamoe/mirai/blob/master/LICENSE
|
|
*/
|
|
|
|
import java.io.InputStream
|
|
import java.io.OutputStream
|
|
import java.security.MessageDigest
|
|
|
|
/*
|
|
* Copyright 2019-2020 Mamoe Technologies and contributors.
|
|
*
|
|
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
|
|
* Use of this source code is governed by the GNU AFFERO GENERAL PUBLIC LICENSE version 3 license that can be found via the following link.
|
|
*
|
|
* https://github.com/mamoe/mirai/blob/master/LICENSE
|
|
*/
|
|
@OptIn(ExperimentalUnsignedTypes::class)
|
|
fun ByteArray.toUHexString(
|
|
separator: String = " ",
|
|
offset: Int = 0,
|
|
length: Int = this.size - offset
|
|
): String {
|
|
if (length == 0) {
|
|
return ""
|
|
}
|
|
val lastIndex = offset + length
|
|
return buildString(length * 2) {
|
|
this@toUHexString.forEachIndexed { index, it ->
|
|
if (index in offset until lastIndex) {
|
|
var ret = it.toUByte().toString(16).toUpperCase()
|
|
if (ret.length == 1) ret = "0$ret"
|
|
append(ret)
|
|
if (index < lastIndex - 1) append(separator)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
fun InputStream.md5(): ByteArray {
|
|
val digest = MessageDigest.getInstance("md5")
|
|
digest.reset()
|
|
use { input ->
|
|
object : OutputStream() {
|
|
override fun write(b: Int) {
|
|
digest.update(b.toByte())
|
|
}
|
|
|
|
override fun write(b: ByteArray, off: Int, len: Int) {
|
|
digest.update(b, off, len)
|
|
}
|
|
}.use { output ->
|
|
input.copyTo(output)
|
|
}
|
|
}
|
|
return digest.digest()
|
|
}
|