I have a small doubt. I have a login system that u...
# ktor
r
I have a small doubt. I have a login system that uses jwt. The client asked that he wants the jwt encrypted. I can encrypt and send to other services. But when I get an encrypted token, I don't know where, in ktor, I should decrypt it.
k
What are you trying to achieve by encrypting the JWT?
r
Just following orders. =/
j
That’s right
Do you can make available the project in the Github?
Here I have a project that do it
I can create a project the example and share with you
r
would be excellent. But let me show you what I can of the project.
j
ok
r
When the login is successful, the controller returns:
call.answer(200, jwt.encryp()
there are two functions, which, given a string, encrypt or decrypt it. ``````
Copy code
fun String.encrypt(): Result<String> = runCatching {
    val cmsEnvelopedDataGenerator = CMSEnvelopedDataGenerator()
    val jceKey = JceKeyTransRecipientInfoGenerator(keysCert().getOrThrow().first)
    cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey)
    val message = CMSProcessableByteArray(this.toByteArray())
    val encryptor = JceCMSContentEncryptorBuilder(CMSAlgorithm.AES256_CBC).setProvider("BC").build()
    Base64.getEncoder().encodeToString(cmsEnvelopedDataGenerator.generate(message, encryptor).encoded)
}.onFailure {
    it.message
    throw it
}
Copy code
fun String.decrypt(): Result<String> = runCatching {
    val envelopeData = CMSEnvelopedData(Base64.getDecoder().decode(this))
    val recipe = envelopeData.recipientInfos.recipients
    val recipientInfo: KeyTransRecipientInformation = recipe.iterator().next() as KeyTransRecipientInformation
    String(recipientInfo.getContent(JceKeyTransEnvelopedRecipient(keysCert().getOrThrow().second)))
}.onFailure {
    it.message
    throw it
}
j
What is the error message?
Are you working on a REST API?
r
It does not recognize the jwt as valid. It happens that I receive the encrypted JWT, and I don't know in which part of the code I should decrypt it so that Ktor can verify it. yep
j
Ok
r
I believe decryption must be done sometime here
Copy code
fun Application.configureSecurity() {
  authentication {
    jwt {
      val issuer = hoconProperty("jwt.issuer")
      val jwkProvider = JwkProviderBuilder(issuer)
        .cached(10, 24, TimeUnit.HOURS)
        .rateLimited(10, 1, TimeUnit.MINUTES)
        .build()
      val jwtAudience = hoconProperty("jwt.audience")
      realm = hoconProperty("jwt.realm")
      verifier(jwkProvider, issuer) {
        acceptLeeway(3)
      }
      validate { credential ->
        if (credential.payload.audience.contains(jwtAudience)) JWTPrincipal(credential.payload) else null
      }
    }
  }
}
j
Tonight I will create the project and send it to you
ok?
r
Ok, Thank you