Added Nimbus library - JWT with RSA Encryption

This commit is contained in:
constantine2nd 2018-02-17 15:54:53 +01:00
parent 67eedb3a87
commit 8db623bb9e
2 changed files with 48 additions and 2 deletions

View File

@ -334,6 +334,11 @@
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>4.23</version>
</dependency>
</dependencies>

View File

@ -4,8 +4,11 @@ import java.io.FileInputStream
import java.security.interfaces.{RSAPrivateKey, RSAPublicKey}
import java.security.{PublicKey, _}
import javax.crypto.Cipher
import code.api.util.CryptoSystem.CryptoSystem
import com.nimbusds.jose.crypto.RSAEncrypter
import com.nimbusds.jose.{EncryptionMethod, JWEAlgorithm, JWEHeader}
import com.nimbusds.jwt.EncryptedJWT
import code.util.Helper.MdcLoggable
import net.liftweb.util.{Helpers, Props}
@ -14,7 +17,7 @@ object CryptoSystem extends Enumeration {
val RSA = Value
}
object CertificateUtil {
object CertificateUtil extends MdcLoggable {
lazy val (publicKey: RSAPublicKey, privateKey: RSAPrivateKey) = APIUtil.getPropsAsBoolValue("jwt.use.ssl", false) match {
case true =>
@ -95,6 +98,44 @@ object CertificateUtil {
cipher.doFinal(encrypted)
}
def getClaimSet(payload: String) = {
import com.nimbusds.jose.util.Base64URL
import com.nimbusds.jwt.PlainJWT
// {"alg":"none"}// {"alg":"none"}
val header = "eyJhbGciOiJub25lIn0"
val plainJwt = new PlainJWT(new Base64URL(header), new Base64URL(payload))
plainJwt.getJWTClaimsSet
}
def encryptJwtWithRsa(jwtPayload: String) = {
// Request JWT encrypted with RSA-OAEP-256 and 128-bit AES/GCM
val header = new JWEHeader(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A128GCM)
// Create an encrypter with the specified public RSA key
val encrypter = new RSAEncrypter(publicKey)
// Create the encrypted JWT object
val encryptedJWT = new EncryptedJWT(header, CertificateUtil.getClaimSet(jwtPayload))
// Do the actual encryption
encryptedJWT.encrypt(encrypter)
logger.debug("encryptedJWT.serialize(): " + encryptedJWT.serialize())
// Return JWT
encryptedJWT.serialize()
}
def decryptJwtWithRsa(jwt: String) = {
import com.nimbusds.jose.crypto.RSADecrypter
import com.nimbusds.jwt.EncryptedJWT
// Parse back// Parse back
val jwtParsed = EncryptedJWT.parse(jwt)
System.out.println("decryptJwtWithRsa: " + jwtParsed.serialize())
// Create a decrypter with the specified private RSA key
val decrypter = new RSADecrypter(privateKey)
jwtParsed.decrypt(decrypter)
logger.debug("jwt: " + jwt)
logger.debug("getState: " + jwtParsed.getState)
logger.debug("getJWTClaimsSet: " + jwtParsed.getJWTClaimsSet)
logger.debug("getCipherText: " + jwtParsed.getCipherText)
logger.debug("getAuthTag: " + jwtParsed.getAuthTag)
jwtParsed.serialize()
}
@throws[Exception]
def main(args: Array[String]): Unit = {