白季飞龙的个人主页

JWT大杂烩

1. 添加依赖

compile 'io.jsonwebtoken:jjwt:0.9.1'

2. 对称加密令牌的生成与解析

package bj

import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import io.jsonwebtoken.impl.crypto.MacProvider
import java.util.*

fun main(args: Array<String>) {
    val key = MacProvider.generateKey()
    println("Key: ${Base64.getEncoder().encodeToString(key.encoded)}")
    val subject = "apple"
    println("Subject: $subject")
    val token = Jwts.builder().setSubject(subject).signWith(SignatureAlgorithm.HS256, key).compact()
    println("GeneratedToken: $token")
    val parsedJwt = Jwts.parser().setSigningKey(key).parseClaimsJws(token)
    println("ParsedJwt: $parsedJwt")
    val parsedSubject = parsedJwt.body.subject
    println("ParsedSubject: $parsedSubject")

}

示例输出:

Key: O4QbVMdcfe01VUELx8QVUtBmFTagN0yDfNsYCK4+JUMI0m4X/2UpGvHbe+OBr/tXSZLRWAPf8Yyjcp9XIgHabg==
Subject: apple
GeneratedToken: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcHBsZSJ9.1qAiE2o-xtMh9ziHNhPYd-1oS2nW0XBtURHotao4isE
ParsedJwt: header={alg=HS256},body={sub=apple},signature=1qAiE2o-xtMh9ziHNhPYd-1oS2nW0XBtURHotao4isE
ParsedSubject: apple

3. 非对称加密令牌的生成与解析

package bj

import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import java.security.KeyPairGenerator
import java.security.interfaces.RSAKey
import java.util.*

fun main(args: Array<String>) {
    // Java的RSA算法默认使用2048字节的keySize,此处修改为512
    val keyPair = KeyPairGenerator.getInstance("RSA").apply { initialize(512) }.genKeyPair()
    println("KeyLength: ${(keyPair.private as RSAKey).modulus.bitLength()}")
    println("PrivateKey: ${Base64.getEncoder().encodeToString(keyPair.private.encoded)}")
    println("PublicKey: ${Base64.getEncoder().encodeToString(keyPair.public.encoded)}")
    val subject = "apple"
    println("Subject: $subject")
    val token = Jwts.builder().setSubject(subject).signWith(SignatureAlgorithm.RS256, keyPair.private).compact()
    println("GeneratedToken: $token")
    val parsedJwt = Jwts.parser().setSigningKey(keyPair.public).parseClaimsJws(token)
    println("ParsedJwt: $parsedJwt")
    println("ParsedSubject: ${parsedJwt.body.subject}")
}

Java的RSA算法默认使用2048字节的keySize,此处修改为512。

示例输出:

KeyLength: 512
PrivateKey: MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAjPqnXsdaDwUhGB+hZt4K6tASMMxiVA+6RtX8g0Bhxh8MiC81f9XpUrOHapZeKNzCZ65LEoK4cOQ5+hp39vuVGwIDAQABAkAZiluCFzmgmPxK44gZG8b8jV+OSajSs9q6dI//s01DWBy0tjwUk2uuIFjmnqE5gV2oDGGq8T2ADoODgu52AIWRAiEA46/uGaPkTd95+xnvIVdlTwfTFu+5aQJ1VbSwIWw+/MkCIQCegoFjYgCm0qJLHRwauf6z4Kn8HK+6kG92J+jcl2TIwwIhAKC4DhVRSBXkGuGx48egPmXz+wBkxXcnghW2juF43FlpAiAvGHd5H9Uxu8Ocrbl792dF6qqWza8or2Fuqcz2PcUkIQIgL1ZlFnqq8np+K3yE7iIEuEX7UqW8etcTHbuwnSP+naI=
PublicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIz6p17HWg8FIRgfoWbeCurQEjDMYlQPukbV/INAYcYfDIgvNX/V6VKzh2qWXijcwmeuSxKCuHDkOfoad/b7lRsCAwEAAQ==
Subject: apple
GeneratedToken: eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhcHBsZSJ9.RBUVHMvNGwb9TN9fcO_qsz5A_0ZqrIAwNiannwb7XqIcqdDTjrXPjs9bEwaDQU59X9D7om4ECc5ab13zTfzLcg
ParsedJwt: header={alg=RS256},body={sub=apple},signature=RBUVHMvNGwb9TN9fcO_qsz5A_0ZqrIAwNiannwb7XqIcqdDTjrXPjs9bEwaDQU59X9D7om4ECc5ab13zTfzLcg
ParsedSubject: apple

漫漫路,莫论逍遥;潜心修,只为悟道