JWT Scala- java.security.spec.InvalidKeySpecException

时间:2017-09-09 00:10:46

标签: scala encryption jwt

我正在尝试使用JWT Scala创建一个JWT:

import pdi.jwt._

...

val claim = s"""{ \"exp\": $oneMinuteFromNow }"""
Jwt.encode(claim, key, JwtAlgorithm.ES512)

key是一个包含

形式的私钥的String
-----BEGIN EC PRIVATE KEY-----
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAmG8JrpLz14+qUs7oxFX0pCoe90Ah
MMB/9ZENy8KZ+us26i/6PiBBc7XaiEi6Q8Icz2tiazwSpyLPeBrFVPFkPgIADyLa
T0fp7D2JKHWpdrWQvGLLMwGqYCaaDi79KugPo6V4bnpLBlVtbH4ogg0Hqv89BVyI
ZfwWPCBH+Zssei1VlgM=
-----END EC PRIVATE KEY-----

但我得到了:

java.security.spec.InvalidKeySpecException: encoded key spec not recognized: wrong version for private key info
  at org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi.engineGeneratePrivate(Unknown Source)
  at org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi.engineGeneratePrivate(Unknown Source)
  at java.security.KeyFactory.generatePrivate(KeyFactory.java:366)
  at pdi.jwt.JwtUtils$.parsePrivateKey(JwtUtils.scala:109)
  at pdi.jwt.JwtUtils$.sign(JwtUtils.scala:152)
  at pdi.jwt.JwtUtils$.sign(JwtUtils.scala:159)
  at pdi.jwt.JwtCore$class.encode(Jwt.scala:80)
  at pdi.jwt.Jwt$.encode(Jwt.scala:23)
  at pdi.jwt.JwtCore$class.encode(Jwt.scala:109)
  at pdi.jwt.Jwt$.encode(Jwt.scala:23)

我用Google搜索了我能想到的一切,但我不确定我做错了什么。任何帮助表示赞赏!

(上面的键不是真正的键BTW)

1 个答案:

答案 0 :(得分:1)

我终于有了这个工作。

openssl ecparam -genkey -name secp521r1 -noout -out ec512-key-pair.pem

我使用命令生成密钥。签署JWT的代码:

object JwtGen {

  def generateToken(keyPath: String) : String = {
    if (keyPath.isEmpty) throw new java.io.IOException("keyPath is empty!")
    val claim = s"""{ \"exp\": $oneMinuteFromNow }"""
    Jwt.encode(claim, encodeKey(keyPath), JwtAlgorithm.ES512)
  }

  private def oneMinuteFromNow: Long = {
    (System.currentTimeMillis / 1000) + 60
  }

  private def encodeKey(keyPath: String): PrivateKey = {
    Security.addProvider(new BouncyCastleProvider)
    val parser = new PEMParser(new InputStreamReader(new FileInputStream(keyPath)))
    val pemObject = Option(parser.readObject)
    pemObject match {
      case Some(kp: PEMKeyPair) => convertFormat(kp)
      case _ => throw new java.io.IOException(s"cannot parse pem file $keyPath")
    }
  }

  private def convertFormat(pemKeyPair: PEMKeyPair): PrivateKey = {
    val converter = new JcaPEMKeyConverter
    val keyPair = converter.getKeyPair(pemKeyPair)
    keyPair.getPrivate
  }
}