Skip to content
HOA PHAN edited this page May 30, 2022 · 3 revisions

deps

dependencies {
    implementation("io.jsonwebtoken:jjwt-api:0.11.5")
    runtimeOnly("io.jsonwebtoken:jjwt-impl:0.11.5")
    runtimeOnly("io.jsonwebtoken:jjwt-jackson:0.11.2")
}

genkey

import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import java.io.FileOutputStream
import java.io.FileWriter
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.util.*

fun main(args: Array<String>) {
    val kpg = KeyPairGenerator.getInstance("RSA")
    kpg.initialize(2048)
    val kp = kpg.generateKeyPair()
    saveBin(kp)
    saveBase64(kp)
    val key = generateJwtToken(kp.private)
    println(key)
}

fun saveBin(keyPair: KeyPair){
    val outFile = "rsa";
    val outPr = FileOutputStream(outFile + ".key");
    outPr.write(keyPair.private.encoded);
    outPr.close();

    val outPl =  FileOutputStream(outFile + ".pub");
    outPl.write(keyPair.public.encoded);
    outPl.close();
}

fun saveBase64(keyPair: KeyPair){
    val encoder = Base64.getEncoder()

    val outFile = "rsa.64";
    val out = FileWriter(outFile + ".key");
    out.write("-----BEGIN RSA PRIVATE KEY-----\n");
    out.write(encoder.encodeToString(keyPair.private.encoded));
    out.write("\n-----END RSA PRIVATE KEY-----\n");
    out.close();

    val outPl = FileWriter(outFile + ".pub");
    outPl.write("-----BEGIN RSA PUBLIC KEY-----\n");
    outPl.write(encoder.encodeToString(keyPair.public.encoded));
    outPl.write("\n-----END RSA PUBLIC KEY-----\n");
    outPl.close();
}

fun generateJwtToken(privateKey: PrivateKey): String {
    return Jwts.builder().setSubject("adam")
        .setExpiration(Date())
        .setIssuer("[email protected]")
        .claim("groups", arrayOf("user", "admin")) // RS256 with privateKey
        .signWith(privateKey)
        .compact()
}

eye

Clone this wiki locally