本文整理汇总了Scala中java.security.PrivateKey类的典型用法代码示例。如果您正苦于以下问题:Scala PrivateKey类的具体用法?Scala PrivateKey怎么用?Scala PrivateKey使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PrivateKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例2: Session
//设置package包名称以及导入依赖的类
package akka.stream.alpakka.googlecloud.pubsub
import java.security.PrivateKey
import java.time.Instant
import akka.actor.ActorSystem
import akka.stream.Materializer
import scala.concurrent.Future
@akka.annotation.InternalApi
private[pubsub] class Session(clientEmail: String, privateKey: PrivateKey) {
protected var maybeAccessToken: Option[Future[AccessTokenExpiry]] = None
protected def now = Instant.now()
protected val httpApi: HttpApi = HttpApi
private def getNewToken()(implicit as: ActorSystem, materializer: Materializer): Future[AccessTokenExpiry] = {
val accessToken = httpApi.getAccessToken(clientEmail = clientEmail, privateKey = privateKey, when = now)
maybeAccessToken = Some(accessToken)
accessToken
}
private def expiresSoon(g: AccessTokenExpiry): Boolean =
g.expiresAt < (now.getEpochSecond + 60)
def getToken()(implicit as: ActorSystem, materializer: Materializer): Future[String] = {
import materializer.executionContext
maybeAccessToken
.getOrElse(getNewToken())
.flatMap { result =>
if (expiresSoon(result)) {
getNewToken()
} else {
Future.successful(result)
}
}
.map(_.accessToken)
}
}
示例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)
}
}
示例4: Plist
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.security.{PrivateKey, Signature}
import java.util.Base64
import org.bouncycastle.pkcs.PKCS10CertificationRequest
case class Plist(csr: PKCS10CertificationRequest, chain: String, privateKey: PrivateKey) {
def toXml = {
val csrString = Base64.getEncoder.encodeToString(csr.getEncoded)
val signature = Signature.getInstance("SHA1WithRSA")
signature.initSign(privateKey)
signature.update(csr.getEncoded)
val signatureString = Base64.getEncoder.encodeToString(signature.sign)
s"""<?xml version="1.0" encoding="UTF-8"?>
|<!DOCTYPE plist PUBLIC "-//Apple Inc//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|<plist version="1.0">
|<dict>
|<key>PushCertRequestCSR</key>
|<string>
|$csrString
|</string>
|<key>PushCertCertificateChain</key>
|<string>
|$chain
|</string>
|<key>PushCertSignature</key>
|<string>
|$signatureString
|</string>
|</dict>
|</plist>
""".stripMargin
}
}
示例5: Pkcs12Convertor
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.io.{OutputStream, Reader}
import java.security.cert.X509Certificate
import java.security.{KeyStore, PrivateKey}
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import org.bouncycastle.openssl.{PEMKeyPair, PEMParser}
object Pkcs12Convertor {
def parsePrivateKey(reader: Reader): PrivateKey = {
val pemParser = new PEMParser(reader)
val pemKeyPair = pemParser.readObject().asInstanceOf[PEMKeyPair]
new JcaPEMKeyConverter().getKeyPair(pemKeyPair).getPrivate
}
def parseCertificate(reader: Reader): X509Certificate = {
val pemParser = new PEMParser(reader)
val certificate = pemParser.readObject()
null
}
def write(os: OutputStream, privateKey: PrivateKey, password: Array[Char], certificate: X509Certificate): Unit = {
val keyStore = KeyStore.getInstance("pkcs12")
keyStore.load(null, password)
keyStore.setKeyEntry("1", privateKey, password, Seq(certificate).toArray)
keyStore.store(os, password)
}
}
示例6: PlistFactory
//设置package包名称以及导入依赖的类
package jp.pigumer
import java.security.PrivateKey
import java.util.Base64
import org.bouncycastle.pkcs.PKCS10CertificationRequest
object PlistFactory {
def generate(csr: PKCS10CertificationRequest,
vendorCertificate: String,
appleCertificate: String,
appleRootCertificate: String,
vendorPrivateKey: PrivateKey) = {
val plist = generatePlist(csr, vendorCertificate + "\n" + appleCertificate + "\n" + appleRootCertificate, vendorPrivateKey)
Base64.getEncoder.encodeToString(plist.getBytes())
}
def generatePlist(csr: PKCS10CertificationRequest,
chain: String,
vendorPrivateKey: PrivateKey) = {
val plist = Plist(csr, chain, vendorPrivateKey)
plist.toXml
}
}
示例7: 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))
}
}
示例8: JWTPrivateKeyProviderImpl
//设置package包名称以及导入依赖的类
package access
import java.security.spec.ECPrivateKeySpec
import java.security.{KeyFactory, PrivateKey, Security}
import com.google.inject.Inject
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.spec.ECNamedCurveSpec
import play.api.Configuration
class JWTPrivateKeyProviderImpl @Inject()(configuration: Configuration) extends JWTPrivateKeyProvider {
override def privateKey: PrivateKey = {
val sRaw: String = configuration.getString("accessService.S").getOrElse("")
val S = BigInt(sRaw, 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 privateSpec = new ECPrivateKeySpec(S.underlying(), curveSpec)
KeyFactory.getInstance("ECDSA", "BC").generatePrivate(privateSpec)
}
}
示例9: 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
}
示例10: 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)
}
}
示例11: RSA
//设置package包名称以及导入依赖的类
package utils
import java.security.{KeyFactory, PrivateKey}
import javax.crypto.Cipher
import java.util.Base64
import java.security.spec.RSAPrivateCrtKeySpec
import sun.security.util.DerInputStream
object RSA {
val privateKeyStr = "-----BEGIN RSA PRIVATE KEY-----\nMIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ\nWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR\naY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB\nAoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv\nxTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH\nm7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd\n8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF\nz/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5\nrN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM\nV7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe\naTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil\npsLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz\nuku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876\n-----END RSA PRIVATE KEY-----"
val privateKey: PrivateKey = {
val removedStr = privateKeyStr.replace("-----BEGIN RSA PRIVATE KEY-----\n", "").replace("-----END RSA PRIVATE KEY-----", "").replaceAll("\\s", "")
val derReader = new DerInputStream(Base64.getDecoder.decode(removedStr))
val seq = derReader.getSequence(0)
val modulus = seq(1).getBigInteger
val publicExp = seq(2).getBigInteger
val privateExp = seq(3).getBigInteger
val prime1 = seq(4).getBigInteger
val prime2 = seq(5).getBigInteger
val exp1 = seq(6).getBigInteger
val exp2 = seq(7).getBigInteger
val crtCoef = seq(8).getBigInteger
val keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef)
val kf = KeyFactory.getInstance("RSA")
kf.generatePrivate(keySpec)
}
def decrypt(text: String): String = {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.DECRYPT_MODE, privateKey)
new String(cipher.doFinal(Base64.getDecoder.decode(text)))//TODO: verify text to be 128bit
}
}
示例12: JiraApi
//设置package包名称以及导入依赖的类
package de.codecentric.ccdashboard.service.timesheet.oauth
import java.security.spec.PKCS8EncodedKeySpec
import java.security.{KeyFactory, PrivateKey}
import java.util.Base64
import com.github.scribejava.core.builder.api.DefaultApi10a
import com.github.scribejava.core.model.OAuth1RequestToken
import com.github.scribejava.core.services.{RSASha1SignatureService, SignatureService}
class JiraApi(val privateKey: String, val authorizeUrl: String, val requestTokenResource: String, val accessTokenResource: String) extends DefaultApi10a {
def getAccessTokenEndpoint: String = accessTokenResource
def getAuthorizationUrl(requestToken: OAuth1RequestToken): String = String.format(authorizeUrl, requestToken.getToken)
def getRequestTokenEndpoint: String = requestTokenResource
override def getSignatureService: SignatureService = new RSASha1SignatureService(getPrivateKey)
private def getPrivateKey: PrivateKey = try {
val key: Array[Byte] = Base64.getDecoder.decode(privateKey) // this is the PEM encoded PKCS#8 private key
val keySpec: PKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(key)
val kf: KeyFactory = KeyFactory.getInstance("RSA")
kf.generatePrivate(keySpec)
}
catch {
case e: Exception => {
throw new RuntimeException(e)
}
}
}
示例13: 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)
}
}
示例14: 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)
}
}
}
示例15: JWTPrivateKeyProviderImpl
//设置package包名称以及导入依赖的类
package com.eigenroute.authentication
import java.security.spec.ECPrivateKeySpec
import java.security.{KeyFactory, PrivateKey, Security}
import com.typesafe.config.ConfigFactory
import org.bouncycastle.jce.ECNamedCurveTable
import org.bouncycastle.jce.spec.ECNamedCurveSpec
class JWTPrivateKeyProviderImpl extends JWTPrivateKeyProvider {
val configuration = ConfigFactory.load()
override def privateKey: PrivateKey = {
val sRaw: String = configuration.getString("eigenrouteAuthenticatedAction.privateKey.S")
val S = BigInt(sRaw, 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 privateSpec = new ECPrivateKeySpec(S.underlying(), curveSpec)
KeyFactory.getInstance("ECDSA", "BC").generatePrivate(privateSpec)
}
}
开发者ID:shafiquejamal,项目名称:eigenroute-authenticated-action,代码行数:26,代码来源:JWTPrivateKeyProviderImpl.scala