Create and verify jwt

jjwt lib

https://github.com/jwtk/jjwt

verify JWT

key参考格式如下:

1
2
3
4
5
6
7
MIIBIjANBgkqhkiG5w0BAQEFAAOCAQ8AMIIBCgKCAQEAtqEIbojnolofNc39VMoX
Wl/9HmCpJsAV3hM8rJFnklPRDpBI5KrymOQXep2yQuETsAoulgScYI7rPl2mp9Gb
rnXkwaKOKyvgOeI2W7+xRImgCfGsSzqyK6jgmwtpIr6pDl3FqK09A+5czytAfRa2
kJNm16XnQk+sqO0O1YyUTRC3GzV6Su32v7m+0a31RgZxi+1Yp7Mrue7zlCL55xth
n+8LfE5Z/zXG/KRLnKJfNn0zo7TFURPvPkpr8LYh2FrSiOYaQ3A5tZXhXiMjYnwN
jKCELB/GbOMJHqae1dInEFGUDb7LZ9OYrQ8HkgyebsX3Z5oZ3CEHLkL9mJaOdEym
1wIDAQAD

JWT参考格式如下:

1
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImRmMzhlMzYyLWY5MzktNDEyMy1hOWUxLTJjYThlZWI1Yjk5YyIsInRzIjoxNTIzNjAzNzk4LCJpYXQiOjE1MjM2MDI1OTd9.qy_UZVRuWcJTClYy5CMQrI4rya1MoKR-WT5mxxOGWbO334tQI2SBYyabWRpaCI2mPY9RNzfDFzmuqOvyTyryIohvWPwge9a1KesWmAyoO8_zGvVY9pt-wsKLww7bouskYJXkuBR7fd0AGganlZARR1u0csQwW27rWsY22gNQyGn1Kxlvik2Z5gV5lBttQS1Q5j0fEqI1a8W5Y3Rv8y3PlmiAoAwmuqS_j-zUygnMkmuXHXB1qnrnTMlmEymRnEbY_MXgHcYOjUT-S5yZt5wbCcSerFo4tkrxz6Um61c7HcuCEbttIV6qEHzqohkH_ksncMRX232U4lrI0lovDWwMYg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fun parseJwt(jwt: String, publicKey: String): Claims {
val key = Base64.getDecoder().decode(publicKey.replace("\n", ""))
val keySpec = X509EncodedKeySpec(key)
val keyFactory = KeyFactory.getInstance("RSA")
val public = keyFactory.generatePublic(keySpec)
return Jwts.parser().setSigningKey(public)
.parseClaimsJws(jwt).body
}

fun isValid(token: String, publicKey: String): Boolean {
try {
parseJwt(token, publicKey)
return true
} catch (e: SignatureException) {
e.printStackTrace()
}
return false
}