Last active
June 6, 2023 12:01
-
-
Save Szer/3304c81e4173cde9b871dad7d54b35e7 to your computer and use it in GitHub Desktop.
Example of JWK creation
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
object JwtHelpers { | |
data class KeyPair(val public: RSAPublicKey, val private: RSAPrivateKey) | |
// we need static keyPairs for consistent testing | |
val rsaKeyPair = run { | |
// keySize = 512 | |
// Choose two distinct prime numbers p and q. | |
val p = BigInteger("80015048226958274584861777197787136869318208410134237774308318008156105353397") | |
val q = BigInteger("84597213199129215561490406209976328146625812489295431631787994073201979267081") | |
// Compute n = pq (modulus) | |
val modulus = p.multiply(q) | |
// Compute φ(n) = φ(p)φ(q) = (p − 1)(q − 1) = n - (p + q -1), where φ is Euler's totient function. | |
// and choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e., e and φ(n) are coprime. | |
val m = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)) | |
// random (no) coprime of m | |
val publicExponent = BigInteger("3558378466727931118468155250915611321631043711054806878764573684269336548927293476472136929952773308920033222349399256587177891621088267708150487725894837") | |
// Determine d as d ≡ e−1 (mod φ(n)); i.e., d is the multiplicative inverse of e (modulo φ(n)). | |
val privateExponent = publicExponent.modInverse(m) | |
val spec = RSAPublicKeySpec(modulus, publicExponent) | |
val privateSpec = RSAPrivateKeySpec(modulus, privateExponent) | |
val factory = KeyFactory.getInstance("RSA") | |
val pub = factory.generatePublic(spec) as RSAPublicKey | |
val priv = factory.generatePrivate(privateSpec) as RSAPrivateKey | |
KeyPair(pub, priv) | |
} | |
val jwkKeys = """ | |
{ | |
"keys": [ | |
{ | |
"kty": "RSA", | |
"use": "sig", | |
"kid": "${rsaKeyPair.public.encoded.encodeBase64()}", | |
"x5t": "${rsaKeyPair.public.encoded.encodeBase64()}", | |
"n": "${rsaKeyPair.public.modulus.toByteArray().encodeBase64()}", | |
"e": "${rsaKeyPair.public.publicExponent.toByteArray().encodeBase64()}" | |
} | |
] | |
} | |
""".trimIndent() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment