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

Scala BigInteger类代码示例

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

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



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

示例1: Prover

//设置package包名称以及导入依赖的类
package scapi.sigma.dlog

import java.math.BigInteger
import java.security.SecureRandom

import akka.actor.{Actor, ActorLogging, ActorRef}
import edu.biu.scapi.interactiveMidProtocols.sigmaProtocol.utility.{SigmaBIMsg, SigmaGroupElementMsg}
import edu.biu.scapi.primitives.dlog.GroupElement
import org.bouncycastle.util.BigIntegers
import scapi.sigma.rework.SigmaProtocolFunctions.{FirstMessage, RandomChallenge, SecondMessage, StartInteraction}


class Prover(commonInput: CommonInput,
             proverInput: ProverInput,
             verifierActor: ActorRef) extends Actor with ActorLogging {

  val dlog = commonInput.dlogGroup
  val w = proverInput.w
  val random = new SecureRandom()

  override def receive = beforeFirstMessage

  private def beforeFirstMessage: Receive = {
    case StartInteraction =>
      val qMinusOne = dlog.getOrder.subtract(BigInteger.ONE)

      val r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random)

      //Compute a = g^r.
      val a: GroupElement = dlog.exponentiate(dlog.getGenerator, r)

      val sigmaProtocolMsg = new SigmaGroupElementMsg(a.generateSendableData)
      verifierActor ! FirstMessage(sigmaProtocolMsg)
      context become beforeSecondMessage(r)
  }

  private def beforeSecondMessage(r: BigInteger): Receive = {
    case RandomChallenge(challenge) =>
      require(challenge.bytes.length * 8 == commonInput.protocolParams.soundness, "wrong challenge length")

      //Compute z = (r+ew) mod q
      val q: BigInteger = dlog.getOrder
      val e: BigInteger = new BigInteger(1, challenge.bytes)
      val ew: BigInteger = e.multiply(w).mod(q)
      val z: BigInteger = r.add(ew).mod(q)
      verifierActor ! SecondMessage(new SigmaBIMsg(z))
      context become finished
  }

  private def finished: Receive = {
    case a: Any => log.warning(s"Got a message after protocol being finished: $a")
  }
} 
开发者ID:kushti,项目名称:scala-scapi,代码行数:54,代码来源:Prover.scala


示例2: PublicKeyBase

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

import javax.crypto.spec.DHParameterSpec
import java.math.BigInteger
import java.security.KeyPairGenerator
import javax.crypto.KeyAgreement
import javax.crypto.interfaces.DHPublicKey
import org.apache.commons.codec.binary.Hex

abstract class PublicKeyBase extends Base {
  protected val p = new java.math.BigInteger("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563", 16)

  private val dhParamSpec = new DHParameterSpec(DH_P_BI, DH_G_BI, DH_L)
  val dh_key_generator = KeyPairGenerator.getInstance("DH")
  dh_key_generator.initialize(dhParamSpec)

  private val keyPair = dh_key_generator.generateKeyPair()

  val keyAgreement = KeyAgreement.getInstance("DH")
  keyAgreement.init(keyPair.getPrivate())

  private val dhPublicKey = keyPair.getPublic.asInstanceOf[DHPublicKey]
  private val dh_y = dhPublicKey.getY()

  println("New: " + LocalPublicKey.parse(dh_y, DH_SIZE_BYTES))
  println("Old: " + Hex.encodeHexString(bigIntegerToBytes(dh_y, DH_SIZE_BYTES)))

  val publicKey = LocalPublicKey(bigIntegerToBytes(dh_y, DH_SIZE_BYTES))

  def decodeString(str: String): Array[Byte] = {
    val chars = str.toCharArray();

    val chars_length = chars.length - chars.length % 2;

    val res = Array.ofDim[Byte](chars_length / 2);

    for (i <- 0.until(chars_length, 2)) {

      val b = new String(chars, i, 2);

      res(i / 2) = Integer.parseInt(b, 16).asInstanceOf[Byte];
    }

    return (res);
  }

  def bigIntegerToBytes(bi: BigInteger, num_bytes: Int): Array[Byte] = {
    var str = bi.toString(16);
    // System.out.println(str.length() + "|" + str);
    while (str.length() < num_bytes * 2) {
      str = "0" + str;
    }
    // System.out.println(num_bytes * 2 + "||" + str);
    return (decodeString(str));
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:57,代码来源:PublicKeyBase.scala


示例3: Base

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

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import java.nio.charset.Charset

abstract class Base {
  protected val DH_P = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A63A36210000000000090563"
  protected val DH_G = "02"
  protected val DH_L = 160

  protected val UTF8 = Charset.forName("UTF8");
  protected val KEYA_IV = "keyA".getBytes(UTF8)
  protected val KEYB_IV = "keyB".getBytes(UTF8)
  protected val REQ1_IV = "req1".getBytes(UTF8)
  protected val REQ2_IV = "req2".getBytes(UTF8)
  protected val REQ3_IV = "req3".getBytes(UTF8)
  protected val VC = Array[Byte](0, 0, 0, 0, 0, 0, 0, 0)

  protected val RC4_STREAM_ALG = "RC4";

  protected val DH_P_BI = new BigInteger(DH_P, 16)
  protected val DH_G_BI = new BigInteger(DH_G, 16)

  protected val DH_SIZE_BYTES = DH_P.length() / 2

  protected val CRYPTO_PLAIN: Byte = Plain.id
  protected val CRYPTO_RC4: Byte = RC4.id

  protected val PADDING_MAX = 512

  private def randomPaddingSize: Int = {
    val random = ThreadLocalRandom.current
    Math.abs(random.nextInt % PADDING_MAX)
  }

  protected def randomPadding(): Array[Byte] = {
    val padding = Array.ofDim[Byte](randomPaddingSize)
    val random = ThreadLocalRandom.current
    random.nextBytes(padding)
    padding
  }
} 
开发者ID:zpooky,项目名称:bittorrent,代码行数:44,代码来源:Base.scala


示例4: SessionUtil

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

import java.math.BigInteger
import java.util.concurrent.ThreadLocalRandom
import javax.xml.bind.DatatypeConverter

object SessionUtil {
  def randomString(length: Int) = {
    // http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
    val random = ThreadLocalRandom.current()
    new BigInteger(length * 5, random).toString(32) // because 2^5 = 32
  }

  
  def randomServerSecret() = randomString(128)

  // Do not change this unless you understand the security issues behind timing attacks.
  // This method intentionally runs in constant time if the two strings have the same length.
  // If it didn't, it would be vulnerable to a timing attack.
  def constantTimeEquals(a: String, b: String) = {
    if (a.length != b.length) {
      false
    }
    else {
      var equal = 0
      for (i <- Array.range(0, a.length)) {
        equal |= a(i) ^ b(i)
      }
      equal == 0
    }
  }

  def toHexString(array: Array[Byte]): String = {
    DatatypeConverter.printHexBinary(array)
  }

  def hexStringToByte(hexString: String): Array[Byte] = {
    DatatypeConverter.parseHexBinary(hexString)
  }
} 
开发者ID:adamw,项目名称:testpr,代码行数:41,代码来源:SessionUtil.scala


示例5: md

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package io

import java.math.BigInteger
import java.net.{ HttpURLConnection, URL, URLConnection }
import java.security.MessageDigest

import mesosphere.marathon.stream._
import org.apache.commons.io.FilenameUtils.getName

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait PathFun {

  private[this] def md = MessageDigest.getInstance("SHA-1")

  def mdHex(in: String): String = {
    val ret = md
    ret.update(in.getBytes("UTF-8"), 0, in.length)
    new BigInteger(1, ret.digest()).toString(16)
  }

  def fileName(url: URL): String = getName(url.getFile)

  def contentPath(url: URL): Future[String] = contentHeader(url).map { header =>
    //filter only strong eTags and make sure, it can be used as path
    val eTag: Option[String] = header.get("ETag")
      .flatMap(_.filterNot(_.startsWith("W/")).headOption)
      .map(_.replaceAll("[^A-z0-9\\-]", ""))
    val contentPart = eTag.getOrElse(IO.mdSum(url.openStream()))
    s"$contentPart/${fileName(url)}"
  }

  def contentHeader(url: URL): Future[Map[String, List[String]]] = Future {
    val connection = url.openConnection() match {
      case http: HttpURLConnection =>
        http.setRequestMethod("HEAD")
        http
      case other: URLConnection => other
    }
    scala.concurrent.blocking(connection.getHeaderFields)
      .map { case (key, list) => (key, list.toList) }(collection.breakOut)
  }

} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:47,代码来源:PathFun.scala


示例6: Cert

//设置package包名称以及导入依赖的类
package run.cosy.crypto

import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.RSAPublicKeySpec

import akka.http.scaladsl.model.Uri
import org.w3.banana.{PointedGraph, RDF, RDFOps, binder}
import org.w3.banana.binder.{PGBinder, RecordBinder, ToPG}

object Cert {
   def binderWithName[Rdf<:RDF](u: Uri)(implicit ops: RDFOps[Rdf]): PGBinder[Rdf, RSAPublicKey] =
      new Cert[Rdf].binderRootName(u.toString())
   
   def binder[Rdf<:RDF](implicit ops: RDFOps[Rdf]): PGBinder[Rdf, RSAPublicKey] =  new Cert[Rdf].binder

}

class Cert[Rdf<:RDF](implicit ops: RDFOps[Rdf]) {
   import org.w3.banana.{CertPrefix, RDF, RDFOps, binder}
   implicit val recordBinder = org.w3.banana.binder.RecordBinder[Rdf](ops)
   val cert = CertPrefix[Rdf]
   import org.w3.banana.binder._
   import recordBinder._

   implicit val rsaClassUri = recordBinder.classUrisFor[RSAPublicKey](cert.RSAPublicKey)
   val factory = KeyFactory.getInstance("RSA")
   val exponent = property[BigInteger](cert.exponent)
   val modulus = property[Array[Byte]](cert.modulus)
   
   val binder: PGBinder[Rdf, RSAPublicKey] =
      pgb[RSAPublicKey](modulus, exponent)(
         (m: Array[Byte], e: BigInteger) => factory.generatePublic(new RSAPublicKeySpec(new BigInteger(m), e)).asInstanceOf[RSAPublicKey],
         (key: RSAPublicKey) => Some((key.getModulus.toByteArray, key.getPublicExponent))
      ).withClasses(rsaClassUri)
   
   def binderRootName(uri: String)  =
      pgbWithConstId[RSAPublicKey](uri)(modulus, exponent)(
         (m: Array[Byte], e: BigInteger) => factory.generatePublic(new RSAPublicKeySpec(new BigInteger(m), e)).asInstanceOf[RSAPublicKey],
         (key: RSAPublicKey) => Some((key.getModulus.toByteArray, key.getPublicExponent))
      ).withClasses(rsaClassUri)
} 
开发者ID:read-write-web,项目名称:solid-client,代码行数:44,代码来源:Cert.scala


示例7: EstonianReferenceNumberFinder

//设置package包名称以及导入依赖的类
package org.pdfextractor.algorithm.finder.et

import java.math.BigInteger
import java.util.Locale

import org.pdfextractor.algorithm.finder.et.EstonianRegexPatterns._
import org.pdfextractor.algorithm.finder.{AbstractFinder, _}
import org.pdfextractor.db.domain.dictionary.PaymentFieldType.REFERENCE_NUMBER
import org.pdfextractor.db.domain.dictionary.SupportedLocales
import org.springframework.stereotype.Service

@Service
class EstonianReferenceNumberFinder extends AbstractFinder(SupportedLocales.ESTONIA, REFERENCE_NUMBER, EstRefNoLineR, EstRefNoR) {

  override def parseValue(raw: String): Any = raw

  override def isValueAllowed(raw: Any): Boolean = {
    try {
      val value = new BigInteger(raw.asInstanceOf[String])
      isCorrectFormat(value) && checkDigitMatches(value,
        calculateCheckDigit(value))
    } catch {
      case _: Throwable => false
    }
  }

  private def calculateCheckDigit(value: BigInteger) = {
    val productsSum = calculate731Sum(digitsToPenultimateInReverse(value))

    findTensMultiple(productsSum) - productsSum
  }

  private def checkDigitMatches(value: BigInteger, checkDigit: Int) = {
    val lastDigit =
      Integer.valueOf("" + value.toString.charAt(value.toString.length - 1))
    lastDigit == checkDigit
  }

  private def isCorrectFormat(value: BigInteger): Boolean = {
    Option(value).isDefined &&
      value.signum > 0 && // must be positive
      value.toString.length >= 2 && // must have 2 - 20 digits
      value.toString.length <= 20
  }

} 
开发者ID:kveskimae,项目名称:pdfalg,代码行数:47,代码来源:EstonianReferenceNumberFinder.scala


示例8: Keys

//设置package包名称以及导入依赖的类
package com.malliina.aws.cognito

import java.math.BigInteger
import java.security.KeyFactory
import java.security.interfaces.RSAPublicKey
import java.security.spec.RSAPublicKeySpec
import java.util.Base64

object Keys {
  val keyFactory = KeyFactory.getInstance("RSA")

  def publicKey(key: JWTKey): RSAPublicKey =
    publicKey(toBigInt(key.n), toBigInt(key.e))

  private def publicKey(modulus: BigInteger, exponent: BigInteger): RSAPublicKey = {
    val keySpec = new RSAPublicKeySpec(modulus, exponent)
    keyFactory.generatePublic(keySpec).asInstanceOf[RSAPublicKey]
  }

  private def toBigInt(enc: String): BigInteger =
    new BigInteger(1, Base64.getUrlDecoder.decode(enc))
} 
开发者ID:malliina,项目名称:cognito-utils,代码行数:23,代码来源:Keys.scala


示例9: DownloadManagerSpec

//设置package包名称以及导入依赖的类
package im.actor.util.http

import java.math.BigInteger
import java.nio.file.Files
import java.security.MessageDigest

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Span, Seconds }
import org.scalatest.{ FlatSpec, Matchers }

class DownloadManagerSpec extends FlatSpec with ScalaFutures with Matchers {
  it should "Download https files" in e1

  override implicit def patienceConfig: PatienceConfig =
    new PatienceConfig(timeout = Span(10, Seconds))

  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()

  val downloadManager = new DownloadManager()

  def e1() = {
    whenReady(downloadManager.download("https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js")) {
      case (path, size) ?

        val fileBytes = Files.readAllBytes(path)
        fileBytes.length shouldEqual size

        val md = MessageDigest.getInstance("MD5")
        val hexDigest = new BigInteger(1, md.digest(fileBytes)) toString (16)

        hexDigest shouldEqual "593e60ad549e46f8ca9a60755336c7df"
    }
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:38,代码来源:DownloadManagerSpec.scala


示例10: Pkcs12ConvertorSpec

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

import java.io.{FileOutputStream, StringReader}
import java.math.BigInteger
import java.time.{Duration, Instant}
import java.util.Date

import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers
import org.bouncycastle.asn1.x500.X500NameBuilder
import org.bouncycastle.asn1.x500.style.BCStyle
import org.bouncycastle.asn1.x509.AlgorithmIdentifier
import org.bouncycastle.cert.X509v3CertificateBuilder
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter
import org.bouncycastle.crypto.util.PrivateKeyFactory
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder
import org.specs2.mutable.Specification

class Pkcs12ConvertorSpec extends Specification {

  "Pkcs12Convertor" should {

    "parsePrivateKey" in {
      val keyPair = RSAKeyPairFactory.generate
      val pem = RSAKeyPairFactory.privateKeyToString(keyPair)
      val reader = new StringReader(pem)

      val pk = Pkcs12Convertor.parsePrivateKey(reader)
      keyPair.getPrivate.getEncoded must_== pk.getEncoded
    }

    "parseCertificate" in {
      val keyPair = RSAKeyPairFactory.generate
      val builder = new X500NameBuilder()
      builder.addRDN(BCStyle.C, "JP")
      builder.addRDN(BCStyle.CN, "Pigumer Group")
      val csr = CertificationSigningRequestFactory.generate(builder.build(), keyPair)

      val now = Instant.now()
      val notBefore = new Date(now.toEpochMilli)
      val notAfter = new Date(now.plus(Duration.ofDays(365)).toEpochMilli)

      val b = new X509v3CertificateBuilder(csr.getSubject, BigInteger.valueOf(1L), notBefore, notAfter, csr.getSubject, csr.getSubjectPublicKeyInfo)

      val sigAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA)
      val digAlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)

      val privateKeyInfo = PrivateKeyFactory.createKey(keyPair.getPrivate.getEncoded)
      val contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyInfo)
      val certificate = new JcaX509CertificateConverter().getCertificate(b.build(contentSigner))

      val os = new FileOutputStream("test.p12")
      try {
        Pkcs12Convertor.write(os, keyPair.getPrivate, "test".toCharArray, certificate)
      } finally {
        os.close
      }

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


示例11: persist

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.daos;

import com.weiglewilczek.slf4s.Logging
import java.math.BigInteger
trait DaoCrud  {
  def persist[T](t: T): T
  def persistAll[T](t: List[T]): List[T]
  def find[T](c: Class[T]): List[T]
  def get[T](c: Class[T], id: Int): T
  def get[T](c: Class[T], id: BigInteger): T
  def find[T](c: Class[T], s: String): List[T]
  def findOne[T](c: Class[T], s: String): T
  def merge[T](t: T): T
  def mergeAll[T](t: List[T]): List[T]
  def delete[T](t: T): Unit
  def deleteAll[T](t: List[T]): Unit
  def remove[T](t: T): Unit
  def removeAll[T](t: List[T]): Unit

} 
开发者ID:writeonly,项目名称:babel,代码行数:21,代码来源:DaoCrud.scala


示例12: DaoJdo

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.daos

//import org.springframework.jdbc.core.JdbcTemplate
import collection.JavaConversions._
import org.springframework.orm.jdo.support.JdoDaoSupport
import pl.writeonly.babel.entities.Entity
import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
import com.weiglewilczek.slf4s.Logging
import org.springframework.orm.jdo.JdoCallback
import javax.jdo.PersistenceManager
import javax.jdo.JDOHelper
import pl.writeonly.babel.entities.Variable
import java.math.BigInteger
import pl.writeonly.babel.entities.DictionaryItem

//@org.springframework.stereotype.Repository
class DaoJdo extends JdoDaoSupport with DaoCrud {

  def persist[T](entity: T): T = getJdoTemplate.makePersistent(entity)

  def persistAll[T](t: List[T]): List[T] = {
    getJdoTemplate.makePersistentAll(t)
    t
  }
  def get[T](clazz: Class[T], id: Int): T = getJdoTemplate.getObjectById(clazz, id)
  def get[T](clazz: Class[T], id: BigInteger): T = getJdoTemplate.getObjectById(clazz, id)
  //  def find[T](c: Class[T]) =  List(getJdoTemplate.find(c).toArray : _*).asInstanceOf[List[T]]
  def find[T](c: Class[T]) = getJdoTemplate.find(c).toArray.map(as[T](_)).toList
  def as[T](entity: Object) =   entity.asInstanceOf[T]
  def find[T](c: Class[T], s: String) = List(getJdoTemplate.find(c, s).toArray: _*).asInstanceOf[List[T]]
  def findOne[T](c: Class[T], s: String): T = getJdoTemplate.find(c, s).iterator.next
  def merge[T](t: T): T = persist(t)
  def mergeAll[T](t: List[T]): List[T] = persistAll(t)
  //
  def delete[T](entity: T) =  getJdoTemplate.deletePersistent(entity)
  def deleteAll[T](entities: List[T]) = getJdoTemplate.deletePersistentAll(ListBuffer(entities: _*))
  def remove[T](t: T) = getJdoTemplate.deletePersistent(t)
  def removeAll[T](t: List[T]) = getJdoTemplate.deletePersistentAll(t)

} 
开发者ID:writeonly,项目名称:babel,代码行数:42,代码来源:DaoJdo.scala


示例13: DictionaryApp

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.apps

import pl.writeonly.babel.mediators.AppLogging
import pl.writeonly.babel.mediators.AppContext
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.DictionaryItem
import pl.writeonly.babel.entities.Variable
import java.math.BigInteger
import pl.writeonly.babel.entities._

object DictionaryApp extends AppLogging {
  implicit def int2big(i: Int) = new BigInteger("" + i)
  AppContext.main(args)
  val dao = AppContext.bean[DaoCrud]("daoImpl")

  //val v0 = new Variable("variable")
  
  
  
  val maked = new Dictionary("dict")
  val clazz = classOf[Dictionary]
  logger info "maked => " + maked
  
  maked.items += new DictionaryItem ("item0") 
  maked.items += new DictionaryItem ("item1") 
  //maked.items += new DictionaryItem ("item2") 
  logger info "maked.items " + maked.items

  val persisted = dao.persist(maked)
  logger info "persisted => " + persisted
  val finded = dao.get(clazz, persisted.id)
  logger info "finded => " + finded

  val deleted = dao.delete(finded)
  logger info "deleted => " + deleted
  val v4 = dao.get(clazz, finded.id)
  logger info "v4 => " + v4
} 
开发者ID:writeonly,项目名称:babel,代码行数:39,代码来源:DictionaryApp.scala


示例14: DictionaryItemApp

//设置package包名称以及导入依赖的类
package pl.writeonly.babel.apps

import pl.writeonly.babel.mediators.AppLogging
import pl.writeonly.babel.mediators.AppContext
import pl.writeonly.babel.daos.DaoCrud
import pl.writeonly.babel.entities.DictionaryItem
import pl.writeonly.babel.entities.Variable
import java.math.BigInteger

object DictionaryItemApp extends AppLogging {
  implicit def long2big(i: Long) = BigInteger.valueOf(i)
  implicit def big2long(big :BigInteger) = big.longValue() 
  AppContext.main(args)
  val dao = AppContext.bean[DaoCrud]("daoImpl")

  //val v0 = new Variable("variable")
  //val v0 = new DictionaryItem("item", 666)
  val v0 = new DictionaryItem("item")
  val clazz = classOf[DictionaryItem]
  logger info "v0 => " + v0

  val v1 = dao.persist(v0)
  logger info "v1 => " + v1
  val v2 = dao.get(clazz, v1.id)
  logger info "v2 => " + v2

  val v3 = dao.delete(v2)
  logger info "v3 => " + v3
  val v4 = dao.get(clazz, v2.id)
  logger info "v4 => " + v4
} 
开发者ID:writeonly,项目名称:babel,代码行数:32,代码来源:DictionaryItemApp.scala


示例15: Hasher

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

import java.math.BigInteger
import java.security.MessageDigest

import homeworkzen.Config


object Hasher {
  def apply(passwordToHash: String): String = {
    val salt = Config.Api.hashSalt
    val md = MessageDigest.getInstance("SHA-512")
    md.update(salt.getBytes("UTF-8"))
    val bytes = md.digest(passwordToHash.getBytes("UTF-8"))
    val digest = new BigInteger(1, bytes)
    f"$digest%064x"
  }
} 
开发者ID:anopse,项目名称:HomeworkZen,代码行数:19,代码来源:Hasher.scala


示例16: LocalStore

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

import java.io.FileOutputStream
import java.math.BigInteger
import java.nio.file.{Files, Paths}
import javax.crypto.SecretKey

import org.ipfs.api.Base58
import org.jboss.netty.util.CharsetUtil


object LocalStore {
  def fileName(secretKey: SecretKey) = "/home/mats/tmp/" + Base58.encode(secretKey.getEncoded)    // TODO: Probably won't work on other machine :-)

  def save(user: User, password: String) = {
    val coreUserData = CoreUserData(user)
    val secretKey = Crypto.reCreateSecretKey(password)
    val json = JSON.toJsonString(coreUserData)
    val encryptedJSONBytes = Crypto.encryptWithSymmetricKey(json.getBytes(CharsetUtil.UTF_8), secretKey)
    val fos = new FileOutputStream(fileName(secretKey))
    fos.write(encryptedJSONBytes)
    fos.close()
  }

  def retrieve(password: String) = {
    val secretKey = Crypto.reCreateSecretKey(password)
    val path = Paths.get(fileName(secretKey))
    val encryptedJsonBytes = Files.readAllBytes(path)
    val jsonBytes = Crypto.decryptWithSymmetricKey(encryptedJsonBytes, secretKey)
    val json = new String(jsonBytes, CharsetUtil.UTF_8)
    val coreUserData = JSON.fromJsonString[CoreUserData](json)
    val privateKey = Crypto.getPrivateKeyFromBigIntegers(coreUserData.privateKeyBigIntegerComponentsAsStrings.toSeq.map(s => new BigInteger(s)))
    val publicKey = Crypto.getPublicKeyFromEncoded(coreUserData.encodedPublicKey)
    val recreatedUser = new User(coreUserData.name, privateKey, publicKey)
    coreUserData.bubbleHandles.foreach(bh => recreatedUser.addBubbleHandle(bh))
    coreUserData.friends.foreach(f => recreatedUser.friends.add(f))

    recreatedUser
  }
} 
开发者ID:matshenricson,项目名称:xyztr,代码行数:41,代码来源:LocalStore.scala


示例17: Base58Spec

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

import java.math.BigInteger
import java.util

import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class Base58Spec extends FlatSpec {
  import fr.acinq.syscoin.Base58._

  "Base58" should "encode byte arrays" in {
    assert(encode("Hello World".getBytes("UTF-8")) === "JxF12TrwUP45BMd")
    assert(encode(BigInteger.valueOf(3471844090L).toByteArray) === "16Ho7Hs")
    assert(encode(new Array[Byte](1)) === "1")
    assert(encode(new Array[Byte](7)) === "1111111")
    assert(encode(new Array[Byte](0)) === "")
  }

  it should "decode strings" in {
    assert(util.Arrays.equals(decode("JxF12TrwUP45BMd"), "Hello World".getBytes("UTF-8")))
    assert(util.Arrays.equals(decode(""), new Array[Byte](0)))
    assert(util.Arrays.equals(decode("1"), new Array[Byte](1)))
    assert(util.Arrays.equals(decode("1111111"), new Array[Byte](7)))
    decode("93VYUMzRG9DdbRP72uQXjaWibbQwygnvaCu9DumcqDjGybD864T")
    intercept[NoSuchElementException] {
      decode("This isn't valid base58")
    }
  }
} 
开发者ID:sidhujag,项目名称:syscoin-lib,代码行数:33,代码来源:Base58Spec.scala


示例18: Dealer

//设置package包名称以及导入依赖的类
package scapi.sigma.damgardjurik.product

import java.math.BigInteger

import akka.actor.{Actor, ActorSystem, Props}
import edu.biu.scapi.midLayer.asymmetricCrypto.encryption.{DJKeyGenParameterSpec, ScDamgardJurikEnc}
import edu.biu.scapi.midLayer.asymmetricCrypto.keys.{DamgardJurikPrivateKey, DamgardJurikPublicKey}
import edu.biu.scapi.midLayer.ciphertext.BigIntegerCiphertext
import edu.biu.scapi.midLayer.plaintext.BigIntegerPlainText
import scapi.sigma.rework.SigmaProtocolFunctions.StartInteraction
import scapi.sigma.damgardjurik.product.Prover.SendFirstMessage


class Dealer extends Actor {

  lazy val protocolParams = ProtocolParams(soundness = 40, lengthParameter = 1)
  lazy val commonInput = CommonInput(pubKey, c1, c2, c3)
  lazy val proverInput = ProverInput(privKey, x1, x2)
  val b1 = new BigInteger("1000")
  val b2 = new BigInteger("2000")
  val b3 = new BigInteger("2000000")
  val x1 = new BigIntegerPlainText(b1)
  val x2 = new BigIntegerPlainText(b2)
  val x3 = new BigIntegerPlainText(b3)
  val djEncScheme = new ScDamgardJurikEnc()
  val keyPair = djEncScheme.generateKey(new DJKeyGenParameterSpec())
  djEncScheme.setKey(keyPair.getPublic, keyPair.getPrivate)
  val pubKey = keyPair.getPublic.asInstanceOf[DamgardJurikPublicKey]
  val privKey = keyPair.getPrivate.asInstanceOf[DamgardJurikPrivateKey]
  val c1 = djEncScheme.encrypt(x1).asInstanceOf[BigIntegerCiphertext]
  val c2 = djEncScheme.encrypt(x2).asInstanceOf[BigIntegerCiphertext]
  val c3 = djEncScheme.encrypt(x3).asInstanceOf[BigIntegerCiphertext]
  val verifier = context.actorOf(Props(classOf[Verifier], protocolParams, commonInput))
  val prover = context.actorOf(Props(classOf[Prover], protocolParams, commonInput, proverInput, verifier))

  override def receive: Receive = {
    case StartInteraction =>
      prover ! SendFirstMessage
  }
}


object Launcher extends App {
  val actorSystem = ActorSystem()
  val dealer = actorSystem.actorOf(Props[Dealer])
  dealer ! StartInteraction
} 
开发者ID:kushti,项目名称:scala-scapi,代码行数:48,代码来源:Dealer.scala


示例19: Dealer

//设置package包名称以及导入依赖的类
package scapi.sigma.dlog

import java.math.BigInteger
import java.security.SecureRandom

import akka.actor.{ActorSystem, Props}
import edu.biu.scapi.primitives.dlog.miracl.MiraclDlogECF2m
import org.bouncycastle.util.BigIntegers
import scapi.sigma.rework.SigmaProtocolFunctions.StartInteraction



object Dealer extends App {
  //adding Miracl to libraries being loaded
  System.setProperty("java.library.path", System.getProperty("java.library.path") + ":/usr/lib/scapi")
  val sysPathsField = classOf[ClassLoader].getDeclaredField("sys_paths")
  sysPathsField.setAccessible(true)
  sysPathsField.set(null, null)
  //println(System.getProperty("java.library.path"))
  System.loadLibrary("MiraclJavaInterface")

  val sys = ActorSystem("SigmaProtocolExample")

  val soundness = 40
  val protocolParams = ProtocolParams(soundness)

  val random = new SecureRandom()

  val dlog = new MiraclDlogECF2m("K-233")
  val qMinusOne = dlog.getOrder.subtract(BigInteger.ONE)
  val w = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random)
  val h = dlog.exponentiate(dlog.getGenerator, w)

  val commonInput = CommonInput(protocolParams, dlog, h)
  val proverInput = ProverInput(w)

  val verifier = sys.actorOf(Props(classOf[Verifier], commonInput))
  val prover = sys.actorOf(Props(classOf[Prover], commonInput, proverInput, verifier))

  prover ! StartInteraction
} 
开发者ID:kushti,项目名称:scala-scapi,代码行数:42,代码来源:Dealer.scala


示例20: NkPrivateRsaCrtKey

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

import java.security.interfaces.RSAPrivateCrtKey
import java.security.spec.RSAPrivateCrtKeySpec
import java.security.KeyFactory
import java.math.BigInteger
import NetHsmProtocol._

case class NkPrivateRsaCrtKey(
  modulus: Seq[Byte],
  publicExponent: Seq[Byte],
  privateExponent: Seq[Byte],
  primeP: Seq[Byte],
  primeQ: Seq[Byte],
  primeExponentP: Seq[Byte],
  primeExponentQ: Seq[Byte],
  crtCoefficient: Seq[Byte]) {
  
  def javaPrivateKey: RSAPrivateCrtKey = {
  	val privateKeySpec: RSAPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
  	    new BigInteger(modulus.toArray), 
  	    new BigInteger(publicExponent.toArray), 
  	    new BigInteger(privateExponent.toArray),
  	    new BigInteger(primeP.toArray),
  	    new BigInteger(primeQ.toArray),
  	    new BigInteger(primeExponentP.toArray),
  	    new BigInteger(primeExponentQ.toArray),
  	    new BigInteger(crtCoefficient.toArray))
    val kf = KeyFactory.getInstance("RSA")
    kf.generatePrivate(privateKeySpec).asInstanceOf[RSAPrivateCrtKey]
  }
  
  def publicKey: NkPublicRsaKey = {
    NkPublicRsaKey(modulus, publicExponent)
  }

  def privateKey: NkPrivateRsaKey = {
    NkPrivateRsaKey(primeP, primeQ, publicExponent)
  }
}

object NkPrivateRsaCrtKey {
  def apply(priv: RSAPrivateCrtKey) = {
    new NkPrivateRsaCrtKey(
        priv.getModulus.toByteArray,
        priv.getPublicExponent.toByteArray,
        priv.getPrivateExponent.toByteArray,
        priv.getPrimeP.toByteArray,
        priv.getPrimeQ.toByteArray,
        priv.getPrimeExponentP.toByteArray,
        priv.getPrimeExponentQ.toByteArray,
        priv.getCrtCoefficient.toByteArray
     )
  }

} 
开发者ID:vinaebizs,项目名称:nitrokey-nethsm,代码行数:57,代码来源:NkPrivateRsaCrtKey.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ObjectInputStream类代码示例发布时间:2022-05-23
下一篇:
Scala ByteOrder类代码示例发布时间: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