Skip to content

Instantly share code, notes, and snippets.

@kanshi
Created March 30, 2022 00:13
Show Gist options
  • Save kanshi/5662cbd750ff899284d1d5ceaec1a061 to your computer and use it in GitHub Desktop.
Save kanshi/5662cbd750ff899284d1d5ceaec1a061 to your computer and use it in GitHub Desktop.
import pdi.jwt.{Jwt, JwtAlgorithm}
import org.bitcoins.core.util.Base58
import org.bouncycastle.jce.spec.ECPublicKeySpec
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.security.{KeyFactory, PublicKey, Security}
import scala.util._
val jwtToken = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2NDg1OTcwNzIsImV4cCI6MTY0ODU5NzY3Mn0.MFEtqJzrLTnjYwH4gAOsH-0qsrQIFsKcYHyHdE1WdWHLn_xa-fGPoV3OkDLr0Rk1IcIoawSrDXNxkyZR0wGhFw"
val desoPKey = "BC1YLhwpmWkgk2iM9yTSxzgUVhYjgessSPTiVHkkK9pMrhweqJnWrvK"
if (Security.getProvider("BC") == null)
Security.addProvider(new BouncyCastleProvider())
val keyFactory: KeyFactory = KeyFactory.getInstance("EC", "BC")
val isSignatureValid: Boolean =
Base58.decodeCheck(desoPKey) match {
case Failure(_) => false
case Success(desoPKeyBytes) =>
val pointBytes = desoPKeyBytes.slice(3, desoPKeyBytes.length)
if (pointBytes.length != 33) false
else {
val curveParams = ECNamedCurveTable.getParameterSpec("secp256k1")
val pubKeySpec = new ECPublicKeySpec(curveParams.getCurve.decodePoint(pointBytes.toArray), curveParams)
val publicKey: PublicKey = keyFactory.generatePublic(pubKeySpec)
Jwt.isValid(jwtToken, publicKey, Seq(JwtAlgorithm.ES256))
}
}
if (Security.getProvider("BC") != null)
Security.removeProvider("BC")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment