当前位置: 首页 > 工具软件 > auth-jwt > 使用案例 >

auth0.jwt生成token

严恩
2023-12-01

生成公钥私钥,并存储到resource

        const val ALGORITHM = "RSA"
        const val PRIVATE_KEY_PATH = "KEY/licensePrivate.key"
        const val PUBLIC_KEY_PATH = "KEY/licensePublic.key"
        
        val keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM)
        val keyPair = keyPairGenerator.generateKeyPair()
        val publicKey = keyPair.public
        val privateKey = keyPair.private
        val publicKeyByte = publicKey.encoded
        val privateKeyByte = privateKey.encoded
        val publicKeyString = Base64.encode(publicKeyByte)
        val privateKeyString = Base64.encode(privateKeyByte)
        var fos = FileOutputStream(PUBLIC_KEY_PATH)
        fos.write(publicKeyString.toByteArray())
        fos.flush()
        fos = FileOutputStream(PRIVATE_KEY_PATH)
        fos.write(privateKeyString.toByteArray())
        fos.flush()
        fos.close()

从本地获取公钥私钥

//EncodedKeySpec的实现有所不同,私钥是PKCS8EncodedKeySpec,公钥是X509EncodedKeySpec
fun getPirvateKey(): PrivateKey {
        val resourceAsStream = Companion::class.java.classLoader.getResourceAsStream(PRIVATE_KEY_PATH)
        val privateKeyString = resourceAsStream?.readAllText()
        resourceAsStream?.close()
        val privateKeyByte = Base64.decode(privateKeyString)
        val pkcS8EncodedKeySpec = PKCS8EncodedKeySpec(privateKeyByte) 
        val keyFactory = KeyFactory.getInstance(ALGORITHM)
        return keyFactory.generatePrivate(pkcS8EncodedKeySpec)
    }
fun getPublicKey(): PublicKey {
        val resourceAsStream = Companion::class.java.classLoader.getResourceAsStream(PUBLIC_KEY_PATH)
        val publicKeyString = resourceAsStream?.readAllText()
        resourceAsStream?.close()
        val publicKeyByte = Base64.decode(publicKeyString)
        val x509EncodedKeySpec = X509EncodedKeySpec(publicKeyByte)
        val keyFactory = KeyFactory.getInstance(ALGORITHM)
        return keyFactory.generatePublic(x509EncodedKeySpec)
    }

生成token

        val algorithm: Algorithm = Algorithm.RSA256(getPublicKey() as RSAPublicKey, getPirvateKey() as RSAPrivateKey)
        val token = JWT.create()
            .withIssuedAt(Date()) //生成时间
            .withExpiresAt(SimpleDateFormat(DATE_FORMAT).parse(command.expireTime)) //过期时间
            .withClaim("info", command.toJson().toString()) //claim是自定义的负载信息
            .sign(algorithm)

解析token

		val decode = JWT.decode(license)
        val dataStr = decode.claims["info"]!!.asString()
        val data = JSONUtil.parseObj(dataStr)
 类似资料: