本文整理汇总了Scala中java.security.cert.X509Certificate类的典型用法代码示例。如果您正苦于以下问题:Scala X509Certificate类的具体用法?Scala X509Certificate怎么用?Scala X509Certificate使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了X509Certificate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
}
示例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)
}
示例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)
}
}
}
示例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)
}
}
示例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)
}
示例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
}
}
示例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)
}
}
示例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)
}
示例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))
}
}
示例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)
}
}
示例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))
}
}
}
示例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)
}
}
示例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()
}
示例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())
}
}
}
示例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")
}
}