当前位置: 首页>>代码示例>>Scala>>正文


Scala PublicKey类代码示例

本文整理汇总了Scala中java.security.PublicKey的典型用法代码示例。如果您正苦于以下问题:Scala PublicKey类的具体用法?Scala PublicKey怎么用?Scala PublicKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了PublicKey类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: IdJwtHandler

//设置package包名称以及导入依赖的类
package io.scalac.frees.login.handlers.id

import java.security.{PrivateKey, PublicKey}
import java.util.concurrent.TimeUnit

import cats.Id
import io.scalac.frees.login.algebras.{Claims, JwtService}
import io.scalac.frees.login.types.{JWT, UserId}
import pdi.jwt.{Jwt, JwtAlgorithm, JwtCirce, JwtClaim}

import scala.concurrent.duration.FiniteDuration
import scala.util.Try

class IdJwtHandler(
  pubKey: PublicKey,
  privKey: PrivateKey
) extends JwtService.Handler[Id] {
  val twoDays = FiniteDuration(2, TimeUnit.DAYS).toSeconds
  val algo = JwtAlgorithm.ES512

  override def issue(id: UserId): Id[JWT] = {

    val claim = JwtClaim()
      .about(id.toString)
      .issuedNow
      .expiresIn(twoDays)

    Jwt.encode(claim, privKey, algo)
  }

  override def validate(jwt: JWT): Id[Option[Claims]] = {
    JwtCirce.decode(jwt, pubKey, Seq(algo)).toOption.flatMap { c =>
      for {
        userId <- c.subject.flatMap(s => Try(s.toLong).toOption)
        expiration <- c.expiration.filter(_ > currentTimeSeconds)
        issuedAt <- c.issuedAt.filter(_ <= System.currentTimeMillis())
      } yield Claims(userId, issuedAt, expiration)
    }
  }

  private def currentTimeSeconds: Long = System.currentTimeMillis() / 1000

} 
开发者ID:LGLO,项目名称:freestyle-login,代码行数:44,代码来源:IdJwtHandler.scala

示例2: EncryptionContext

//设置package包名称以及导入依赖的类
package client

import java.security.{Key, PublicKey}
import javax.crypto.{KeyGenerator, Cipher}

import com.cryptoutility.protocol.crypto.{Base64Encode, Encrypt}
import play.api.Configuration

class EncryptionContext (publicKey: PublicKey, config: Configuration) {
  
  val symmetricAlgorithm = config.getString("cipher.symmetric.algorithm").get
  val asymmetricAlgorithm = config.getString("cipher.asymmetric.algorithm").get
  val secretKeyAlgorithm = config.getString("cipher.symmetric.key.algorithm").get

  def encrypt = Encrypt(symmetricAlgorithm, identity)(_, _)

  def cipher = {
    val key = secret
    val c = Cipher.getInstance(symmetricAlgorithm)
    c.init(Cipher.ENCRYPT_MODE, key)
    (key, c)
  }

  def secret = KeyGenerator.getInstance(secretKeyAlgorithm).generateKey()

  def encryptEncoded = Encrypt(symmetricAlgorithm, Base64Encode(_))(_, _)
  def wrap = Encrypt.wrap(asymmetricAlgorithm,  publicKey, Base64Encode(_))(_)
} 
开发者ID:ejosiah,项目名称:crypto-utility,代码行数:29,代码来源:EncryptionContext.scala

示例3: Cipher

//设置package包名称以及导入依赖的类
package com.github.wildprairie.common.utils

import java.nio.file.Paths
import java.security.{PrivateKey, PublicKey}


object Cipher {
  val RSA = new Cipher("RSA")
}

class Cipher(algorithm: String) {
  import java.nio.file.Files
  import java.security.KeyFactory
  import java.security.spec.X509EncodedKeySpec
  import java.security.spec.PKCS8EncodedKeySpec

  def generatePrivate: PrivateKey = {
    val keyBytes = Files.readAllBytes(Paths.get(getClass.getResource("/private_key.der").toURI))
    val spec = new PKCS8EncodedKeySpec(keyBytes)
    val kf = KeyFactory.getInstance(algorithm)
    kf.generatePrivate(spec)
  }

  def generatePublic: PublicKey = {
    val keyBytes = Files.readAllBytes(Paths.get(getClass.getResource("/public_key.der").toURI))
    val spec = new X509EncodedKeySpec(keyBytes)
    val kf = KeyFactory.getInstance(algorithm)
    kf.generatePublic(spec)
  }

  def decrypt(privateKey: PrivateKey, input: Array[Byte]): Array[Byte] = {
    val decrypt = javax.crypto.Cipher.getInstance(algorithm)
    decrypt.init(javax.crypto.Cipher.DECRYPT_MODE, privateKey)
    decrypt.doFinal(input)
  }
} 
开发者ID:OpenWakfu,项目名称:wildprairie,代码行数:37,代码来源:Cipher.scala

示例4: Friend

//设置package包名称以及导入依赖的类
package xyztr

import java.security.PublicKey


case class Friend(friendName: String, encodedPublicKeyOfFriend: Array[Byte]) {
  def publicKey = Crypto.getPublicKeyFromEncoded(encodedPublicKeyOfFriend)
}

object Friend {
  def apply(friendName: String, publicKeyOfFriend: PublicKey) = new Friend(friendName, publicKeyOfFriend.getEncoded)
}

case class FriendRequest(nameOfSender: String, encodedPublicKeyOfSender: Array[Byte]) {
  def publicKeyOfSender = Crypto.getPublicKeyFromEncoded(encodedPublicKeyOfSender)
}

object FriendRequest {
  def apply(sender: User) = new FriendRequest(sender.name, sender.publicKey.getEncoded)
}

case class FriendResponse(nameOfSender: Option[String], encodedPublicKeyOfSender: Option[Array[Byte]]) {
  def publicKeyOfSender = encodedPublicKeyOfSender.map(k => Crypto.getPublicKeyFromEncoded(k))
}

object FriendResponse {
  def apply(sender: User): FriendResponse = FriendResponse(Some(sender.name), Some(sender.publicKey.getEncoded))
  def apply(): FriendResponse = new FriendResponse(None, None)    // This is a way of rejecting the friend request
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:30,代码来源:Friend.scala

示例5: BubbleHandle

//设置package包名称以及导入依赖的类
package xyztr

import java.security.{PrivateKey, PublicKey}
import java.util.Date
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec

import xyztr.TierionClient.SaveBubbleRecordResponse


case class BubbleHandle(ipfsHash: String, encodedEncryptedEncryptionKey: Array[Byte], created: Long, blockchainHashId: Option[String]) extends Ordered[BubbleHandle] {
  def decryptSecretKey(privateKey: PrivateKey): SecretKey = new SecretKeySpec(Crypto.decryptWithPrivateKey(encodedEncryptedEncryptionKey, privateKey), "AES")

  def compare(that: BubbleHandle) = {
    val milliDiff = that.created - this.created
    if (milliDiff < 0) -1
    else if (milliDiff > 0) +1
    else 0
  }
}

object BubbleHandle {
  def apply(ipfsHash: String, secretKey: SecretKey, publicKey: PublicKey, response: Option[SaveBubbleRecordResponse] = None): BubbleHandle = response.isDefined match {
    case false => BubbleHandle(ipfsHash, Crypto.encryptWithPublicKey(secretKey.getEncoded, publicKey), new Date().getTime, None)
    case true  => BubbleHandle(ipfsHash, Crypto.encryptWithPublicKey(secretKey.getEncoded, publicKey), response.get.timestamp, Some(response.get.id))
  }
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:28,代码来源:BubbleHandle.scala

示例6: JWTPublicKeyProviderImpl

//设置package包名称以及导入依赖的类
package access

import java.security.spec.{ECPoint, ECPublicKeySpec}
import java.security.{KeyFactory, PublicKey, Security}

import com.google.inject.Inject
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.spec.ECNamedCurveSpec
import play.api.Configuration

class JWTPublicKeyProviderImpl @Inject()(configuration: Configuration) extends JWTPublicKeyProvider {

  override def publicKey: PublicKey = {
    val xRaw: String = configuration.getString("accessService.X").getOrElse("")
    val yRaw: String = configuration.getString("accessService.Y").getOrElse("")
    val X = BigInt(xRaw, 16)
    val Y = BigInt(yRaw, 16)
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider())
    val curveParams = ECNamedCurveTable.getParameterSpec("P-521")
    val curveSpec =
      new ECNamedCurveSpec("P-521", curveParams.getCurve, curveParams.getG, curveParams.getN, curveParams.getH)
    val publicSpec = new ECPublicKeySpec(new ECPoint(X.underlying(), Y.underlying()), curveSpec)
    KeyFactory.getInstance("ECDSA", "BC").generatePublic(publicSpec)
  }

} 
开发者ID:shafiquejamal,项目名称:api-gateway-template,代码行数:27,代码来源:JWTPublicKeyProviderImpl.scala

示例7: UserContext

//设置package包名称以及导入依赖的类
package mu.node.echod.models

import java.security.{PrivateKey, PublicKey}
import java.util.Calendar

import mu.node.echod.util.KeyUtils
import pdi.jwt.Jwt
import play.api.libs.json.Json

import scala.util.Try

case class UserContext(userId: String) extends KeyUtils {

  def toJwt(expiryMillis: Long, jwtSigningKey: PrivateKey): String = {
    val json =
      s"""{
         |  "sub": "$userId",
         |  "exp": $expiryMillis
         |}
         |""".stripMargin
    Jwt.encode(json, jwtSigningKey, jwtDsa)
  }
}

object UserContext extends KeyUtils {
  def fromJwt(jwt: String, jwtVerificationKey: PublicKey): Option[UserContext] = {
    Jwt
      .decode(jwt, jwtVerificationKey, Seq(jwtDsa))
      .flatMap(payload => Try(Json.parse(payload)))
      .toOption
      .filter(json => (json \ "exp").asOpt[Long].exists(notExpired))
      .flatMap(json => (json \ "sub").asOpt[String].map(UserContext(_)))
  }

  private def notExpired(expiryMillis: Long): Boolean =
    expiryMillis > Calendar.getInstance().getTimeInMillis
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:38,代码来源:UserContext.scala

示例8: loadPkcs8PrivateKey

//设置package包名称以及导入依赖的类
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)
  }
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:25,代码来源:KeyUtils.scala

示例9: UserContextServerInterceptor

//设置package包名称以及导入依赖的类
package mu.node.echod.grpc

import java.security.PublicKey

import com.google.common.collect.Iterables
import io.grpc._
import mu.node.echod.models.UserContext


class UserContextServerInterceptor(jwtVerificationKey: PublicKey) extends ServerInterceptor {

  override def interceptCall[ReqT, RespT](
      call: ServerCall[ReqT, RespT],
      headers: Metadata,
      next: ServerCallHandler[ReqT, RespT]): ServerCall.Listener[ReqT] = {
    readBearerToken(headers) flatMap { token =>
      UserContext.fromJwt(token, jwtVerificationKey)
    } map { userContext =>
      val withUserContext = Context
        .current()
        .withValue[UserContext](UserContextServerInterceptor.userContextKey, userContext)
      Contexts.interceptCall(withUserContext, call, headers, next)
    } getOrElse {
      next.startCall(call, headers)
    }
  }

  private def readBearerToken(headers: Metadata): Option[String] = {
    val authorizationHeaderKey = Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER)
    try {
      Iterables
        .toArray(headers.getAll(authorizationHeaderKey), classOf[String])
        .find(header => header.startsWith("Bearer "))
        .map(header => header.replaceFirst("Bearer ", ""))
    } catch {
      case _: Exception => Option.empty
    }
  }
}

object UserContextServerInterceptor {
  val userContextKey: Context.Key[UserContext] = Context.key("user_context")
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:44,代码来源:UserContextServerInterceptor.scala

示例10: SshUtil

//设置package包名称以及导入依赖的类
package gitbucket.core.ssh

import java.security.PublicKey
import java.util.Base64

import org.apache.sshd.common.config.keys.KeyUtils
import org.apache.sshd.common.util.buffer.ByteArrayBuffer
import org.eclipse.jgit.lib.Constants
import org.slf4j.LoggerFactory


object SshUtil {

  private val logger = LoggerFactory.getLogger(SshUtil.getClass)

  def str2PublicKey(key: String): Option[PublicKey] = {
    // TODO RFC 4716 Public Key is not supported...
    val parts = key.split(" ")
    if (parts.size < 2) {
      logger.debug(s"Invalid PublicKey Format: ${key}")
      None
    } else {
      try {
        val encodedKey = parts(1)
        val decode = Base64.getDecoder.decode(Constants.encodeASCII(encodedKey))
        Some(new ByteArrayBuffer(decode).getRawPublicKey)
      } catch {
        case e: Throwable =>
          logger.debug(e.getMessage, e)
          None
      }
    }
  }

  def fingerPrint(key: String): Option[String] =
    str2PublicKey(key) map KeyUtils.getFingerPrint

} 
开发者ID:piggymumu,项目名称:gitbucket,代码行数:39,代码来源:SshUtil.scala

示例11: PemKeyUtil

//设置package包名称以及导入依赖的类
package jwtyped

import java.security.{PrivateKey, PublicKey}
import java.security.spec.PKCS8EncodedKeySpec
import java.util.Base64
import java.security.spec.X509EncodedKeySpec
import java.security.KeyFactory

object PemKeyUtil {

  def decodePublicKey(pem: String): PublicKey = {
    val bytes = pemToDer(pem)
    decodePublicKey(bytes)
  }

  def decodePrivateKey(pem: String): PrivateKey = {
    val bytes = pemToDer(pem)
    decodePrivateKey(bytes)
  }

  def pemToDer(pem: String): Array[Byte] = {
    Base64.getDecoder.decode(trimBeginEnd(pem))
  }

  def trimBeginEnd(pem: String) = {
    pem.replaceAll("-----BEGIN (.*)-----", "")
      .replaceAll("-----END (.*)----", "")
      .replaceAll("\r\n", "")
      .replaceAll("\n", "")
      .trim()
  }

  def decodePublicKey(der: Array[Byte]): PublicKey = {
    val spec = new X509EncodedKeySpec(der)
    val rsa = KeyFactory.getInstance("RSA")
    rsa.generatePublic(spec)
  }

  def decodePrivateKey(der: Array[Byte]): PrivateKey = {
    val spec = new PKCS8EncodedKeySpec(der)
    val rsa = KeyFactory.getInstance("RSA")
    rsa.generatePrivate(spec)
  }

} 
开发者ID:etaty,项目名称:jwtyped,代码行数:46,代码来源:PemKeyUtil.scala

示例12: AlgoPublicKey

//设置package包名称以及导入依赖的类
package jwtyped.algorithm

import java.security.{PrivateKey, PublicKey}

import jwtyped._

case class AlgoPublicKey(algorithm: String, publicKey: PublicKey)

object AlgoPublicKey {
  implicit val ecdsaVerify = new Verify[AlgoPublicKey] {
    override def verify(algorithm: AlgoPublicKey, message: Message, signature: Signature): Boolean = {
      val ecdsaVerify = java.security.Signature.getInstance(algorithm.algorithm)
      ecdsaVerify.initVerify(algorithm.publicKey)
      ecdsaVerify.update(message.getBytes)
      ecdsaVerify.verify(signature.value)
    }
  }
}

case class AlgoPrivateKey(algorithm: String, privateKey: PrivateKey)

object AlgoPrivateKey {
  implicit val ecdsaSign = new Sign[AlgoPrivateKey] {
    override def sign(algorithm: AlgoPrivateKey, message: Message): Signature = {
      val ecdsaSign = java.security.Signature.getInstance(algorithm.algorithm)
      ecdsaSign.initSign(algorithm.privateKey)
      ecdsaSign.update(message.getBytes)
      Signature(ecdsaSign.sign())
    }
  }
}

case class AlgoPublicPrivateKey(algorithm: String, publicKey: PublicKey, privateKey: PrivateKey)

object AlgoPublicPrivateKey {

  def toAlgoPublicKey(algo: AlgoPublicPrivateKey): AlgoPublicKey = AlgoPublicKey(algo.algorithm, algo.publicKey)

  def toAlgoPrivateKey(algo: AlgoPublicPrivateKey): AlgoPrivateKey = AlgoPrivateKey(algo.algorithm, algo.privateKey)

  implicit val algoPublicPrivateKeySign = new Sign[AlgoPublicPrivateKey] {
    override def sign(algorithm: AlgoPublicPrivateKey, message: Message): Signature = {
      Sign[AlgoPrivateKey].sign(AlgoPublicPrivateKey.toAlgoPrivateKey(algorithm), message)
    }
  }

  implicit val algoPublicPrivateKeyVerify = new Verify[AlgoPublicPrivateKey] {
    override def verify(algorithm: AlgoPublicPrivateKey, message: Message, signature: Signature): Boolean = {
      Verify[AlgoPublicKey].verify(AlgoPublicPrivateKey.toAlgoPublicKey(algorithm), message, signature)
    }
  }
} 
开发者ID:etaty,项目名称:jwtyped,代码行数:53,代码来源:AlgoPublicPrivateKey.scala

示例13: JWTPublicKeyProviderImpl

//设置package包名称以及导入依赖的类
package com.eigenroute.authentication

import java.security.spec.{ECPoint, ECPublicKeySpec}
import java.security.{KeyFactory, PublicKey, Security}

import com.typesafe.config.ConfigFactory
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.spec.ECNamedCurveSpec

class JWTPublicKeyProviderImpl extends JWTPublicKeyProvider {

  val configuration = ConfigFactory.load()

  override def publicKey: PublicKey = {
    val xRaw: String = configuration.getString("eigenrouteAuthenticatedAction.publicKey.X")
    val yRaw: String = configuration.getString("eigenrouteAuthenticatedAction.publicKey.Y")
    val X = BigInt(xRaw, 16)
    val Y = BigInt(yRaw, 16)
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider())
    val curveParams = ECNamedCurveTable.getParameterSpec("P-521")
    val curveSpec =
      new ECNamedCurveSpec("P-521", curveParams.getCurve, curveParams.getG, curveParams.getN, curveParams.getH)
    val publicSpec = new ECPublicKeySpec(new ECPoint(X.underlying(), Y.underlying()), curveSpec)
    KeyFactory.getInstance("ECDSA", "BC").generatePublic(publicSpec)
  }

} 
开发者ID:shafiquejamal,项目名称:eigenroute-authenticated-action,代码行数:28,代码来源:JWTPublicKeyProviderImpl.scala


注:本文中的java.security.PublicKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。