feat(hash): 新增 HashCodec 哈希体系与 13 种 JDK 标准算法实现

HashCodec 接口只需重写 hash(InputStream),其余重载、十六进制输出与
常量时间校验均由默认实现提供;MessageDigestCodec 流式基类 8KB 缓冲、
恒定内存、不关闭调用方流;提供 HashUtils 懒加载单例与 HashType 枚举,
TestHash 覆盖已知向量、算法一致性、流生命周期与文件/路径重载。
This commit is contained in:
2026-11-18 18:57:46 +08:00
parent 988a0c0dc1
commit 713342bbc6
18 changed files with 933 additions and 52 deletions
@@ -0,0 +1,81 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashType.kt
* LastUpdate 2026-11-18 18:48:01
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.HashCodec
import java.io.InputStream
/**
* 哈希算法类型枚举。
*
* 每个枚举项持有一个哈希编解码器的工厂函数,枚举本身实现了 [HashCodec],
* 可直接作为编解码器使用,哈希操作委托给对应的编解码器实例。
*
* @param codec 哈希编解码器的工厂函数,每次访问 [code] 时调用以创建实例
*/
enum class HashType(private val codec: () -> HashCodec) : HashCodec {
/** MD2 哈希(输出 128 位,已过时,仅用于兼容遗留系统)。 */
MD2(::MD2),
/** MD5 哈希(输出 128 位,存在碰撞漏洞,不得用于安全场景)。 */
MD5(::MD5),
/** SHA-1 哈希(输出 160 位,存在碰撞攻击,不得用于安全场景)。 */
SHA1(::SHA1),
/** SHA-224 哈希(SHA-2 家族,输出 224 位)。 */
SHA224(::SHA224),
/** SHA-256 哈希(SHA-2 家族,输出 256 位)。 */
SHA256(::SHA256),
/** SHA-384 哈希(SHA-2 家族,输出 384 位)。 */
SHA384(::SHA384),
/** SHA-512 哈希(SHA-2 家族,输出 512 位)。 */
SHA512(::SHA512),
/** SHA3-224 哈希(SHA-3 家族,输出 224 位)。 */
SHA3224(::SHA3224),
/** SHA3-256 哈希(SHA-3 家族,输出 256 位)。 */
SHA3256(::SHA3256),
/** SHA3-384 哈希(SHA-3 家族,输出 384 位)。 */
SHA3384(::SHA3384),
/** SHA3-512 哈希(SHA-3 家族,输出 512 位)。 */
SHA3512(::SHA3512),
/** SHA-512/224 哈希(SHA-2 家族,输出 224 位)。 */
SHA512224(::SHA512224),
/** SHA-512/256 哈希(SHA-2 家族,输出 256 位)。 */
SHA512256(::SHA512256);
/**
* 获取当前类型对应的哈希编解码器实例(每次访问都会通过工厂函数新建)。
*/
val code get() = codec()
/**
* 计算输入流内容的哈希值,委托给 [code] 对应的编解码器。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
override fun hash(input: InputStream): ByteArray {
return code.hash(input)
}
}
@@ -16,71 +16,103 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile HashUtils.kt * CurrentFile HashUtils.kt
* LastUpdate 2026-01-11 09:09:52 * LastUpdate 2026-11-18 18:53:11
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("HashUtils") @file:JvmName("HashUtils")
package com.mingliqiye.utils.hash package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.*
import com.mingliqiye.utils.bcrypt.checkpw
import com.mingliqiye.utils.bcrypt.hashpw
import com.mingliqiye.utils.bytes.bytesToHex
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/** /**
* 计算指定文件的哈希值。 * 提供 MD2 哈希器的懒加载实例。
* * 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
* @param file 要计算哈希值的文件对象
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
* @return 文件的十六进制格式哈希值字符串
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
*/ */
@Throws(IOException::class, NoSuchAlgorithmException::class) @get:JvmName("getMd2Codec")
fun calculateFileHash(file: File, algorithm: String): String { val MD2 by lazy(::Md2Codec)
// 检查文件是否存在
if (!file.exists()) {
throw IOException("File not found: " + file.absolutePath)
}
val digest = MessageDigest.getInstance(algorithm)
FileInputStream(file).use { fis ->
val buffer = ByteArray(8192)
var bytesRead: Int
// 分块读取文件内容并更新摘要
while (fis.read(buffer).also { bytesRead = it } != -1) {
digest.update(buffer, 0, bytesRead)
}
}
return bytesToHex(digest.digest())
}
/** /**
* 使用 BCrypt 算法对字符串进行加密。 * 提供 MD5 哈希器的懒加载实例。
* * 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
* @param string 需要加密的明文字符串
* @return 加密后的 BCrypt 哈希字符串
*/ */
fun bcrypt(string: String): String { @get:JvmName("getMd5Codec")
return hashpw(string) val MD5 by lazy(::Md5Codec)
}
/** /**
* 验证给定字符串与 BCrypt 哈希是否匹配。 * 提供 SHA-1 哈希器的懒加载实例。
* * 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
* @param string 明文字符串
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
* @return 如果匹配返回 true,否则返回 false
*/ */
fun checkBcrypt(string: String, bcrypted: String): Boolean { @get:JvmName("getSha1Codec")
return checkpw(string, bcrypted) val SHA1 by lazy(::Sha1Codec)
}
/**
* 提供 SHA-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 224 位摘要。
*/
@get:JvmName("getSha224Codec")
val SHA224 by lazy(::Sha224Codec)
/**
* 提供 SHA-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 256 位摘要,适用于文件校验、数字签名等场景。
*/
@get:JvmName("getSha256Codec")
val SHA256 by lazy(::Sha256Codec)
/**
* 提供 SHA-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 384 位摘要。
*/
@get:JvmName("getSha384Codec")
val SHA384 by lazy(::Sha384Codec)
/**
* 提供 SHA-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 512 位摘要,在 64 位平台上通常比 SHA-256 更快。
*/
@get:JvmName("getSha512Codec")
val SHA512 by lazy(::Sha512Codec)
/**
* 提供 SHA3-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 224 位摘要。
*/
@get:JvmName("getSha3224Codec")
val SHA3224 by lazy(::Sha3224Codec)
/**
* 提供 SHA3-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 256 位摘要。
*/
@get:JvmName("getSha3256Codec")
val SHA3256 by lazy(::Sha3256Codec)
/**
* 提供 SHA3-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 384 位摘要。
*/
@get:JvmName("getSha3384Codec")
val SHA3384 by lazy(::Sha3384Codec)
/**
* 提供 SHA3-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 512 位摘要。
*/
@get:JvmName("getSha3512Codec")
val SHA3512 by lazy(::Sha3512Codec)
/**
* 提供 SHA-512/224 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
@get:JvmName("getSha512224Codec")
val SHA512224 by lazy(::Sha512224Codec)
/**
* 提供 SHA-512/256 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
@get:JvmName("getSha512256Codec")
val SHA512256 by lazy(::Sha512256Codec)
@@ -0,0 +1,176 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashCodec.kt
* LastUpdate 2026-11-18 18:36:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import com.mingliqiye.utils.base.BaseType
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
/**
* 哈希编解码器接口。
*
* 实现类只需重写 [hash](InputStream 版本)一个方法,
* 其余字节数组、字符串、文件、路径的重载以及十六进制输出、
* 哈希校验均由接口提供默认实现。
*
* 使用示例(以 SHA-256 为例):
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
interface HashCodec {
/**
* 计算输入流内容的哈希值(唯一需要实现的方法)。
*
* 实现不需要关闭输入流,由调用方负责流的生命周期。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
fun hash(input: InputStream): ByteArray
/**
* 计算字节数组的哈希值。
*
* @param bytes 待计算哈希的字节数组
* @return 哈希结果字节数组
*/
fun hash(bytes: ByteArray): ByteArray = hash(bytes.inputStream())
/**
* 计算字符串的哈希值。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 哈希结果字节数组
*/
fun hash(string: String, charset: Charset = Charsets.UTF_8): ByteArray = hash(string.toByteArray(charset))
/**
* 计算文件内容的哈希值。
*
* @param file 待计算哈希的文件
* @return 哈希结果字节数组
*/
fun hash(file: File): ByteArray = file.inputStream().use { hash(it) }
/**
* 计算路径指向文件内容的哈希值。
*
* @param path 待计算哈希的文件路径
* @return 哈希结果字节数组
*/
fun hash(path: Path): ByteArray = Files.newInputStream(path).use { hash(it) }
/**
* 计算输入流内容的哈希值并以小写十六进制字符串返回。
*
* @param input 待计算哈希的输入流
* @return 十六进制格式的哈希字符串
*/
fun hashHex(input: InputStream): String = BaseType.BASE16.encode(hash(input))
/**
* 计算字节数组的哈希值并以小写十六进制字符串返回。
*
* @param bytes 待计算哈希的字节数组
* @return 十六进制格式的哈希字符串
*/
fun hashHex(bytes: ByteArray): String = BaseType.BASE16.encode(hash(bytes))
/**
* 计算字符串的哈希值并以小写十六进制字符串返回。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 十六进制格式的哈希字符串
*/
fun hashHex(string: String, charset: Charset = Charsets.UTF_8): String =
BaseType.BASE16.encode(hash(string, charset))
/**
* 计算文件内容的哈希值并以小写十六进制字符串返回。
*
* @param file 待计算哈希的文件
* @return 十六进制格式的哈希字符串
*/
fun hashHex(file: File): String = BaseType.BASE16.encode(hash(file))
/**
* 计算路径指向文件内容的哈希值并以小写十六进制字符串返回。
*
* @param path 待计算哈希的文件路径
* @return 十六进制格式的哈希字符串
*/
fun hashHex(path: Path): String = BaseType.BASE16.encode(hash(path))
/**
* 校验输入流内容的哈希值是否与期望值一致。
*
* 使用 [java.security.MessageDigest.isEqual] 进行常量时间比较,避免时序攻击。
*
* @param input 待校验的输入流
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(input: InputStream, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(input), hashed)
/**
* 校验字节数组的哈希值是否与期望值一致。
*
* @param bytes 待校验的字节数组
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(bytes: ByteArray, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(bytes), hashed)
/**
* 校验字符串的哈希值是否与期望值一致。
*
* @param string 待校验的字符串
* @param hashed 期望的哈希值字节数组
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashed: ByteArray, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), hashed)
/**
* 校验字符串的哈希值是否与期望的十六进制字符串一致(忽略大小写)。
*
* @param string 待校验的字符串
* @param hashedHex 期望的十六进制哈希字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashedHex: String, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), BaseType.BASE16.decode(hashedHex.lowercase()))
}
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Md2Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
*
* MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
*/
class Md2Codec : MessageDigestCodec("MD2")
@@ -0,0 +1,31 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Md5Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
*
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
*/
class Md5Codec : MessageDigestCodec("MD5")
@@ -0,0 +1,63 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MessageDigestCodec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import java.io.InputStream
import java.security.MessageDigest
/**
* 基于 JDK [MessageDigest] 的哈希编解码器抽象基类。
*
* 以固定 8KB 缓冲区流式读取输入,内存占用恒定,适用于任意大小的文件与数据流。
* 每次调用 [hash] 都会新建 [MessageDigest] 实例(其本身非线程安全),
* 因此本类实例无状态、可安全地在多线程间共享。
*
* 遵循 [HashCodec] 契约:不关闭输入流,由调用方负责流的生命周期。
*
* 子类只需指定算法名称,也可借此扩展 JDK 默认提供者之外的算法
* (如 BouncyCastle 提供的 SM3),前提是相应 [java.security.Provider] 已注册。
*
* @param algorithm [MessageDigest.getInstance] 所用的算法名称
*/
abstract class MessageDigestCodec(private val algorithm: String) : HashCodec {
/**
* 以 8KB 缓冲区流式计算输入流内容的哈希值。
*
* 不关闭输入流;每次调用新建 [MessageDigest] 实例,线程安全。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
* @throws java.security.NoSuchAlgorithmException 当前环境无指定算法的提供者时抛出
*/
override fun hash(input: InputStream): ByteArray {
val digest = MessageDigest.getInstance(algorithm)
val buffer = ByteArray(8192)
while (true) {
val n = input.read(buffer)
if (n == -1) break
digest.update(buffer, 0, n)
}
return digest.digest()
}
}
@@ -0,0 +1,31 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha1Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
*
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
* 仅建议用于兼容遗留系统或非安全性校验。
*/
class Sha1Codec : MessageDigestCodec("SHA-1")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*/
class Sha224Codec : MessageDigestCodec("SHA-224")
@@ -0,0 +1,37 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 目前广泛使用的安全哈希算法,适用于文件校验、数字签名、消息摘要等场景。
*
* 使用示例:
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
class Sha256Codec : MessageDigestCodec("SHA-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-224 哈希编解码器(SHA-3 家族,Keccak 结构,输出 224 位 / 28 字节)。
*/
class Sha3224Codec : MessageDigestCodec("SHA3-224")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-256 哈希编解码器(SHA-3 家族,Keccak 结构,输出 256 位 / 32 字节)。
*/
class Sha3256Codec : MessageDigestCodec("SHA3-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-384 哈希编解码器(SHA-3 家族,Keccak 结构,输出 384 位 / 48 字节)。
*/
class Sha3384Codec : MessageDigestCodec("SHA3-384")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3512Codec.kt
* LastUpdate 2026-11-18 11:18:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-512 哈希编解码器(SHA-3 家族,Keccak 结构,输出 512 位 / 64 字节)。
*/
class Sha3512Codec : MessageDigestCodec("SHA3-512")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-384 哈希编解码器(SHA-2 家族,输出 384 位 / 48 字节)。
*/
class Sha384Codec : MessageDigestCodec("SHA-384")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*
* 以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
class Sha512224Codec : MessageDigestCodec("SHA-512/224")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
class Sha512256Codec : MessageDigestCodec("SHA-512/256")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512 哈希编解码器(SHA-2 家族,输出 512 位 / 64 字节)。
*
* 在 64 位平台上通常比 SHA-256 更快,适用于大文件校验与高安全需求场景。
*/
class Sha512Codec : MessageDigestCodec("SHA-512")
@@ -0,0 +1,142 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile TestHash.kt
* LastUpdate 2026-11-18 11:17:46
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.hash.code.Md2Codec
import com.mingliqiye.utils.hash.code.Md5Codec
import com.mingliqiye.utils.hash.code.MessageDigestCodec
import com.mingliqiye.utils.hash.code.Sha1Codec
import com.mingliqiye.utils.hash.code.Sha224Codec
import com.mingliqiye.utils.hash.code.Sha256Codec
import com.mingliqiye.utils.hash.code.Sha3224Codec
import com.mingliqiye.utils.hash.code.Sha3256Codec
import com.mingliqiye.utils.hash.code.Sha3384Codec
import com.mingliqiye.utils.hash.code.Sha3512Codec
import com.mingliqiye.utils.hash.code.Sha384Codec
import com.mingliqiye.utils.hash.code.Sha512224Codec
import com.mingliqiye.utils.hash.code.Sha512256Codec
import com.mingliqiye.utils.hash.code.Sha512Codec
import com.mingliqiye.utils.hash.code.HashCodec
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import java.io.FilterInputStream
import java.nio.file.Files
import java.security.MessageDigest
/**
* [HashCodec] 及其全部内置算法实现的测试。
*/
class TestHash {
private val codecs: List<Pair<HashCodec, String>> = listOf(
Md2Codec() to "MD2",
Md5Codec() to "MD5",
Sha1Codec() to "SHA-1",
Sha224Codec() to "SHA-224",
Sha256Codec() to "SHA-256",
Sha384Codec() to "SHA-384",
Sha512Codec() to "SHA-512",
Sha512224Codec() to "SHA-512/224",
Sha512256Codec() to "SHA-512/256",
Sha3224Codec() to "SHA3-224",
Sha3256Codec() to "SHA3-256",
Sha3384Codec() to "SHA3-384",
Sha3512Codec() to "SHA3-512",
)
/** 测试常见算法对 "hello" 的已知哈希向量 */
@Test
fun knownVectors() {
assertEquals("5d41402abc4b2a76b9719d911017c592", Md5Codec().hashHex("hello"))
assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", Sha1Codec().hashHex("hello"))
assertEquals(
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
Sha256Codec().hashHex("hello")
)
}
/** 测试全部算法的流式结果与 MessageDigest 直接计算一致,且校验方法正确 */
@Test
fun allAlgorithmsMatchMessageDigest() {
val data = ByteArray(100_000) { (it % 251).toByte() }
for ((codec, algorithm) in codecs) {
val expected = MessageDigest.getInstance(algorithm).digest(data)
assertArrayEquals(expected, codec.hash(data), algorithm)
assertArrayEquals(expected, codec.hash(data.inputStream()), algorithm)
assertEquals(BaseType.BASE16.encode(expected), codec.hashHex(data), algorithm)
assertTrue(codec.verifyHash(data, expected), algorithm)
val tampered = expected.copyOf().also { it[0] = (it[0].toInt() xor 1).toByte() }
assertFalse(codec.verifyHash(data, tampered), algorithm)
assertTrue(codec.verifyHash("hello", codec.hashHex("hello")), algorithm)
assertFalse(codec.verifyHash("hello", codec.hashHex("world")), algorithm)
}
}
/** 测试实现不关闭调用方传入的输入流 */
@Test
fun doesNotCloseCallerStream() {
var closed = false
val stream = object : FilterInputStream("hello".byteInputStream()) {
override fun close() {
closed = true
super.close()
}
}
Sha256Codec().hash(stream)
assertFalse(closed)
}
/** 测试文件与路径重载结果和字节数组一致 */
@Test
fun fileAndPathOverloads() {
val data = ByteArray(20_000) { (it % 256).toByte() }
val path = Files.createTempFile("mingli-hash-test", ".bin")
try {
Files.write(path, data)
val codec = Sha256Codec()
assertArrayEquals(codec.hash(data), codec.hash(path))
assertArrayEquals(codec.hash(data), codec.hash(path.toFile()))
assertEquals(codec.hashHex(data), codec.hashHex(path))
assertEquals(codec.hashHex(data), codec.hashHex(path.toFile()))
} finally {
Files.deleteIfExists(path)
}
}
/** 测试自定义算法名称的扩展基类用法 */
@Test
fun customAlgorithmViaBaseClass() {
val codec = object : MessageDigestCodec("SHA-256") {}
assertArrayEquals(Sha256Codec().hash("hello"), codec.hash("hello"))
}
/** 测试空输入可正常计算哈希 */
@Test
fun emptyInput() {
val empty = ByteArray(0)
for ((codec, algorithm) in codecs) {
assertArrayEquals(MessageDigest.getInstance(algorithm).digest(empty), codec.hash(empty), algorithm)
}
}
}