java.security.spec.PKCS8EncodedKeySpec Scala Examples

The following examples show how to use java.security.spec.PKCS8EncodedKeySpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: KeyUtils.scala    From daml   with Apache License 2.0 6 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.jwt

import java.io.{File, FileInputStream}
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.security.cert.CertificateFactory
import java.security.interfaces.{ECPublicKey, RSAPrivateKey, RSAPublicKey}
import java.security.spec.PKCS8EncodedKeySpec
import java.security.KeyFactory

import com.daml.lf.data.TryOps.Bracket.bracket
import scalaz.Show
import scalaz.syntax.show._

import scala.util.Try

object KeyUtils {
  final case class Error(what: Symbol, message: String)

  object Error {
    implicit val showInstance: Show[Error] =
      Show.shows(e => s"KeyUtils.Error: ${e.what}, ${e.message}")
  }

  private val mimeCharSet = StandardCharsets.ISO_8859_1

  
  def generateJwks(keys: Map[String, RSAPublicKey]): String = {
    def generateKeyEntry(keyId: String, key: RSAPublicKey): String =
      s"""    {
         |      "kid": "$keyId",
         |      "kty": "RSA",
         |      "alg": "RS256",
         |      "use": "sig",
         |      "e": "${java.util.Base64.getUrlEncoder
           .encodeToString(key.getPublicExponent.toByteArray)}",
         |      "n": "${java.util.Base64.getUrlEncoder.encodeToString(key.getModulus.toByteArray)}"
         |    }""".stripMargin

    s"""
       |{
       |  "keys": [
       |${keys.toList.map { case (keyId, key) => generateKeyEntry(keyId, key) }.mkString(",\n")}
       |  ]
       |}
    """.stripMargin
  }
} 
Example 2
Source File: GatlingFeeder.scala    From matcher   with MIT License 5 votes vote down vote up
package com.wavesplatform.dex.load

import java.io.{File, PrintWriter}
import java.security
import java.security.KeyFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.util.Base64

import com.wavesplatform.dex.api.ws.protocol.WsAddressSubscribe.JwtPayload
import com.wavesplatform.dex.auth.JwtUtils
import com.wavesplatform.dex.domain.account.{AddressScheme, PrivateKey, PublicKey}
import com.wavesplatform.dex.domain.bytes.ByteStr
import com.wavesplatform.wavesj.PrivateKeyAccount
import play.api.libs.json.Json

import scala.concurrent.duration._
import scala.io.Source
import scala.util.Random

object GatlingFeeder {

  def authServiceKeyPair(rawPrivateKey: String): security.PrivateKey = {
    val privateKeyContent = rawPrivateKey
      .replace("-----BEGIN PRIVATE KEY-----", "")
      .replace("-----END PRIVATE KEY-----", "")
      .replaceAll("\\n", "")

    val kf         = KeyFactory.getInstance("RSA")
    val ksPkcs8    = new PKCS8EncodedKeySpec(Base64.getDecoder.decode(privateKeyContent))
    val privateKey = kf.generatePrivate(ksPkcs8)

    privateKey
  }

  private def mkJwtSignedPayload(a: PrivateKeyAccount): JwtPayload = {
    val exp = System.currentTimeMillis() / 1000 + 24.hour.toSeconds
    JwtPayload(
      signature = ByteStr(Array.emptyByteArray),
      publicKey = PublicKey(a.getPublicKey),
      networkByte = AddressScheme.current.chainId.toChar.toString,
      clientId = "test",
      firstTokenExpirationInSeconds = exp,
      activeTokenExpirationInSeconds = exp,
      scope = List("general")
    ).signed(PrivateKey(a.getPrivateKey))
  }

  private def mkAusString(accountPrivateKey: PrivateKeyAccount, authKp: security.PrivateKey): String = {
    s"""{"T":"aus","S":"${accountPrivateKey.getAddress}","t":"jwt","j":"${JwtUtils.mkJwt(authKp,
                                                                                         Json.toJsObject(mkJwtSignedPayload(accountPrivateKey)))}"}"""
  }

  private def mkObsStrings(pairsFile: File, numberPerClient: Int): String = {
    val source = Source.fromFile(pairsFile)
    try {
      val pairs = Random.shuffle(source.getLines.toVector)
      require(numberPerClient <= pairs.size, "numberPerClient > available asset pairs in file")
      pairs.take(numberPerClient).map(x => s"""{"T":"obs","S":"$x","d":100}""").mkString(";")
    } finally source.close()
  }

  def mkFile(accountsNumber: Int,
             seedPrefix: String,
             authKp: security.PrivateKey,
             pairsFile: File,
             orderBookNumberPerAccount: Int,
             feederFile: File): Unit = {
    val output = new PrintWriter(feederFile, "utf-8")
    try {
      (0 until accountsNumber).foreach { i =>
        val pk = PrivateKeyAccount.fromSeed(s"$seedPrefix$i", 0, AddressScheme.current.chainId)
        output.println(s"""${pk.getAddress};${mkAusString(pk, authKp)};${mkObsStrings(pairsFile, orderBookNumberPerAccount)}""")
      }
    } finally output.close()
    println(s"Results have been saved to $feederFile")
  }
} 
Example 3
Source File: Security.scala    From keycloak-benchmark   with Apache License 2.0 5 votes vote down vote up
package org.jboss.perf

import java.math.BigInteger
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}
import java.security._
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit

import org.keycloak.common.util.Base64
import sun.security.x509._

import scala.util.Random


object Security {
  // not really secure; gives deterministic numbers
  private val secureRandom = new SecureRandom(new SecureRandomSpi {
    val random = new Random(1234L)
    override def engineGenerateSeed(numBytes: Int): Array[Byte] = {
      val bytes = new Array[Byte](numBytes)
      random.nextBytes(bytes)
      bytes
    }

    override def engineSetSeed(seed: Array[Byte]) {}

    override def engineNextBytes(bytes: Array[Byte]) {
      random.nextBytes(bytes)
    }

  }, new SecureRandom().getProvider) {}
  private val algorithm = "RSA"
  private val signingAlgorithm = "SHA256WithRSA"
  private val keyPair: KeyPair = {
    val generator = KeyPairGenerator.getInstance(algorithm)
    generator.initialize(2048, secureRandom)
    generator.genKeyPair()
  }

  val PublicKey =  Base64.encodeBytes(KeyFactory.getInstance(algorithm).getKeySpec(keyPair.getPublic, classOf[X509EncodedKeySpec]).getEncoded)
  val PrivateKey = Base64.encodeBytes(KeyFactory.getInstance(algorithm).getKeySpec(keyPair.getPrivate, classOf[PKCS8EncodedKeySpec]).getEncoded)
  val Certificate = Base64.encodeBytes(generateCertificate("CN=Benchmark", keyPair).getEncoded)

  private def generateCertificate(dn: String, pair: KeyPair): X509Certificate = {
    val info = new X509CertInfo();
    val from = new java.util.Date();
    val to = new java.util.Date(from.getTime() + TimeUnit.DAYS.toMillis(365));
    val interval = new CertificateValidity(from, to);
    val sn = new BigInteger(64, secureRandom);
    val owner = new X500Name(dn);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, owner);
    info.set(X509CertInfo.ISSUER, owner);
//    Use following for Java < 1.8:
//    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
//    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    var algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    // Sign the cert to identify the algorithm that's used.
    var cert = new X509CertImpl(info);
    cert.sign(pair.getPrivate, signingAlgorithm);

    // Update the algorith, and resign.
    algo = cert.get(X509CertImpl.SIG_ALG).asInstanceOf[AlgorithmId];
    info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
    cert = new X509CertImpl(info);
    cert.sign(pair.getPrivate, signingAlgorithm);
    return cert;
  }
} 
Example 4
Source File: ParseEncodedKeySpec.scala    From tsec   with MIT License 5 votes vote down vote up
package tsec.jwt.util

import java.security.KeyFactory
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}

import cats.MonadError
import tsec.signature.jca._

object ParseEncodedKeySpec {

  def pubKeyFromBytes[F[_], A](keyBytes: Array[Byte])(implicit kt: KFTag[A]): SigPublicKey[A] = {
    val spec = new X509EncodedKeySpec(keyBytes)
    SigPublicKey[A](
      KeyFactory
        .getInstance(kt.keyFactoryAlgo, "BC")
        .generatePublic(spec)
    )
  }

  def privKeyFromBytes[F[_], A](keyBytes: Array[Byte])(implicit kt: KFTag[A]): SigPrivateKey[A] = {
    val spec = new PKCS8EncodedKeySpec(keyBytes)
    SigPrivateKey[A](
      KeyFactory
        .getInstance(kt.keyFactoryAlgo, "BC")
        .generatePrivate(spec)
    )
  }

  
  def concatSignatureToDER[F[_], A](
      signature: Array[Byte]
  )(implicit me: MonadError[F, Throwable], ecTag: ECKFTag[A]): F[Array[Byte]] = {
    var (r, s) = signature.splitAt(signature.length / 2)
    r = r.dropWhile(_ == 0)
    if (r.length > 0 && r(0) < 0)
      r +:= 0.toByte

    s = s.dropWhile(_ == 0)
    if (s.length > 0 && s(0) < 0)
      s +:= 0.toByte

    val signatureLength = 2 + r.length + 2 + s.length
    if (signatureLength > 255)
      me.raiseError(GeneralSignatureError("Invalid ECDSA signature format"))

    var signatureDER = scala.collection.mutable.ListBuffer.empty[Byte]
    signatureDER += 48
    if (signatureLength >= 128)
      signatureDER += 0x81.toByte

    signatureDER += signatureLength.toByte
    signatureDER += 2.toByte += r.length.toByte ++= r
    signatureDER += 2.toByte += s.length.toByte ++= s

    me.pure(signatureDER.toArray)
  }
} 
Example 5
Source File: JwsAlgorithm.scala    From akka-http-session   with Apache License 2.0 5 votes vote down vote up
package com.softwaremill.session

import java.nio.charset.StandardCharsets.UTF_8
import java.security.spec.PKCS8EncodedKeySpec
import java.security.{KeyFactory, PrivateKey, Signature}
import java.util.Base64

import com.typesafe.config.Config
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

import scala.util.{Failure, Success, Try}

sealed trait JwsAlgorithm {
  def value: String
  def sign(message: String): String

  protected def encode(bytes: Array[Byte]): String =
    Base64.getUrlEncoder.withoutPadding().encodeToString(bytes)
}

object JwsAlgorithm {

  case class Rsa(privateKey: PrivateKey) extends JwsAlgorithm {

    override val value: String = "RS256"

    override def sign(message: String): String = {
      val privateSignature: Signature = Signature.getInstance("SHA256withRSA")
      privateSignature.initSign(privateKey)
      privateSignature.update(message.getBytes(UTF_8))

      encode(privateSignature.sign())
    }
  }

  object Rsa {

    def fromConfig(jwsConfig: Config): Try[Rsa] = {

      def readKeyFromConf(): Try[String] = {
        val configKey = "rsa-private-key"
        Option(jwsConfig.hasPath(configKey))
          .filter(identity)
          .flatMap(_ => Option(jwsConfig.getString(configKey)))
          .filter(_.trim.nonEmpty)
          .map(_.replaceAll("\\s", "").replaceAll("-----[^-]+-----", ""))
          .map(Success(_))
          .getOrElse(Failure(new IllegalArgumentException(
            "akka.http.session.jws.rsa-private-key must be defined in order to use alg = RS256")))
      }

      readKeyFromConf()
        .flatMap { key =>
          Try {
            val keyFactory = KeyFactory.getInstance("RSA")
            val privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder.decode(key)))
            Rsa(privateKey)
          }.recoverWith {
            case ex => Failure(new IllegalArgumentException("Invalid RSA private key", ex))
          }
        }
    }
  }

  case class HmacSHA256(serverSecret: String) extends JwsAlgorithm {
    override val value: String = "HS256"
    override def sign(message: String): String = {
      val key = serverSecret.getBytes("UTF-8")
      val mac = Mac.getInstance("HmacSHA256")
      mac.init(new SecretKeySpec(key, "HmacSHA256"))
      encode(mac.doFinal(message.getBytes("utf-8")))
    }
  }

} 
Example 6
Source File: KeyUtils.scala    From grpc-scala-microservice-kit   with Apache License 2.0 5 votes vote down vote up
package mu.node.echod.util

import java.nio.file.{Files, Paths}
import java.security.{KeyFactory, PrivateKey, PublicKey}
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}

import pdi.jwt.JwtAlgorithm.RS256

trait KeyUtils {

  val jwtDsa = RS256

  def loadPkcs8PrivateKey(path: String): PrivateKey = {
    val keyBytes = Files.readAllBytes(Paths.get(path))
    val spec = new PKCS8EncodedKeySpec(keyBytes)
    KeyFactory.getInstance("RSA").generatePrivate(spec)
  }

  def loadX509PublicKey(path: String): PublicKey = {
    val keyBytes = Files.readAllBytes(Paths.get(path))
    val spec = new X509EncodedKeySpec(keyBytes)
    KeyFactory.getInstance("RSA").generatePublic(spec)
  }
} 
Example 7
Source File: AkkaGrpcServerScala.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc.interop

import java.io.FileInputStream
import java.nio.file.{ Files, Paths }
import java.security.cert.CertificateFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.security.{ KeyFactory, KeyStore, SecureRandom }

import scala.concurrent.duration._

import akka.actor.ActorSystem
import akka.util.ByteString
import akka.http.scaladsl.Http.ServerBinding
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse }
import akka.http.scaladsl.{ Http2, HttpsConnectionContext }
import akka.stream.SystemMaterializer
import io.grpc.internal.testing.TestUtils
import javax.net.ssl.{ KeyManagerFactory, SSLContext }

import scala.concurrent.{ Await, Future }


case class AkkaGrpcServerScala(serverHandlerFactory: ActorSystem => HttpRequest => Future[HttpResponse])
    extends GrpcServer[(ActorSystem, ServerBinding)] {
  override def start() = {
    implicit val sys = ActorSystem()
    implicit val mat = SystemMaterializer(sys).materializer

    val testService = serverHandlerFactory(sys)

    val bindingFuture = Http2().bindAndHandleAsync(
      testService,
      interface = "127.0.0.1",
      port = 0,
      parallelism = 256, // TODO remove once https://github.com/akka/akka-http/pull/2146 is merged
      connectionContext = serverHttpContext())

    val binding = Await.result(bindingFuture, 10.seconds)
    (sys, binding)
  }

  override def stop(binding: (ActorSystem, ServerBinding)) =
    binding match {
      case (sys, binding) =>
        sys.log.info("Exception thrown, unbinding")
        Await.result(binding.unbind(), 10.seconds)
        Await.result(sys.terminate(), 10.seconds)
    }

  private def serverHttpContext() = {
    val keyEncoded =
      new String(Files.readAllBytes(Paths.get(TestUtils.loadCert("server1.key").getAbsolutePath)), "UTF-8")
        .replace("-----BEGIN PRIVATE KEY-----\n", "")
        .replace("-----END PRIVATE KEY-----\n", "")
        .replace("\n", "")

    val decodedKey = ByteString(keyEncoded).decodeBase64.toArray

    val spec = new PKCS8EncodedKeySpec(decodedKey)

    val kf = KeyFactory.getInstance("RSA")
    val privateKey = kf.generatePrivate(spec)

    val fact = CertificateFactory.getInstance("X.509")
    val is = new FileInputStream(TestUtils.loadCert("server1.pem"))
    val cer = fact.generateCertificate(is)

    val ks = KeyStore.getInstance("PKCS12")
    ks.load(null)
    ks.setKeyEntry("private", privateKey, Array.empty, Array(cer))

    val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(ks, null)

    val context = SSLContext.getInstance("TLS")
    context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom)

    new HttpsConnectionContext(context)
  }

  override def getPort(binding: (ActorSystem, ServerBinding)): Int = binding._2.localAddress.getPort
} 
Example 8
Source File: RSAUtils.scala    From asura   with MIT License 5 votes vote down vote up
package asura.common.util

import java.security._
import java.security.interfaces.{RSAPrivateKey, RSAPublicKey}
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}
import java.util

import javax.crypto.Cipher

object RSAUtils {

  private val KEY_ALGORITHM = "RSA"
  private val KEY_SIZE = 1024

  private val PUBLIC_KEY = "RSAPublicKey"
  private val PRIVATE_KEY = "RSAPrivateKey"

  @throws[Exception]
  def initKey(): util.Map[String, AnyRef] = {
    val keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM)
    keyPairGenerator.initialize(KEY_SIZE)
    val keyPair = keyPairGenerator.generateKeyPair
    val publicKey = keyPair.getPublic.asInstanceOf[RSAPublicKey]
    val privateKey = keyPair.getPrivate.asInstanceOf[RSAPrivateKey]
    val keyMap = new util.HashMap[String, AnyRef]
    keyMap.put(PUBLIC_KEY, publicKey)
    keyMap.put(PRIVATE_KEY, privateKey)
    keyMap
  }


  @throws[Exception]
  def encryptByPrivateKey(data: Array[Byte], key: Array[Byte]): Array[Byte] = {
    val pkcs8KeySpec = new PKCS8EncodedKeySpec(key)
    val keyFactory = KeyFactory.getInstance(KEY_ALGORITHM)
    val privateKey = keyFactory.generatePrivate(pkcs8KeySpec)
    val cipher = Cipher.getInstance(keyFactory.getAlgorithm)
    cipher.init(Cipher.ENCRYPT_MODE, privateKey)
    cipher.doFinal(data)
  }

  @throws[Exception]
  def encryptByPublicKey(data: Array[Byte], key: Array[Byte]): Array[Byte] = {
    val keyFactory = KeyFactory.getInstance(KEY_ALGORITHM)
    val x509KeySpec = new X509EncodedKeySpec(key)
    val pubKey = keyFactory.generatePublic(x509KeySpec)
    val cipher = Cipher.getInstance(keyFactory.getAlgorithm)
    cipher.init(Cipher.ENCRYPT_MODE, pubKey)
    cipher.doFinal(data)
  }

  @throws[Exception]
  def decryptByPrivateKey(data: Array[Byte], key: Array[Byte]): Array[Byte] = {
    val pkcs8KeySpec = new PKCS8EncodedKeySpec(key)
    val keyFactory = KeyFactory.getInstance(KEY_ALGORITHM)
    val privateKey = keyFactory.generatePrivate(pkcs8KeySpec)
    val cipher = Cipher.getInstance(keyFactory.getAlgorithm)
    cipher.init(Cipher.DECRYPT_MODE, privateKey)
    cipher.doFinal(data)
  }

  @throws[Exception]
  def decryptByPublicKey(data: Array[Byte], key: Array[Byte]): Array[Byte] = {
    val keyFactory = KeyFactory.getInstance(KEY_ALGORITHM)
    val x509KeySpec = new X509EncodedKeySpec(key)
    val pubKey = keyFactory.generatePublic(x509KeySpec)
    val cipher = Cipher.getInstance(keyFactory.getAlgorithm)
    cipher.init(Cipher.DECRYPT_MODE, pubKey)
    cipher.doFinal(data)
  }

  def getPrivateKey(keyMap: util.Map[String, AnyRef]): Array[Byte] = {
    val key = keyMap.get(PRIVATE_KEY).asInstanceOf[Key]
    key.getEncoded
  }

  @throws[Exception]
  def getPublicKey(keyMap: util.Map[String, AnyRef]): Array[Byte] = {
    val key = keyMap.get(PUBLIC_KEY).asInstanceOf[Key]
    key.getEncoded
  }
}