Last active
June 29, 2023 23:13
-
-
Save arnabmitra/1520f2fbab65731e5979264f1e656f1f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.jsonwebtoken.ExpiredJwtException | |
import io.jsonwebtoken.Jwts | |
import io.jsonwebtoken.MalformedJwtException | |
import io.jsonwebtoken.SignatureAlgorithm | |
import io.jsonwebtoken.UnsupportedJwtException | |
import org.bouncycastle.jce.ECNamedCurveTable | |
import org.bouncycastle.jce.provider.BouncyCastleProvider | |
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec | |
import org.junit.jupiter.api.Test | |
import java.security.KeyPair | |
import java.security.KeyPairGenerator | |
import java.security.SignatureException | |
import java.util.Date | |
class JwtKt_JJWTTest { | |
fun generateSecp256k1KeyPair(): KeyPair { | |
val ecSpec: ECNamedCurveParameterSpec = ECNamedCurveTable.getParameterSpec("secp256r1") | |
val g: KeyPairGenerator = KeyPairGenerator.getInstance("EC", BouncyCastleProvider()) | |
g.initialize(ecSpec) | |
return g.generateKeyPair() | |
} | |
fun generateJwt(keyPair: KeyPair): String { | |
val now = Date() | |
val claims = Jwts.claims().setSubject("subject") | |
claims["created"] = now | |
val algo = SignatureAlgorithm.forName(SignatureAlgorithm.ES256.toString()) | |
return Jwts.builder() | |
.setClaims(claims) | |
.setIssuedAt(now) | |
.signWith(keyPair.private, algo) | |
.compact() | |
} | |
fun validateJwt(jwt: String, keyPair: KeyPair) { | |
try { | |
Jwts.parserBuilder() | |
.setSigningKey(keyPair.public) | |
.build() | |
.parseClaimsJws(jwt) | |
println("JWT is valid") | |
} catch (e: ExpiredJwtException) { | |
println("JWT is expired") | |
} catch (e: UnsupportedJwtException) { | |
println("JWT format is not supported") | |
} catch (e: MalformedJwtException) { | |
println("JWT is not correctly constructed") | |
} catch (e: SignatureException) { | |
println("JWT signature does not match") | |
} catch (e: Exception) { | |
println("Unexpected exception: $e") | |
} | |
} | |
@Test | |
fun `generate admin jwt`() { | |
val keyPair = generateSecp256k1KeyPair() | |
val jwt = generateJwt(keyPair) | |
validateJwt(jwt, keyPair) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment