• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala X509Certificate类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: InsecureClient

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils

import com.sun.jersey.api.client.{Client, ClientResponse}
import org.json4s.jackson.Serialization._
import javax.ws.rs.core.MediaType
import javax.net.ssl.{HostnameVerifier, SSLContext, SSLSession, X509TrustManager}

import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.client.urlconnection.HTTPSProperties
import java.security.cert.X509Certificate

import com.sun.jersey.api.client.filter.GZIPContentEncodingFilter

class InsecureClient {

  implicit val defaultFormats = json.JsonExtraction.formats

  private val jsonContentType = MediaType.APPLICATION_JSON + ";charset=utf-8"

  private val sslContext = SSLContext.getInstance("SSL")
  sslContext.init(null, Array(new InsecureTrustManager), null)

  private val config = new DefaultClientConfig()

  config.getProperties.put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
    new HostnameVerifier() {
      override def verify(s: String, sslSession: SSLSession): Boolean = true
    },
    sslContext
  ))


  private val client = Client.create(config)
  client.addFilter(new GZIPContentEncodingFilter(false))

  def get[A](url: String)(implicit m: Manifest[A]): A = {
    val response = client.resource(url).accept(jsonContentType).get[ClientResponse](classOf[ClientResponse])
    val responseBody = response.getEntity(classOf[String])
    println(s"TARGET = $url")
    response.getStatus match {
      case 200 => read[A](responseBody)
      case _ => throw new RuntimeException(s"Unexpected response from $url, status code ${response.getStatus} : $responseBody")
    }
  }

  def getRawResponse(url: String, contentType: String = jsonContentType)(implicit m: Manifest[String]): (Int, String) = {
    val response = client.resource(url).accept(contentType).get[ClientResponse](classOf[ClientResponse])
    val responseBody = response.getEntity(classOf[String])
    val status = response.getStatus
    (status, responseBody)
  }
}

class InsecureTrustManager extends X509TrustManager {
  def checkClientTrusted(p1: Array[X509Certificate], p2: String) {}

  def checkServerTrusted(p1: Array[X509Certificate], p2: String) {}

  def getAcceptedIssuers: Array[X509Certificate] = Array()
} 
开发者ID:danewatts,项目名称:zap-automation,代码行数:61,代码来源:InsecureClient.scala


示例2: Client

//设置package包名称以及导入依赖的类
package cz.alenkacz.marathon.scaler.rabbitmq

import java.net.URL
import java.security.cert.X509Certificate

import com.rabbitmq.http.client.{Client => HttpClient}
import org.apache.http.conn.ssl.{
  SSLConnectionSocketFactory,
  SSLContextBuilder,
  SSLSocketFactory,
  TrustStrategy
}

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

class Client(apiUrl: String, username: String, password: String) {
  lazy val trustAllSslContext = new SSLContextBuilder()
    .loadTrustMaterial(null, new TrustStrategy() {
      override def isTrusted(chain: Array[X509Certificate],
                             authType: String): Boolean = true
    })
    .build()
  lazy val client =
    new HttpClient(new URL(apiUrl), username, password, trustAllSslContext)

  def queueExists(vhost: String, queueName: String): Try[Boolean] = {
    Try(client.getQueue(vhost, queueName) match {
      case null => false
      case _ => true
    })
  }

  def messageCount(vhost: String, queueName: String): Try[Long] = {
    Try(client.getQueue(vhost, queueName).getTotalMessages)
  }

  def purgeQueue(vhost: String, queueName: String): Unit =
    client.purgeQueue(vhost, queueName)

  case class Queue(messages: Int)
} 
开发者ID:alenkacz,项目名称:marathon-rabbitmq-autoscale,代码行数:42,代码来源:Client.scala


示例3: HttpClientProvider

//设置package包名称以及导入依赖的类
package org.zalando.react.nakadi.client.providers

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}

import akka.actor.ActorContext
import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ClientConnectionSettings
import akka.http.scaladsl.{Http, HttpsConnectionContext}
import akka.stream.scaladsl.Flow

import scala.concurrent.Future
import scala.concurrent.duration._


class HttpClientProvider(actorContext: ActorContext,
                         server: String, port: Int,
                         isConnectionSSL: Boolean = false,
                         acceptAnyCertificate: Boolean = false,
                         connectionTimeout: FiniteDuration) {

  val http = Http(actorContext.system)

  private val settings = {
    ClientConnectionSettings
      .apply(actorContext.system)
      .withConnectingTimeout(connectionTimeout)
      .withIdleTimeout(Duration.Inf)
  }

  val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = {

    isConnectionSSL match {
      case true =>
        val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else {

          val permissiveTrustManager: TrustManager = new X509TrustManager() {
            override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
          }

          val ctx = SSLContext.getInstance("TLS")
          ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom())
          ctx
        }
        http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings)
      case false =>
        http.outgoingConnection(server, port, settings = settings)
    }
  }

} 
开发者ID:zalando-nakadi,项目名称:reactive-nakadi,代码行数:56,代码来源:HttpClientProvider.scala


示例4: 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)
  }

} 
开发者ID:takesection,项目名称:apple-mdm-certificate,代码行数:33,代码来源:Pkcs12Convertor.scala


示例5: TransportMessagePipeline

//设置package包名称以及导入依赖的类
package one.lockstep.monolock.client.pipeline
import java.security.cert.X509Certificate

import one.lockstep.lock.client.transport.TransportProvider
import one.lockstep.monolock.protocol._
import one.lockstep.util._
import one.lockstep.util.codec._
import one.lockstep.util.crypto.Ciphersuite
import one.lockstep.util.internal.BytesModule.Bytes
import one.lockstep.util.protocol._

import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag

class TransportMessagePipeline(createTransport: () => TransportProvider,
                               rootServerCertOpt: Option[X509Certificate],
                               transportCiphersuite: Ciphersuite)
                              (implicit ec: ExecutionContext) extends MessagePipeline with Logging {

  private lazy val transport = createTransport()
  private val handshake = new Handshake(transport, rootServerCertOpt) //immediately starts handshake
  private val encapsulationStage = new EncapsulationStage
  private implicit val implicitCiphersuite = transportCiphersuite

  override def send(request: MonolockRequest): Future[MonolockResponse] = request match {
    case enrollmentRequest: EnrollmentRequest =>
      logger.debug(s"sending enrollment request, lockId = ${enrollmentRequest.lockId}")
      send[EnrollmentRequest, EnrollmentResponse]("", enrollmentRequest)

    case unlockRequest: UnlockRequest =>
      logger.debug(s"sending unlock request, lockId = ${unlockRequest.lockId}")
      send[UnlockRequest, UnlockResponse]("", unlockRequest)
  }

  private def send[Request : Protocol : ClassTag, Response : Protocol : ClassTag](path: String, request: Request): Future[Response] = {
    handshake.join().flatMap { publicKey =>
      val serialized = serialize(request)
      val (encapsulated, responseKey) = encapsulationStage.encapsulate(serialized, publicKey)
      transport.sendReceive("", encapsulated).map(encalsulatedResponse => {
        val decapsulated = encapsulationStage.decapsulate(encalsulatedResponse, responseKey)
        deserialize[Response](decapsulated)
      })
    }
  }

  override def shutdown(): Unit = {
    transport.shutdown()
  }

  private def serialize[Request: Protocol : ClassTag](request: Request): Bytes =
    Protocol.encode[Request](request)

  private def deserialize[Response : Protocol : ClassTag](response: Bytes): Response =
    Protocol.decode[Response](response)

} 
开发者ID:lockstep-one,项目名称:vault,代码行数:57,代码来源:TransportMessagePipeline.scala


示例6: Handshake

//设置package包名称以及导入依赖的类
package one.lockstep.monolock.client.pipeline

import java.io.IOException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit

import one.lockstep.lock.client.transport.TransportProvider
import one.lockstep.monolock.protocol._
import one.lockstep.util._
import one.lockstep.util.codec._
import one.lockstep.util.crypto.PublicKey

import scala.concurrent._
import scala.util.{Failure, Success}
import one.lockstep.util.protocol._

import scala.concurrent.duration.Duration

class Handshake(transport: TransportProvider, rootCertOpt: Option[X509Certificate] = None)
               (implicit ec: ExecutionContext) extends Logging {

  private[this] var currentHandshake: Future[PublicKey] = sendHandshake()

  def join(): Future[PublicKey] = synchronized {
    if (currentHandshake.value.exists(_.isFailure))
      currentHandshake = sendHandshake()
    currentHandshake
  }

  def sendHandshake(): Future[PublicKey] = {
    logger.debug("sending handshake")
    val serialized = Protocol.encode(HandshakeRequest())
    transport.sendReceive("handshake", serialized).map { response =>
      val certificates = Protocol.decode[HandshakeResponse](response).certificates
      validate(certificates)
      PublicKey(certificates.last.getPublicKey.getEncoded)
    } andThen {
      case Success(publicKey) =>
        logger.debug(s"handshake completed successfully; public key: ${show(publicKey.raw)}")
      case Failure(cause: IOException) if cause.getMessage.endsWith("Canceled") =>
        logger.debug("handshake cancelled")
      case Failure(cause) =>
        logger.error("handshake failed: " + cause)
        logger.debug("handshake failure details", cause)
    }
  }

  private def validate(certificates: Seq[X509Certificate]) = {
    // if rootCertOpt is not defined then we go trustless
    logger.debug(s"handshake received certificate chain of size ${certificates.size}")
    require(certificates.nonEmpty, "certificate chain must be non-empty")
    require(certificates.size <= 2, "certificate chain must not be longer than 2")
    cert.verify(rootCertOpt.toSeq ++ certificates)
    val last = certificates.last
    val validityDuration = Duration(last.getNotAfter.getTime - last.getNotBefore.getTime, TimeUnit.MILLISECONDS)
    require(validityDuration.toDays <= 2, "certificate validitiy duration must be at most 2 days")
    // todo validate specific attributes of the incoming certificates
  }


} 
开发者ID:lockstep-one,项目名称:vault,代码行数:62,代码来源:Handshake.scala


示例7: createPipeline

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

import java.security.cert.X509Certificate

import one.lockstep.lock.client._
import one.lockstep.multilock.client.pipeline._
import one.lockstep.multilock.protocol.Server
import one.lockstep.test.BaseSpec
import one.lockstep.util.concurrent.ExecutionEnv
import one.lockstep.util.crypto.Ciphersuite

import scala.concurrent.ExecutionContext
import scala.concurrent.forkjoin.ForkJoinPool
import scala.language.implicitConversions

trait MultilockManagerFixtures extends LockManagerFixtures {
  spec: BaseSpec =>

  trait MultilockPipelineFixture extends PipelineFixture {
    type Pipeline = one.lockstep.multilock.client.pipeline.MessagePipeline

    // this could not be abstract, since usages exist where an overriding fixture must reference super.createPipeline()
    override def createPipeline(): MessagePipeline = ???
  }

  trait MultilockHttpPipelineFixture extends MultilockPipelineFixture with HttpTransportProviderFixture {

    def transportCiphersuite: Ciphersuite
    def certificates: Seq[(Server, Option[X509Certificate])]

    override def createPipeline(): MessagePipeline = {
      import ExecutionEnv.Implicits._
      new TransportMessagePipeline(createTransportProvider, certificates, transportCiphersuite)
    }
  }

  trait MultilockManagerFixture extends LockManagerFixture {
    this: TransactionalFixture with MultilockPipelineFixture =>

    def protocolCiphersuite: Ciphersuite
    def servers: Seq[Server]

    lazy val lockManagerId = spec.nextId()
    lazy val lockManagerName = s"${spec.getClass.getSimpleName}$lockManagerId"
    lazy val lockManagerExecutor = new ForkJoinPool().withCleanup("client executor")(_.shutdown())
    lazy val lockManagerExecutionContext = ExecutionContext.fromExecutor(lockManagerExecutor)

    override def lockManager: LockManager =
      new MultilockManager(createPipeline, servers, protocolCiphersuite)(lockManagerExecutionContext)
  }
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:52,代码来源:MultilockManagerFixtures.scala


示例8: Ca

//设置package包名称以及导入依赖的类
package one.lockstep.util.ca

import java.security.cert.X509Certificate
import java.security.{PrivateKey => JPrivateKey}
import java.time.ZonedDateTime
import java.time.temporal._
import java.util.Date

import sun.security.tools.keytool.CertAndKeyGen
import sun.security.x509.{X500Name, X509CertImpl, X509CertInfo}
import one.lockstep.util._
import scala.concurrent.duration.Duration

class Ca(keyType: String, sigAlg: String, providerName: String, keyLength: Int) { // "EC", "SHA256withECDSA", "SunEC", 256

  def generateAndSign(issuerOpt: Option[CertifiedKeyPair],
                      subjectName: String, forwardValidity: Duration): CertifiedKeyPair = {
    generateAndSign(issuerOpt, subjectName, Duration.Zero, forwardValidity)
  }

  def generateAndSign(issuerOpt: Option[CertifiedKeyPair],
                      subjectName: String, backwardsValidity: Duration, forwardValidity: Duration): CertifiedKeyPair = {

    val gen = new CertAndKeyGen(keyType, sigAlg, providerName)
    gen.setRandom(random)
    gen.generate(keyLength)
    val now = ZonedDateTime.now()
    val start = now.minus(backwardsValidity.toSeconds, ChronoUnit.SECONDS)
    val end = now.plus(forwardValidity.toSeconds, ChronoUnit.SECONDS)
    val totalSec = java.time.Duration.between(start, end).getSeconds
    val selfSigned = gen.getSelfCertificate(new X500Name(subjectName), Date.from(start.toInstant), totalSec)
    val certificate = issuerOpt.fold(ifEmpty = selfSigned) { issuer =>
      signCert(selfSigned, issuer.certificate, issuer.privateKey)
    }
    CertifiedKeyPair(gen.getPrivateKey, certificate)
  }

  def signCert(certificate: X509Certificate, issuerCert: X509Certificate, issuerKey: JPrivateKey): X509Certificate = {
    val certInfo = new X509CertInfo(certificate.getTBSCertificate) <| (_.set(X509CertInfo.ISSUER, issuerCert.getIssuerDN))
    new X509CertImpl(certInfo) <| (_.sign(issuerKey, issuerCert.getSigAlgName))
  }

}

object Ca {
  val default = new Ca("EC", "SHA256withECDSA", "SunEC", keyLength = 256)
} 
开发者ID:lockstep-one,项目名称:vault,代码行数:48,代码来源:Ca.scala


示例9: CertSpec

//设置package包名称以及导入依赖的类
package one.lockstep.monolock

import java.security.cert.X509Certificate

import one.lockstep.test.BaseSpec
import one.lockstep.util._
import one.lockstep.util.ca.Ca

import scala.concurrent.duration._
import one.lockstep.util.codec._
import cert._

class CertSpec extends BaseSpec with Logging {
  val ca = new Ca("EC", "SHA256withECDSA", "SunEC", 256)

  "self-signed certificate should be verifiable" in {
    val selfSigned = ca.generateAndSign(issuerOpt = None, "CN=Lockstep Monolock Server", 1.day ,3600.seconds)
    logger.debug(s"issuer DN = ${selfSigned.certificate.getIssuerDN}")
    logger.debug(s"key usage = ${selfSigned.certificate.getKeyUsage}")
    cert.verify(Seq(selfSigned.certificate))
  }

  "verification of expired certificate should fail" in {
    val selfSigned = ca.generateAndSign(issuerOpt = None, "CN=Lockstep Monolock Server", 0.seconds)
    Thread.sleep(10)
    the [Exception] thrownBy cert.verify(Seq(selfSigned.certificate))
  }

  "self-signed certificate-chain should be verifiable" in {
    val cert1 = ca.generateAndSign(None, "CN=Lockstep Monolock Server", 3600.seconds)
    val cert2 = ca.generateAndSign(Some(cert1), "CN=Lockstep Monolock Server", 3600.seconds)
    val cert3 = ca.generateAndSign(Some(cert2), "CN=Lockstep Monolock Server", 3600.seconds)
    cert.verify(Seq(cert1.certificate, cert2.certificate, cert3.certificate))
  }

  "certificate chain should be verifiable against a trusted root" in {
    val root = ca.generateAndSign(None , "CN=Lockstep Monolock Root, O=Customer.x", 3600.second)
    val cert1 = ca.generateAndSign(Some(root) , "CN=Lockstep Monolock Server Root[2], O=Customer.x ", 3600.seconds)
    val cert2 = ca.generateAndSign(Some(cert1), "CN=Lockstep Monolock Server Short-Term [2], O=Customer.x", 3600.second)
    cert.verify(Seq(root.certificate, cert1.certificate, cert2.certificate))
  }

  "x509 certificate should be reconstructable from its encoded format" in {
    val certificate = ca.generateAndSign(issuerOpt = None, "CN=Lockstep Monolock Server", 3600.seconds).certificate
    val reconstructed = decode[X509Certificate](certificate.getEncoded)
    cert.verify(Seq(reconstructed))
  }

  "x509 certificate-chain should be reconstructable from its encoded format" in {
    val cert1 = ca.generateAndSign(None , "CN=Lockstep Monolock Server", 3600.seconds)
    val cert2 = ca.generateAndSign(Some(cert1), "CN=Lockstep Monolock Server", 3600.seconds)
    val cert3 = ca.generateAndSign(Some(cert2), "CN=Lockstep Monolock Server", 3600.seconds)
    val reconstructed2 = decode[X509Certificate](cert2.certificate.getEncoded)
    val reconstructed3 = decode[X509Certificate](cert3.certificate.getEncoded)
    cert.verify(Seq(cert1.certificate, reconstructed2, reconstructed3))
  }

} 
开发者ID:lockstep-one,项目名称:vault,代码行数:59,代码来源:CertSpec.scala


示例10: verify

//设置package包名称以及导入依赖的类
package one.lockstep.util

import java.io.ByteArrayInputStream
import java.security.cert.{CertificateFactory, X509Certificate}
import java.util

import one.lockstep.monolock.protocol.Versions
import scodec.Codec
import scodec.codecs._
import one.lockstep.util.protocol._

package object cert {

  
  def verify(chain: Seq[X509Certificate]): Unit = {
    require(chain.nonEmpty, "certificate chain must be non-empty")
    if (chain.size == 1) {
      val cert = chain.head
      cert.checkValidity()
      verifySelfSigned(cert)
    } else {
      val last = chain.last
      val rest = chain.init
      last.checkValidity()
      require(!util.Arrays.equals(last.getPublicKey.getEncoded, rest.last.getPublicKey.getEncoded),
        "chained certificates must be distinct")
      last.verify(rest.last.getPublicKey)
      verify(rest)
    }
  }

  def verifySelfSigned(cert: X509Certificate) = cert.verify(cert.getPublicKey)

  implicit lazy val certCodec: Codec[X509Certificate] = bytes.xmap[X509Certificate] (
    { bytes => decodeCert(bytes) },
    { cert => cert.getEncoded }
  )
  //Note: the below preface/protocol are used for client/server handshake, NOT for loading cert from configuration
  implicit lazy val certProtocol = Protocol[X509Certificate](Label("x509-certificate"), Versions.current, since = Versions.v1)

  private def decodeCert(encoded: Bytes): X509Certificate =
    try {
      val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
      val inputStream = new ByteArrayInputStream(encoded)
      try {
        certificateFactory.generateCertificate(inputStream).asInstanceOf[X509Certificate]
      } finally {
        inputStream.close()
      }
    } catch {
      case e: Exception =>
        val message: String = "failed to load certificate"
        throw new RuntimeException(message, e)
    }

} 
开发者ID:lockstep-one,项目名称:vault,代码行数:57,代码来源:package.scala


示例11: hostname

//设置package包名称以及导入依赖的类
package com.twitter.finagle.ssl

import com.twitter.finagle.SslHostVerificationException
import com.twitter.util.Try
import sun.security.util.HostnameChecker
import java.security.cert.X509Certificate
import javax.net.ssl.SSLSession


  def hostname(hostname: String): SessionVerifier = new SessionVerifier {
    val checker = HostnameChecker.getInstance(HostnameChecker.TYPE_TLS)

    override def apply(session: SSLSession): Option[Throwable] = {
      // We take the first certificate from the given `getPeerCertificates` array since the expected
      // array structure is peer's own certificate first followed by any certificate authorities.
      val isValid = session.getPeerCertificates.headOption.exists {
        case x509: X509Certificate => Try(checker.`match`(hostname, x509)).isReturn
        case _ => false
      }

      if (isValid) None
      else Some(new SslHostVerificationException(session.getPeerPrincipal.getName))
    }
  }
} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:26,代码来源:SessionVerifier.scala


示例12: IgnorantTrustManagerTest

//设置package包名称以及导入依赖的类
package com.twitter.finagle.ssl

import java.net.Socket
import java.security.cert.X509Certificate
import javax.net.ssl.SSLEngine
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar

@RunWith(classOf[JUnitRunner])
class IgnorantTrustManagerTest extends FunSuite with MockitoSugar {

  val authType = "DHE_DSS"
  val socket = mock[Socket]
  val engine = mock[SSLEngine]
  val cert = mock[X509Certificate]
  val chain = Array(cert)

  test("an IgnorantTrustManager can be created") {
    val tm = new IgnorantTrustManager()
    assert(tm != null)
  }

  test("an IgnorantTrustManager has no accepted issuers") {
    val tm = new IgnorantTrustManager()
    val issuers = tm.getAcceptedIssuers()
    assert(issuers.length == 0)
  }

  test("checkClientTrusted does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType)
  }

  test("checkClientTrusted with socket does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType, socket)
  }

  test("checkClientTrusted with engine does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkClientTrusted(chain, authType, engine)
  }

  test("checkServerTrusted does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType)
  }

  test("checkServerTrusted with socket does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType, socket)
  }

  test("checkServerTrusted with engine does not throw") {
    val tm = new IgnorantTrustManager()
    tm.checkServerTrusted(chain, authType, engine)
  }

} 
开发者ID:wenkeyang,项目名称:finagle,代码行数:62,代码来源:IgnorantTrustManagerTest.scala


示例13: HTTPClient

//设置package包名称以及导入依赖的类
package pi.jenkins.build

import java.io.InputStream
import java.security.cert.X509Certificate

import org.apache.http.HttpResponse
import org.apache.http.client.config.RequestConfig
import org.apache.http.config.{RegistryBuilder, SocketConfig}
import org.apache.http.conn.socket.{ConnectionSocketFactory, PlainConnectionSocketFactory}
import org.apache.http.conn.ssl.{SSLConnectionSocketFactory, SSLContexts, TrustStrategy}
import org.apache.http.impl.client.{CloseableHttpClient, HttpClients}
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.slf4j.LoggerFactory

object HTTPClient {

  type StreamHandler = (String, HttpResponse) ? InputStream

  private final val LOG = LoggerFactory.getLogger(HTTPClient.getClass)

  private val TIMEOUT: Int = 20 * 1000

  private val socketConfig: SocketConfig = SocketConfig.custom()
    .setSoTimeout(TIMEOUT)
    .setTcpNoDelay(true)
    .build()

  private val requestConfig: RequestConfig = RequestConfig.custom()
    .setSocketTimeout(TIMEOUT)
    .setConnectTimeout(TIMEOUT)
    .build()


  private val sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy {
    override def isTrusted(chain: Array[X509Certificate], authType: String): Boolean = true
  }).build()

  private val sslsf = new SSLConnectionSocketFactory(
    sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)

  private val socketFactoryRegistry = RegistryBuilder.create[ConnectionSocketFactory]().
    register("https", sslsf).
    register("http", PlainConnectionSocketFactory.INSTANCE).build()

  private val cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry)
  cm.setDefaultSocketConfig(socketConfig)
  cm.setMaxTotal(200)
  cm.setDefaultMaxPerRoute(20)

  val client: CloseableHttpClient = HttpClients.custom()
    .setDefaultRequestConfig(requestConfig)
    .setConnectionManager(cm)
    .build()

} 
开发者ID:jdevelop,项目名称:rpi-jenkins,代码行数:56,代码来源:HTTPClient.scala


示例14: lookupHex

//设置package包名称以及导入依赖的类
// Copyright (C) 2016 Grier Forensics. All Rights Reserved.
package com.grierforensics.danesmimeatoolset.rest

import java.security.cert.X509Certificate
import javax.ws.rs._
import javax.ws.rs.core.{MediaType, Response}

import com.grierforensics.danesmimeatoolset.service.{BadCertificateException, Context, GensonConfig}
import org.bouncycastle.cert.dane.DANEEntry
import org.bouncycastle.util.encoders.{DecoderException, Hex}


  @GET
  @Path("{email}/hex/{index}")
  def lookupHex(@PathParam("email") email: String, @PathParam("index") index: Int): String = {
    val result = lookupHex(email) match {
      case results if results.isDefinedAt(index) => results(index)
      case otherwise => throw new WebApplicationException(Response.status(404).entity("DANE not found for email address").build())
    }
    GensonConfig.genson.serialize(result)
  }

  // // // lookupDnsZoneLine

  @GET
  @Path("{email}/dnsZoneLine")
  def lookupDnsZoneLine(@PathParam("email") email: String): Seq[String] = {
    daneSmimeaService.fetchDaneEntries(email).map(daneSmimeaService.getDnsZoneLineForDaneEntry(_)) match {
      case Nil => throw new WebApplicationException(Response.status(404).build())
      case nonempty => nonempty
    }
  }

  @GET
  @Path("{email}/dnsZoneLine/{index}")
  def lookupDnsZoneLine(@PathParam("email") email: String, @PathParam("index") index: Int): String = {
    val result = lookupDnsZoneLine(email) match {
      case results if results.isDefinedAt(index) => results(index)
      case otherwise => throw new WebApplicationException(Response.status(404).entity("DANE not found for email address").build())
    }
    GensonConfig.genson.serialize(result)
  }

  // // // createDnsZoneLineAsText

  @POST
  @Path("{email}/dnsZoneLineForCert")
  @Consumes(Array(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN))
  def createDnsZoneLineAsText(@PathParam("email") email: String, certPem: String): String = {
    try {
      val cert: X509Certificate = daneSmimeaService.fromPem(certPem)
      val de2: DANEEntry = daneSmimeaService.createDANEEntry(email, cert)
      val result = daneSmimeaService.getDnsZoneLineForDaneEntry(de2)
      GensonConfig.genson.serialize(result)
    }
    catch {
      case [email protected](_: BadCertificateException | _: DecoderException) => throw new WebApplicationException(Response.status(400).entity(e.getMessage).build())
    }
  }
} 
开发者ID:grierforensics,项目名称:Great-DANE-Toolset,代码行数:61,代码来源:ToolsetResource.scala


示例15: PaymentProtocolSpec

//设置package包名称以及导入依赖的类
package fr.acinq.syscoin

import java.io._
import java.security._
import java.security.cert.{CertificateFactory, X509Certificate}
import java.security.spec.PKCS8EncodedKeySpec

import com.google.protobuf.ByteString
import org.syscoin.protocols.payments.Protos.{Output, PaymentDetails, PaymentRequest}
import org.bouncycastle.util.io.pem.PemReader
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

import scala.compat.Platform

@RunWith(classOf[JUnitRunner])
class PaymentProtocolSpec extends FlatSpec {
  val keystore = KeyStore.getInstance("JKS")
  keystore.load(classOf[PaymentProtocolSpec].getResourceAsStream("/cacerts"), null)
  val aliases = keystore.aliases()

  "Payment protocol" should "verify payment requests" in {
    val stream = classOf[PaymentProtocolSpec].getResourceAsStream("/r1411736682.syscoinpaymentrequest")
    val request = PaymentRequest.parseFrom(stream)
    val (name, publicKey, trustAnchor) = PaymentProtocol.verifySignature(request, keystore)
    assert(name === "www.syscoincore.org")

    // check that we get an exception if we attempt to modify payment details
    val details = PaymentDetails.parseFrom(request.getSerializedPaymentDetails)
    val request1 = request.toBuilder.setSerializedPaymentDetails(details.toBuilder.setPaymentUrl("foo").build().toByteString).build()
    intercept[RuntimeException] {
      PaymentProtocol.verifySignature(request1, keystore)
    }
  }
  it should "sign payment requests" in {
    val factory = CertificateFactory.getInstance("X.509")
    val cacert = factory.generateCertificate(classOf[PaymentProtocolSpec].getResourceAsStream("/cacert.pem")).asInstanceOf[X509Certificate]
    val servercert = factory.generateCertificate(classOf[PaymentProtocolSpec].getResourceAsStream("/servercert.pem")).asInstanceOf[X509Certificate]
    //val cert3 = factory.generateCertificate(classOf[PaymentProtocolSpec].getResourceAsStream("/ca-int2.crt")).asInstanceOf[X509Certificate]
    val keyPair = new PemReader(new InputStreamReader(classOf[PaymentProtocolSpec].getResourceAsStream("/serverkey.pem"))).readPemObject()
    val keyFactory = KeyFactory.getInstance("RSA")
    val key = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyPair.getContent))
    keystore.setCertificateEntry("foo", cacert)
    val details = PaymentDetails.newBuilder()
      .addOutputs(Output.newBuilder().setAmount(100).setScript(ByteString.EMPTY))
      .setMemo("foo")
      .setPaymentUrl("")
      .setTime(Platform.currentTime)

    val request = PaymentRequest.newBuilder()
      .setPaymentDetailsVersion(1)
      .setSerializedPaymentDetails(details.build().toByteString)
      .build

    val request1 = PaymentProtocol.sign(request, Seq(servercert), key)
    val (name, publicKey, trustAnchor) = PaymentProtocol.verifySignature(request1, keystore)
    assert(name === "Foobar")
  }
} 
开发者ID:sidhujag,项目名称:syscoin-lib,代码行数:61,代码来源:PaymentProtocolSpec.scala


示例16: getSSLContext

//设置package包名称以及导入依赖的类
package rere.driver.connection

import java.io.ByteArrayInputStream
import java.security.KeyStore
import java.security.cert.{CertificateFactory, X509Certificate}
import javax.net.ssl.{SSLContext, TrustManagerFactory}

import rere.driver.TLSProtocolVersion

sealed trait SSLContextProvider {
  def getSSLContext: SSLContext
}

class PreparedSSLContextProvider(context: SSLContext) extends SSLContextProvider {
  override def getSSLContext: SSLContext = context
}

class FromCertificateFileProvider(bytes: Array[Byte], protocolVersion: TLSProtocolVersion) extends SSLContextProvider {
  override def getSSLContext: SSLContext = {
    val certificateFactory = CertificateFactory.getInstance("X.509")
    val certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes)).asInstanceOf[X509Certificate]

    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(null)
    keyStore.setCertificateEntry("rootCa", certificate)
    trustManagerFactory.init(keyStore)

    val context = SSLContext.getInstance(protocolVersion.canonicalName)
    context.init(null, trustManagerFactory.getTrustManagers, null)
    context
  }
} 
开发者ID:pbaun,项目名称:rere,代码行数:34,代码来源:SSLContextProvider.scala


示例17: Tools

//设置package包名称以及导入依赖的类
package org.play.test.helpers

import java.io.InputStream
import java.security.cert.X509Certificate

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.StreamConverters
import play.api.mvc._

import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.duration._

object Tools {

  class ReqHeader(
                           override val id: Long = 1L,
                           override val tags: Map[String, String] = Map.empty,
                           override val uri: String = "",
                           override val path: String = "",
                           override val method: String = "GET",
                           override val version: String = "1",
                           override val queryString: Map[String, Seq[String]] = Map.empty,
                           override val headers: Headers = Headers.apply(),
                           override val remoteAddress: String = "",
                           override val secure: Boolean = false,
                           override val clientCertificateChain: Option[Seq[X509Certificate]] = None) extends RequestHeader {
  }

  def convertStreamToString(is: java.io.InputStream) : String = {
    val s = new java.util.Scanner(is).useDelimiter("\\A")
    if (s.hasNext()) s.next() else ""
  }

  def getBody(result: Future[Result], duration: FiniteDuration = 5.seconds): String = {
    implicit val system = ActorSystem("flowtest")
    implicit val mater = ActorMaterializer()

    val stream = Await.result(result, duration).body.dataStream.runWith(StreamConverters.asInputStream(duration))
    convertStreamToString(stream)
  }

  implicit class BodyExtractor(action: Action[AnyContent]) {
    def body: String = getBody(action.apply(null))
  }
} 
开发者ID:haribageski,项目名称:mockserver,代码行数:48,代码来源:Tools.scala


示例18: certificateForCommonName

//设置package包名称以及导入依赖的类
package io.mediachain.signatures
import java.io.File
import java.nio.file.Paths
import java.security.cert.X509Certificate

import cats.data.Xor
import io.mediachain.core.SignatureError
import io.mediachain.core.SignatureError.{CertificateNotFound, CommonNameMismatch, InvalidCertificate}
import io.mediachain.util.Env


  def certificateForCommonName(commonName: String)
  : Xor[SignatureError, X509Certificate] = {
    val filePath = Paths.get(rootDirectoryPath, commonName, CERTIFICATE_FILENAME)
    val certFile = filePath.toFile
    for {
      _ <- if (certFile.exists) Xor.Right({})
           else Xor.Left(CertificateNotFound(commonName))
      cert <- PEMFileUtil.certificateFromFile(certFile.getAbsolutePath)
      commonNameInCert <- CertificateUtil.commonName(cert)
      _ <- if (commonNameInCert == commonName) Xor.Right({})
           else Xor.Left(CommonNameMismatch(commonName, commonNameInCert))
    } yield cert
  }
}


object LocalCertificateStore {
  private val ROOT_DIR_ENV_VAR = "LSPACE_CERTIFICATE_DIR"

  def getInstance(rootDirectoryPath: Option[String] = None): LocalCertificateStore = {
    val path = rootDirectoryPath
      .orElse(Env.getString(ROOT_DIR_ENV_VAR).toOption)
      .getOrElse(throw new IllegalStateException(
        "Can't create LocalCertificateStore without a root directory path\n" +
        "Either pass in Some(directoryPath) or set the " +
        s"$ROOT_DIR_ENV_VAR environment variable."))

    new LocalCertificateStore(path)
  }
} 
开发者ID:mediachain,项目名称:L-SPACE,代码行数:42,代码来源:LocalCertificateStore.scala


示例19: HttpsNoCert

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

import javax.net.ssl._
import java.security.cert.X509Certificate

import scala.io.Source



object HttpsNoCert {

  object IngenuousTrustManager extends X509TrustManager {
    val getAcceptedIssuers = null

    override def checkClientTrusted(cert: Array[X509Certificate], authType: String) = {
      //don't check
    }
    override def checkServerTrusted(cert: Array[X509Certificate], authType: String) = {
      //don't check
    }
  }

  // Verifies all host names by simply returning true.
  object VerifiesAllHostNames extends HostnameVerifier {
    def verify(s: String, sslSession: SSLSession) = true
  }

  def execute(url: String):String = {
    // SSL Context initialization and configuration
    val sslContext = SSLContext.getInstance("SSL")
    sslContext.init(null, Array(IngenuousTrustManager), new java.security.SecureRandom())
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory)
    HttpsURLConnection.setDefaultHostnameVerifier(VerifiesAllHostNames)

    // Actual call
    Source.fromURL(url, "UTF-8").mkString
  }
} 
开发者ID:OoShiunoO,项目名称:IIIapi,代码行数:39,代码来源:HttpsNoCert.scala


示例20: IgnorantTrustManager

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala GZIPOutputStream类代码示例发布时间:2022-05-23
下一篇:
Scala Partitioner类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap