mirror of
https://github.com/tursom/TursomServer.git
synced 2025-03-14 03:40:06 +08:00
添加 token 工具类 TokenUtil
This commit is contained in:
parent
0cc65cfb34
commit
df48998403
@ -18,7 +18,7 @@ open class TokenUtil {
|
||||
|
||||
fun <T> generate(secretKey: String, data: T, timeout: Long = 30 * 60 * 1000, type: DigestType = DigestType.MD5): String {
|
||||
val head = type.digestBase64
|
||||
val body = gson.toJson(TokenBody(System.currentTimeMillis(), timeout, data)).base64()
|
||||
val body = toJson(TokenBody(System.currentTimeMillis(), timeout, data)).base64()
|
||||
val encryptSource = "$head.$body".toByteArray()
|
||||
val encryptKey = secretKey.toByteArray()
|
||||
encryptSource.forEachIndexed { index, _ ->
|
||||
@ -38,11 +38,11 @@ open class TokenUtil {
|
||||
if (signature != splitToken[2]) {
|
||||
throw WrongSignatureException()
|
||||
}
|
||||
val decode = gson.fromJson<TokenBody<T>>(splitToken[1].base64decode())
|
||||
val decode = fromJson<TokenBody<T>>(splitToken[1].base64decode())
|
||||
if (decode.tim + decode.exp < System.currentTimeMillis()) {
|
||||
throw TokenTimeoutException()
|
||||
}
|
||||
return gson.fromJson(gson.toJson(decode.dat), dataClazz)
|
||||
return fromJson(toJson(decode.dat), dataClazz)
|
||||
}
|
||||
|
||||
open fun encrypt(secretKey: String, encryptSource: ByteArray, type: String): String {
|
||||
@ -57,6 +57,11 @@ open class TokenUtil {
|
||||
return digest1.digest(type)!!.toHexString()!!
|
||||
}
|
||||
|
||||
open fun toJson(bean: Any): String = gson.toJson(bean)
|
||||
open fun <T> fromJson(json: String, clazz: Class<T>): T = gson.fromJson(json, clazz)
|
||||
|
||||
private inline fun <reified T : Any> fromJson(json: String): T = gson.fromJson(json, T::class.java)
|
||||
|
||||
data class TokenBody<T>(val tim: Long, val exp: Long, val dat: T)
|
||||
|
||||
open class TokenException : Exception()
|
||||
@ -68,4 +73,5 @@ open class TokenUtil {
|
||||
@JvmStatic
|
||||
val instance = TokenUtil()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user