org.apache.commons.codec.binary.Hex Scala Examples
The following examples show how to use org.apache.commons.codec.binary.Hex.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: RSAUtils.scala From Linkis with Apache License 2.0 | 5 votes |
package com.webank.wedatasphere.linkis.common.utils import java.security.{KeyPair, KeyPairGenerator, PrivateKey, PublicKey} import javax.crypto.Cipher import org.apache.commons.codec.binary.Hex import org.apache.commons.net.util.Base64 object RSAUtils { private implicit val keyPair = genKeyPair(1024) def genKeyPair(keyLength: Int): KeyPair = { val keyPair = KeyPairGenerator.getInstance("RSA") keyPair.initialize(keyLength) keyPair.generateKeyPair() } def getDefaultPublicKey(): String = { new String(Base64.encodeBase64(keyPair.getPublic.getEncoded)) } def encrypt(data: Array[Byte], publicKey: PublicKey): Array[Byte] = { val cipher = Cipher.getInstance("RSA") cipher.init(Cipher.ENCRYPT_MODE, publicKey) cipher.doFinal(data) } def encrypt(data: Array[Byte]): Array[Byte] = encrypt(data, keyPair.getPublic) def decrypt(data: String, privateKey: PrivateKey): Array[Byte] = { val dataBytes = Hex.decodeHex(data.toCharArray) decrypt(dataBytes, privateKey) } def decrypt(data: String): Array[Byte] = decrypt(data, keyPair.getPrivate) def decrypt(data: Array[Byte], privateKey: PrivateKey): Array[Byte] = { val cipher = Cipher.getInstance("RSA") cipher.init(Cipher.DECRYPT_MODE, privateKey) cipher.doFinal(data) } def decrypt(data: Array[Byte]): Array[Byte] = decrypt(data, keyPair.getPrivate) }
Example 2
Source File: SecureRandomIdGenerator.scala From tsec with MIT License | 5 votes |
package tsec.common import cats.effect.Sync import org.apache.commons.codec.binary.Hex case class SecureRandomIdGenerator(sizeInBytes: Int = 32) extends ManagedRandom { def generate: SecureRandomId = { val byteArray = new Array[Byte](sizeInBytes) nextBytes(byteArray) new String(Hex.encodeHex(byteArray)).asInstanceOf[SecureRandomId] } def generateF[F[_]](implicit F: Sync[F]): F[SecureRandomId] = F.delay(generate) } //Todo: Possible use case for refined? object SecureRandomId { lazy val Strong: SecureRandomIdGenerator = SecureRandomIdGenerator(32) lazy val Interactive: SecureRandomIdGenerator = SecureRandomIdGenerator(16) def apply(s: String): SecureRandomId = s.asInstanceOf[SecureRandomId] def coerce(s: String): SecureRandomId = s.asInstanceOf[SecureRandomId] }
Example 3
Source File: HasherImpl.scala From Scala-Design-Patterns-Second-Edition with MIT License | 5 votes |
package com.ivan.nikolov.structural.bridge.scala import com.ivan.nikolov.structural.bridge.common.Hasher import org.apache.commons.codec.binary.Hex trait Sha1Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-1", data).digest())) } trait Sha256Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-256", data).digest())) } trait Md5Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("MD5", data).digest())) }
Example 4
Source File: Hasher.scala From Scala-Design-Patterns-Second-Edition with MIT License | 5 votes |
package com.ivan.nikolov.structural.bridge import com.ivan.nikolov.structural.bridge.common.Hasher import org.apache.commons.codec.binary.Hex class Sha1Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-1", data).digest())) } class Sha256Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-256", data).digest())) } class Md5Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("MD5", data).digest())) }
Example 5
Source File: HasherImpl.scala From Scala-Design-Patterns-Second-Edition with MIT License | 5 votes |
package com.ivan.nikolov.structural.bridge.scala import com.ivan.nikolov.structural.bridge.common.Hasher import org.apache.commons.codec.binary.Hex trait Sha1Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-1", data).digest())) } trait Sha256Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-256", data).digest())) } trait Md5Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("MD5", data).digest())) }
Example 6
Source File: Hasher.scala From Scala-Design-Patterns-Second-Edition with MIT License | 5 votes |
package com.ivan.nikolov.structural.bridge import com.ivan.nikolov.structural.bridge.common.Hasher import org.apache.commons.codec.binary.Hex class Sha1Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-1", data).digest())) } class Sha256Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("SHA-256", data).digest())) } class Md5Hasher extends Hasher { override def hash(data: String): String = new String(Hex.encodeHex(getDigest("MD5", data).digest())) }
Example 7
Source File: CalculateXORSummary.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.analytics.main import akka.actor.ActorSystem import akka.stream.ActorMaterializer import cmwell.analytics.data.{IndexWithSourceHash, XORSummary, XORSummaryFactory} import cmwell.analytics.downloader.PartitionedDownloader import cmwell.analytics.util.{DiscoverEsTopology, FindContactPoints} import org.apache.commons.codec.binary.Hex import org.apache.log4j.LogManager import org.rogach.scallop.{ScallopConf, ScallopOption} import scala.concurrent.ExecutionContextExecutor object CalculateXORSummary { def main(args: Array[String]): Unit = { val logger = LogManager.getLogger(CalculateXORSummary.getClass) // Since we expect this to be run on a CM-Well node, the default parallelism is to use half the processors // so as to avoid starving the CM-Well node from processor resources. A higher level of parallelism might // be possible (without interfering with CM-Well) since most of the work will actually be on the ES side. val defaultParallelism = 1 max (Runtime.getRuntime.availableProcessors / 2) implicit val system: ActorSystem = ActorSystem("xor-summary") implicit val executionContext: ExecutionContextExecutor = system.dispatcher implicit val actorMaterializer: ActorMaterializer = ActorMaterializer() try { object Opts extends ScallopConf(args) { val readIndex: ScallopOption[String] = opt[String]("read-index", short = 'i', descr = "The name of the index to read from", required = false) val parallelism: ScallopOption[Int] = opt[Int]("parallelism", short = 'p', descr = "The parallelism level", default = Some(defaultParallelism)) val url: ScallopOption[String] = trailArg[String]("url", descr = "A CM-Well URL", required = true) verify() } val esContactPoint = FindContactPoints.es(Opts.url()) val indexesOrAliasesToRead = Opts.readIndex.toOption.fold(Seq("cm_well_all"))(Seq(_)) val esTopology = DiscoverEsTopology(esContactPoint = esContactPoint, aliases = indexesOrAliasesToRead) val dataWriterFactory = new XORSummaryFactory() PartitionedDownloader.runDownload( esTopology = esTopology, parallelism = Opts.parallelism(), objectExtractor = IndexWithSourceHash, dataWriterFactory = dataWriterFactory.apply, sourceFilter = false) // Summarize the summaries down to the index level. val summaryByIndex: Map[String, XORSummary] = dataWriterFactory.shardSummaries .groupBy { case (shard, _) => shard.indexName } .map { case (indexName, summaryMap) => indexName -> summaryMap.values.reduce(XORSummary.combine) } // TODO: Fix questionable JSON generation val r = "{" + summaryByIndex.map { case (index, summary) => val x = Hex.encodeHexString(summary.summary) s""" { "index": "$index", "summary": "$x" } """ }.mkString("\n") + "}" println(r) } catch { case ex: Throwable => logger.error(ex.getMessage, ex) System.exit(1) } finally { system.terminate() } } }
Example 8
Source File: AuthUtil.scala From shield with MIT License | 5 votes |
package shield.aws import java.nio.charset.StandardCharsets import java.security.MessageDigest import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import org.apache.commons.codec.binary.Hex import org.joda.time.format.DateTimeFormat import org.joda.time.{DateTime, DateTimeZone} import spray.http.HttpHeaders.RawHeader import spray.http.HttpRequest object HexBytesUtil { def hex2bytes(hex: String): Array[Byte] = { hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2, 2).toArray.map(Integer.parseInt(_, 16).toByte) } def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String = { sep match { case None => bytes.map("%02x".format(_)).mkString case _ => bytes.map("%02x".format(_)).mkString(sep.get) } } }
Example 9
Source File: FileHash.scala From PackUpdate with Apache License 2.0 | 5 votes |
package at.chaosfield.packupdate.common import java.io.{File, FileInputStream} import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils class FileHash(data: Array[Byte]) { def this(data: String) = this(Hex.decodeHex(data)) def hex: String = Hex.encodeHexString(data) def binary: Array[Byte] = data def canEqual(other: Any): Boolean = other match { case _: FileHash | _: String | _: Array[Byte] => true case _ => false } override def equals(o: Any): Boolean = this.canEqual(o) && (o match { case other: FileHash => data sameElements other.binary case other: String => data sameElements Hex.decodeHex(other) case other: Array[Byte] => data sameElements other case _ => false }) override def toString: String = hex override def hashCode(): Int = data.hashCode } object FileHash { final val Invalid = new FileHash(new Array[Byte](20)) def forFile(file: File): FileHash = new FileHash(DigestUtils.sha256(new FileInputStream(file))) }
Example 10
Source File: SpringConfigController.scala From izanami with Apache License 2.0 | 5 votes |
package controllers import java.security.MessageDigest import akka.actor.ActorSystem import akka.stream.ActorMaterializer import com.google.common.base.Charsets import controllers.actions.SecuredAuthContext import domains.Key import domains.config.{ConfigContext, ConfigService} import env.IzanamiConfig import org.apache.commons.codec.binary.Hex import libs.logs.IzanamiLogger import play.api.libs.json._ import play.api.mvc._ import libs.http.HttpContext import libs.http.HttpContext class SpringConfigController(izanamiConfig: IzanamiConfig, AuthAction: ActionBuilder[SecuredAuthContext, AnyContent], val cc: ControllerComponents)(implicit system: ActorSystem, R: HttpContext[ConfigContext]) extends AbstractController(cc) { import libs.http._ val digester = MessageDigest.getInstance("SHA-256") def byteToHexString(bytes: Array[Byte]): String = String.valueOf(Hex.encodeHex(bytes)) def raw(rootKey: String, appName: String, profileName: String): Action[Unit] = AuthAction.asyncZio(parse.empty) { ctx => val appConfigKey = Key(s"$rootKey:$appName:$profileName:spring-config") val profileConfigKey = Key(s"$rootKey:spring-profiles:$profileName:spring-config") val globalConfigKey = Key(s"$rootKey:spring-globals:spring-config") val host: String = ctx.request.headers .get(izanamiConfig.headerHost) .orElse(ctx.request.headers.get("Host")) .getOrElse("localhost:9000") val result = for { app <- ConfigService.getById(appConfigKey) profile <- ConfigService.getById(profileConfigKey) global <- ConfigService.getById(globalConfigKey) } yield { (app, profile, global) match { case (None, None, None) => NotFound(Json.obj("error" -> "No config found !")) case _ => { val propertySources = JsArray( Seq( app .map(_.value) .collect { case o: JsObject => o } .map( c => Json.obj( "name" -> s"${ctx.request.protocol}://$host/api/configs/$rootKey:$profileName:$appName:spring-config", "source" -> c ) ), profile .map(_.value) .collect { case o: JsObject => o } .map( c => Json.obj( "name" -> s"${ctx.request.protocol}://$host/api/configs/$rootKey:spring-profiles:$profileName:spring-config", "source" -> c ) ), global .map(_.value) .collect { case o: JsObject => o } .map( c => Json.obj( "name" -> s"${ctx.request.protocol}://$host/api/configs/$rootKey:spring-globals:spring-config", "source" -> c ) ) ).flatten ) val payload = Json.obj( "name" -> s"$appName", "profiles" -> Json.arr(s"://$profileName"), "label" -> JsNull, "state" -> JsNull, "propertySources" -> propertySources ) IzanamiLogger.debug(s"Spring config request for $rootKey, $appName, $profileName: \n $payload") val version: String = byteToHexString(digester.digest(Json.stringify(payload).getBytes(Charsets.UTF_8))) Ok(payload ++ Json.obj("version" -> version)) } } } result.mapError { _ => InternalServerError("") } } }