From 021940c2c308bf501fee6f35684d4db29b0fbc9c Mon Sep 17 00:00:00 2001 From: Colt Frederickson Date: Tue, 24 Nov 2026 11:38:12 -0700 Subject: [PATCH] Moved off scalastyle, updated to scalafix and scalafmt --- .github/workflows/ci.yaml | 11 +- .scalafix.conf | 60 ++++++ .scalafmt.conf | 60 ++++++ README.md | 2 +- benchmark/src/main/scala/ApiBenchmark.scala | 13 +- .../src/main/scala/BenchmarkeHelper.scala | 8 +- benchmark/src/main/scala/Ed25519.scala | 33 +-- .../src/main/scala/FP2ElemBenchmark.scala | 8 +- .../main/scala/GenerateFp12Benchmark.scala | 15 +- .../scala/HomogeneousPointBenchmark.scala | 13 +- .../main/scala/InternalEncryptBenchmark.scala | 14 +- build.sbt | 152 ++++++------- project/build.properties | 2 +- project/plugins.sbt | 23 +- scalastyle-config.xml | 113 ---------- .../scala/com/ironcorelabs/recrypt/Api.scala | 12 +- .../com/ironcorelabs/recrypt/ApiError.scala | 1 - .../com/ironcorelabs/recrypt/CoreApi.scala | 88 ++++---- .../ironcorelabs/recrypt/EncryptedValue.scala | 14 +- .../ironcorelabs/recrypt/HashedValue.scala | 13 +- .../com/ironcorelabs/recrypt/PublicKey.scala | 13 +- .../recrypt/SchnorrSignature.scala | 2 +- .../com/ironcorelabs/recrypt/Sha256.scala | 7 +- .../ironcorelabs/recrypt/TransformKey.scala | 16 +- .../recrypt/internal/BytesDecoder.scala | 1 - .../recrypt/internal/CurvePoints.scala | 5 +- .../recrypt/internal/Ed25519Signing.scala | 2 + .../recrypt/internal/EncryptError.scala | 1 + .../recrypt/internal/EncryptedValue.scala | 5 +- .../recrypt/internal/ExtensionField.scala | 3 +- .../recrypt/internal/FP12Elem.scala | 49 +++-- .../recrypt/internal/FP2Elem.scala | 32 +-- .../recrypt/internal/FP6Elem.scala | 17 +- .../ironcorelabs/recrypt/internal/Fp.scala | 39 ++-- .../ironcorelabs/recrypt/internal/Fp480.scala | 151 +++++++++---- .../recrypt/internal/Hashable.scala | 30 ++- .../recrypt/internal/InternalApi.scala | 54 ++--- .../ironcorelabs/recrypt/internal/Key.scala | 25 +-- .../recrypt/internal/Pairing.scala | 144 +++++++------ .../recrypt/internal/PairingConfig.scala | 4 +- .../recrypt/internal/SchnorrSignature.scala | 38 ++-- .../recrypt/internal/SignedValue.scala | 8 +- .../recrypt/internal/SigningKey.scala | 5 +- .../recrypt/internal/package.scala | 10 +- .../internal/point/HomogeneousPoint.scala | 53 +++-- .../com/ironcorelabs/recrypt/package.scala | 2 +- .../recrypt/syntax/hashable.scala | 2 +- .../com/ironcorelabs/recrypt/ApiTest.scala | 125 ++++++----- .../com/ironcorelabs/recrypt/TestBase.scala | 14 +- .../recrypt/internal/Arbitraries.scala | 38 ++-- .../recrypt/internal/EncryptedValueTest.scala | 10 +- .../recrypt/internal/FP12ElemTest.scala | 42 ++-- .../recrypt/internal/FP2ElemTest.scala | 35 ++- .../recrypt/internal/FieldLawTests.scala | 16 +- .../recrypt/internal/FpTest.scala | 20 +- .../recrypt/internal/HashableTest.scala | 2 +- .../recrypt/internal/InternalApiTest.scala | 200 +++++++++++------- .../recrypt/internal/PublicKeyGenTest.scala | 18 +- .../internal/SchnorrSignatureTest.scala | 18 +- .../internal/point/HomogeneousPointTest.scala | 77 +++++-- 60 files changed, 1109 insertions(+), 879 deletions(-) create mode 100644 .scalafix.conf create mode 100644 .scalafmt.conf delete mode 100644 scalastyle-config.xml diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c041ea4..78f105e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -10,13 +10,18 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Restore caches - uses: coursier/cache-action@v8 + uses: coursier/cache-action@v9 - name: Setup Scala uses: coursier/setup-action@v3 with: jvm: 21 apps: sbt - name: Run tests - run: sbt +compile +test scalastyle + # sbt 2 wants one argument with `;` between commands, not a bare list. benchmark gets its own + # tasks because the root can't aggregate it (see build.sbt). + run: > + sbt "+compile; +test; +benchmark/test; +benchmark/Jmh/compile; + scalafmtCheckAll; benchmark/scalafmtCheckAll; scalafmtSbtCheck; + scalafixAll --check; benchmark/scalafixAll --check" diff --git a/.scalafix.conf b/.scalafix.conf new file mode 100644 index 0000000..2b07d2b --- /dev/null +++ b/.scalafix.conf @@ -0,0 +1,60 @@ +// Replaces the code-smell checks scalastyle used to enforce. Formatting, line length and whitespace are +// scalafmt's (.scalafmt.conf). These have no scalafix equivalent and are no longer checked: naming, +// method and file length, parameter count, cyclomatic complexity, equals/hashCode pairing, covariant +// equals, boolean simplification, and declaring a clone() method. +rules = [ + DisableSyntax + LeakingImplicitClassVal + NoAutoTupling + NoValInForComprehension + ProcedureSyntax + RedundantSyntax + OrganizeImports +] + +DisableSyntax { + noNulls = true + noReturns = true + noFinalize = true + noTabs = true + + regex = [ + { + id = "noPrintln" + pattern = "(? val sig = Ed25519.sign( - //To be safe, just pad out the bytes we get from recrypt. + // To be safe, just pad out the bytes we get from recrypt. Ed25519.PrivateKey.fromPaddedBytes(privateRecryptKey.bytes), message ) recrypt.Signature(sig.bytes) }, - { (publicRecryptKey, message, signature) => + (publicRecryptKey, message, signature) => Ed25519.verify( - //To be safe, just pad out the bytes we get from recrypt. + // To be safe, just pad out the bytes we get from recrypt. Ed25519.PublicKey.fromPaddedBytes(publicRecryptKey.bytes), message, Ed25519.Signature.fromPaddedBytes(signature.bytes) ) - } ) val api = new recrypt.Api(randomBytesIO, Ed25519Instance) diff --git a/benchmark/src/main/scala/BenchmarkeHelper.scala b/benchmark/src/main/scala/BenchmarkeHelper.scala index 2a2a47c..0d33d31 100644 --- a/benchmark/src/main/scala/BenchmarkeHelper.scala +++ b/benchmark/src/main/scala/BenchmarkeHelper.scala @@ -1,14 +1,14 @@ package bench import cats.effect.IO -import scodec.bits.ByteVector -import com.ironcorelabs.recrypt.internal.{ Fp, FP12Elem } import cats.implicits._ -import Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.{FP12Elem, Fp} +import scodec.bits.ByteVector trait BenchmarkHelper { val randomBytesIO: IO[ByteVector] = { - //Start with a known value, we'll just add one to it each time + // Start with a known value, we'll just add one to it each time var i = 100L val hashFunc = java.security.MessageDigest.getInstance("SHA-256").digest(_: Array[Byte]) IO { diff --git a/benchmark/src/main/scala/Ed25519.scala b/benchmark/src/main/scala/Ed25519.scala index 383eabb..db67456 100644 --- a/benchmark/src/main/scala/Ed25519.scala +++ b/benchmark/src/main/scala/Ed25519.scala @@ -3,21 +3,22 @@ */ package bench -import org.bouncycastle.crypto.params.{ Ed25519PrivateKeyParameters, Ed25519PublicKeyParameters } +import org.bouncycastle.crypto.params.{Ed25519PrivateKeyParameters, Ed25519PublicKeyParameters} import org.bouncycastle.crypto.signers.Ed25519Signer import scodec.bits.ByteVector /** * Functions and types for working with the ed25519 signature. */ -object Ed25519 { //scalastyle:ignore +object Ed25519 { + /** * An Ed25519 Public Key, which always has the correct length, can be used in `verify` */ sealed abstract case class PublicKey(bytes: ByteVector) { override def toString: String = s"Ed25519.PublicKey as Base64: '${bytes.toBase64}'" } - final object PublicKey { + object PublicKey { final val Length = 32 final val LengthLong = Length.toLong private[Ed25519] def create(bytes: ByteVector): PublicKey = new PublicKey(bytes) {} @@ -34,9 +35,11 @@ object Ed25519 { //scalastyle:ignore * because of the interaction with recrypt and lack of sizing guarantees (a la refined) it's needed. */ def fromPaddedBytes(bytes: ByteVector): PublicKey = - create(bytes - .take(Length) - .padLeft(Length)) + create( + bytes + .take(Length) + .padLeft(Length) + ) } /** @@ -51,8 +54,8 @@ object Ed25519 { //scalastyle:ignore * `generateKeyPair` to obtain a well-formed key. */ sealed abstract case class PrivateKey(bytes: ByteVector) { - //A protection against logging Private keys. - override def toString: String = s"Ed25519.PrivateKey()" + // A protection against logging Private keys. + override def toString: String = "Ed25519.PrivateKey()" /** The 32-byte Ed25519 seed (first half of the NaCl layout). */ def seed: ByteVector = bytes.take(PrivateKey.SeedLength.toLong) @@ -60,9 +63,11 @@ object Ed25519 { //scalastyle:ignore /** The 32-byte public key embedded in this private key (second half of the NaCl layout). */ def embeddedPublicKey: ByteVector = bytes.drop(PrivateKey.SeedLength.toLong) } - final object PrivateKey { + object PrivateKey { + /** Length of the Ed25519 seed in bytes. */ final val SeedLength = 32 + /** Total length of a NaCl-style Ed25519 private key: seed (32) || public key (32). */ final val Length = SeedLength + PublicKey.Length final val LengthLong = Length.toLong @@ -86,7 +91,7 @@ object Ed25519 { //scalastyle:ignore sealed abstract case class Signature(bytes: ByteVector) { override def toString: String = s"Signature in Base64: '${bytes.toBase64}'" } - final object Signature { + object Signature { val Length = 64 val LengthLong = Length.toLong private[Ed25519] def create(bytes: ByteVector): Signature = new Signature(bytes) {} @@ -103,9 +108,11 @@ object Ed25519 { //scalastyle:ignore * because of the interaction with recrypt and lack of sizing guarantees (a la refined) it's needed. */ def fromPaddedBytes(bytes: ByteVector): Signature = - create(bytes - .take(LengthLong) - .padLeft(LengthLong)) + create( + bytes + .take(LengthLong) + .padLeft(LengthLong) + ) } def verify(key: PublicKey, message: ByteVector, signature: Signature): Boolean = { diff --git a/benchmark/src/main/scala/FP2ElemBenchmark.scala b/benchmark/src/main/scala/FP2ElemBenchmark.scala index 593f350..d7887d9 100644 --- a/benchmark/src/main/scala/FP2ElemBenchmark.scala +++ b/benchmark/src/main/scala/FP2ElemBenchmark.scala @@ -1,10 +1,9 @@ package bench -import java.util.concurrent.TimeUnit +import com.ironcorelabs.recrypt.internal.{FP2Elem, Fp} import org.openjdk.jmh.annotations._ -import com.ironcorelabs.recrypt.internal.Fp -import com.ironcorelabs.recrypt.internal.FP2Elem +import java.util.concurrent.TimeUnit @State(Scope.Benchmark) @OutputTimeUnit(TimeUnit.MILLISECONDS) @@ -21,9 +20,8 @@ class FP2ElemBenchmark extends BenchmarkHelper { var elements: Vector[FP2Elem[Fp]] = Vector.empty @Setup - def setup(): Unit = { + def setup(): Unit = elements = Vector.fill(size)(point) - } @Benchmark def addingFP2 = elements.foldLeft(point)((acc, p) => acc + p) diff --git a/benchmark/src/main/scala/GenerateFp12Benchmark.scala b/benchmark/src/main/scala/GenerateFp12Benchmark.scala index 824599d..259b3c4 100644 --- a/benchmark/src/main/scala/GenerateFp12Benchmark.scala +++ b/benchmark/src/main/scala/GenerateFp12Benchmark.scala @@ -1,12 +1,12 @@ package bench -import java.util.concurrent.TimeUnit -import org.openjdk.jmh.annotations._ - -import com.ironcorelabs.recrypt.internal._ +import cats.effect.unsafe.implicits.global import cats.instances.list._ import cats.syntax.traverse._ -import cats.effect.unsafe.implicits.global +import com.ironcorelabs.recrypt.internal._ +import org.openjdk.jmh.annotations._ + +import java.util.concurrent.TimeUnit @State(Scope.Benchmark) @OutputTimeUnit(TimeUnit.SECONDS) @@ -19,13 +19,12 @@ class GenerateFp12ElemBenchmark extends BenchmarkHelper { var fp12s: List[FP12Elem[Fp]] = List.empty private[this] val fp12Elem = pairing.pair(Fp.curvePoints.generator, Fp.curvePoints.g1) - //Old, inferior way of doing fp12 generation. Here just for comparison with FinalExp. + // Old, inferior way of doing fp12 generation. Here just for comparison with FinalExp. def generateFp12(fp: Fp): FP12Elem[Fp] = fp12Elem ^ fp @Setup - def setup(): Unit = { + def setup(): Unit = fp12s = List.fill(size)(randomFp12IO).sequence.unsafeRunSync() - } @Benchmark def generateUsingFinalExp() = fp12s.foreach(pairing.finalExponentiation(_)) diff --git a/benchmark/src/main/scala/HomogeneousPointBenchmark.scala b/benchmark/src/main/scala/HomogeneousPointBenchmark.scala index 735cce5..4f9ce37 100644 --- a/benchmark/src/main/scala/HomogeneousPointBenchmark.scala +++ b/benchmark/src/main/scala/HomogeneousPointBenchmark.scala @@ -1,12 +1,12 @@ package bench -import java.util.concurrent.TimeUnit -import org.openjdk.jmh.annotations._ import cats.effect.unsafe.implicits.global - -import com.ironcorelabs.recrypt.internal._ -import point.HomogeneousPoint import cats.implicits._ +import com.ironcorelabs.recrypt.internal._ +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import org.openjdk.jmh.annotations._ + +import java.util.concurrent.TimeUnit @State(Scope.Benchmark) @OutputTimeUnit(TimeUnit.MILLISECONDS) @@ -19,9 +19,8 @@ class HomogeneousPointBenchmark extends BenchmarkHelper { var points: Vector[HomogeneousPoint[FP2Elem[Fp]]] = Vector.empty @Setup - def setup(): Unit = { + def setup(): Unit = points = Vector.fill(size)(randomFp.map(point.times)).sequence.unsafeRunSync() - } @Benchmark def add() = points.foldLeft(point)((acc, p) => acc.add(p)) diff --git a/benchmark/src/main/scala/InternalEncryptBenchmark.scala b/benchmark/src/main/scala/InternalEncryptBenchmark.scala index 6ecc26c..dacff23 100644 --- a/benchmark/src/main/scala/InternalEncryptBenchmark.scala +++ b/benchmark/src/main/scala/InternalEncryptBenchmark.scala @@ -1,11 +1,11 @@ package bench -import java.util.concurrent.TimeUnit -import org.openjdk.jmh.annotations._ - +import cats.effect.unsafe.implicits.global import com.ironcorelabs.recrypt.internal._ +import org.openjdk.jmh.annotations._ import scodec.bits.ByteVector -import cats.effect.unsafe.implicits.global + +import java.util.concurrent.TimeUnit @State(Scope.Benchmark) @OutputTimeUnit(TimeUnit.SECONDS) @@ -13,7 +13,7 @@ class InternalEncryptBenchmark extends BenchmarkHelper { import Fp.implicits._ private val keyGen = Fp.curvePoints.publicKeyGen val encryptInstance = new InternalApi( - Sha256Hash { bytes: ByteVector => + Sha256Hash { (bytes: ByteVector) => ByteVector.view(java.security.MessageDigest.getInstance("SHA-256").digest(bytes.toArray)) }, Ed25519Signing((_, _) => Signature.empty, (_, _, _) => true), @@ -39,8 +39,8 @@ class InternalEncryptBenchmark extends BenchmarkHelper { publicSigningKey, privateSigningKey ) - private val reencryptedValue = encryptInstance.reencrypt(reencryptionKey, encryptedData, - raRePrivateKey, raReK, publicSigningKey, privateSigningKey).toOption.get + private val reencryptedValue = + encryptInstance.reencrypt(reencryptionKey, encryptedData, raRePrivateKey, raReK, publicSigningKey, privateSigningKey).toOption.get @Benchmark def generatePublicKey = keyGen(privateKey) diff --git a/build.sbt b/build.sbt index fe20a01..3ea98aa 100644 --- a/build.sbt +++ b/build.sbt @@ -1,49 +1,61 @@ -import scalariform.formatter.preferences._ import org.typelevel.scalacoptions.ScalacOptions -import xerial.sbt.Sonatype.sonatypeCentralHost import ReleaseTransformations._ +lazy val scala213 = "2.13.18" + +// The LTS line rather than the latest 3.x. +lazy val scala3 = "3.3.9" + +// publish := {} doesn't cover sbt-pgp's publishSigned, which is what the release actually uses. lazy val noPublish = Seq( + publish / skip := true, publish := {}, publishLocal := {}, - publishArtifact := false) + PgpKeys.publishSigned := {}, + publishArtifact := false +) + +lazy val coreDependencies = Seq( + "org.typelevel" %% "spire" % "0.18.0", + "org.scodec" %% "scodec-bits" % "1.2.5", + "org.typelevel" %% "cats-effect" % "3.7.1" +) + +lazy val testDependencies = Seq( + "org.scalatest" %% "scalatest" % "3.2.20", + "org.scalacheck" %% "scalacheck" % "1.20.0", + "org.typelevel" %% "spire-laws" % "0.18.0", + "org.typelevel" %% "discipline-scalatest" % "2.3.0" +).map(_ % Test) lazy val recryptSettings = Seq( organization := "com.ironcorelabs", - licenses += ("AGPL-3.0", new URL("https://www.gnu.org/licenses/agpl-3.0.txt")), - scalaVersion := "2.13.18", - crossScalaVersions := Seq(scalaVersion.value, "2.12.21"), - headerLicense := Some(HeaderLicense.Custom( - """|Copyright (C) 2017-present IronCore Labs - | - |This program is free software: you can redistribute it and/or modify - |it under the terms of the GNU Affero General Public License as - |published by the Free Software Foundation, either version 3 of the - |License, or (at your option) any later version. - | - |This program is distributed in the hope that it will be useful, - |but WITHOUT ANY WARRANTY; without even the implied warranty of - |MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - |GNU Affero General Public License for more details. - | - |You should have received a copy of the GNU Affero General Public License - |along with this program. If not, see .""".stripMargin - )), - scalariformPreferences := scalariformPreferences.value - .setPreference(DanglingCloseParenthesis, Preserve), - - // Test - libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "3.2.20" % "test", - "org.scalacheck" %% "scalacheck" % "1.20.0" % "test", - "org.typelevel" %% "spire-laws" % "0.17.0" % "test", - "org.typelevel" %% "discipline-scalatest" % "2.3.0" %"test", - ) ++ Seq( // Core dependencies. - "org.typelevel" %% "spire" % "0.17.0", - "org.scodec" %% "scodec-bits" % "1.2.5", - "org.typelevel" %% "cats-effect" % "3.7.1", + licenses += ("AGPL-3.0", uri("https://www.gnu.org/licenses/agpl-3.0.txt")), + scalaVersion := scala213, + crossScalaVersions := Seq(scala213, scala3), + semanticdbEnabled := true, + // Scala 3 emits SemanticDB itself; only Scala 2 needs the plugin pinned to scalafix's build. + semanticdbVersion := (if (scalaBinaryVersion.value == "3") semanticdbVersion.value else scalafixSemanticdb.revision), + headerLicense := Some( + HeaderLicense.Custom( + """|Copyright (C) 2017-present IronCore Labs + | + |This program is free software: you can redistribute it and/or modify + |it under the terms of the GNU Affero General Public License as + |published by the Free Software Foundation, either version 3 of the + |License, or (at your option) any later version. + | + |This program is distributed in the hope that it will be useful, + |but WITHOUT ANY WARRANTY; without even the implied warranty of + |MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + |GNU Affero General Public License for more details. + | + |You should have received a copy of the GNU Affero General Public License + |along with this program. If not, see .""".stripMargin + ) ), - //Release configuration + libraryDependencies ++= coreDependencies ++ testDependencies, + // Release configuration releasePublishArtifactsAction := PgpKeys.publishSigned.value, releaseCrossBuild := true, releaseProcess := Seq[ReleaseStep]( @@ -55,63 +67,53 @@ lazy val recryptSettings = Seq( commitReleaseVersion, tagRelease, releaseStepCommandAndRemaining("+publishSigned"), - releaseStepCommand("sonatypeBundleRelease"), + releaseStepCommand("sonaRelease"), setNextVersion, commitNextVersion, pushChanges ), - isSnapshot := version.value endsWith "SNAPSHOT", - homepage := Some(url("http://github.com/ironcorelabs/recrypt")), - sonatypeCredentialHost := sonatypeCentralHost, - publishTo := sonatypePublishToBundle.value, + isSnapshot := version.value.endsWith("SNAPSHOT"), + homepage := Some(uri("http://github.com/ironcorelabs/recrypt")), + // Snapshots go straight to the Central snapshot repo; releases stage locally so the whole cross-built + // bundle uploads as one unit from the sonaRelease step above. + publishTo := { + if (isSnapshot.value) Some("central-snapshots".at("https://central.sonatype.com/repository/maven-snapshots/")) + else localStaging.value + }, publishMavenStyle := true, Test / publishArtifact := false, pomIncludeRepository := { _ => false }, - scmInfo := Some(ScmInfo(url("https://github.com/ironcorelabs/recrypt"), "git@github.com:ironcorelabs/recrypt.git")), - pomExtra := ( - - { - Seq( - ("coltfred", "Colt Frederickson") - ).map { - case (id, name) => - - {id} - {name} - http://github.com/{id} - - } - } - - ), + scmInfo := Some(ScmInfo(uri("https://github.com/ironcorelabs/recrypt"), "git@github.com:ironcorelabs/recrypt.git")), + developers := List( + Developer("coltfred", "Colt Frederickson", "coltfred+github@gmail.com", uri("http://github.com/coltfred")) + ), coverageMinimumStmtTotal := 80, coverageFailOnMinimum := true, - //Workaround for issue: https://github.com/scalastyle/scalastyle-sbt-plugin/issues/47 - (Compile / scalastyleSources) ++= (Compile / unmanagedSourceDirectories).value, - Test / testOptions += Tests.Argument(TestFrameworks.ScalaTest, "-oDF"), + Test / testOptions += Tests.Argument(TestFrameworks.ScalaTest, "-oD"), Test / tpolecatExcludeOptions += ScalacOptions.warnNonUnitStatement, - libraryDependencies ++= Seq( - "com.ironcorelabs" %% "cats-scalatest" % "3.1.1" % "test" - ), - scalacOptions ++= Seq( - "-Xcheckinit" // Wrap field accessors to throw an exception on uninitialized access. - )) - + // Throw on uninitialized field access. Scala 3 checks it at compile time, and renamed the flag + // -Wsafe-init in 3.5, so bumping scala3 off 3.3 means renaming this. + scalacOptions += (if (scalaBinaryVersion.value == "3") "-Ysafe-init" else "-Xcheckinit") +) +// Can't .aggregate(benchmark): it dependsOn recrypt, so sbt sees a cycle and drops the aggregation +// without a word, and root compile/test skips it. CI runs it explicitly instead. lazy val recrypt = project .in(file(".")) .settings(moduleName := "recrypt-core") .settings(recryptSettings) - //Benchmark target for running perf tests. -lazy val benchmark = project.in(file("benchmark")) +lazy val benchmark = project + .in(file("benchmark")) .dependsOn(recrypt) .settings(name := "recrypt-benchmark") - .settings(recryptSettings: _*) + .settings(recryptSettings*) .settings(coverageEnabled := false) - .settings(noPublish: _*) - .settings(libraryDependencies ++= Seq( - "org.bouncycastle" % "bcprov-jdk18on" % "1.84" - )) + .settings(noPublish*) + .settings( + libraryDependencies ++= Seq( + "org.bouncycastle" % "bcprov-jdk18on" % "1.87" + ) + ) .enablePlugins(JmhPlugin) diff --git a/project/build.properties b/project/build.properties index 3686073..e43c8e7 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.13.1 +sbt.version=2.1.1 diff --git a/project/plugins.sbt b/project/plugins.sbt index a5e7b16..a3f56c2 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,15 +1,8 @@ -addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0") -addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.8.3") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.4.4") -addSbtPlugin("com.github.sbt" % "sbt-release" % "1.6.0") -addSbtPlugin("com.github.sbt" % "sbt-jmh" % "0.4.9") -addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.4.0") -addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") -addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.12.2") -addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.7") - -// workaround for conflict between sbt-scoverage and scalastyle-sbt-plugin -// https://github.com/scala/bug/issues/12632 -ThisBuild / libraryDependencySchemes ++= Seq( - "org.scala-lang.modules" %% "scala-xml" % VersionScheme.Always -) +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.6.2") +addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.14.10") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.4.4") +addSbtPlugin("com.github.sbt" % "sbt-release" % "1.6.0") +addSbtPlugin("com.github.sbt" % "sbt-jmh" % "0.4.9") +addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.4.0") +addSbtPlugin("com.github.sbt" % "sbt-header" % "5.11.0") +addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.7") diff --git a/scalastyle-config.xml b/scalastyle-config.xml deleted file mode 100644 index 647d35a..0000000 --- a/scalastyle-config.xml +++ /dev/null @@ -1,113 +0,0 @@ - - Scalastyle standard configuration - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/main/scala/com/ironcorelabs/recrypt/Api.scala b/src/main/scala/com/ironcorelabs/recrypt/Api.scala index 7ec62ea..efc7dd4 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/Api.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/Api.scala @@ -19,12 +19,14 @@ package com.ironcorelabs.recrypt import cats.effect.IO import scodec.bits.ByteVector + /** * An instance of the recrypt Api. * @param randomByteVector: An IO that should return a new cryptographically random ByteVector that is at least 32 bytes long on each invocation. */ -class Api(randomByteVector: IO[ByteVector], signing: Ed25519Signing) extends CoreApi( - randomByteVector, - Sha256, - signing -) +class Api(randomByteVector: IO[ByteVector], signing: Ed25519Signing) + extends CoreApi( + randomByteVector, + Sha256, + signing + ) diff --git a/src/main/scala/com/ironcorelabs/recrypt/ApiError.scala b/src/main/scala/com/ironcorelabs/recrypt/ApiError.scala index 25dfac6..a38ae3d 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/ApiError.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/ApiError.scala @@ -22,4 +22,3 @@ sealed abstract class ApiError case object InvalidPublicKey extends ApiError final case class InvalidTransformKey(message: String) extends ApiError final case class InvalidHashedValue(message: String) extends ApiError - diff --git a/src/main/scala/com/ironcorelabs/recrypt/CoreApi.scala b/src/main/scala/com/ironcorelabs/recrypt/CoreApi.scala index a6a3a8a..1f31600 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/CoreApi.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/CoreApi.scala @@ -18,13 +18,13 @@ package com.ironcorelabs.recrypt import cats.effect.IO -import scodec.bits.ByteVector -import cats.syntax.either._ -import cats.syntax.traverse._ import cats.instances.either._ import cats.instances.list._ +import cats.syntax.either._ +import cats.syntax.traverse._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ import com.ironcorelabs.recrypt.syntax.hashable._ -import internal.Fp.implicits._ +import scodec.bits.ByteVector /** * A version of the API that does not have scala specific features in it. @@ -56,22 +56,25 @@ class CoreApi( * Generate a key pair using the randomByteVector to create private keys. */ def generateKeyPair: IO[(PrivateKey, PublicKey)] = - privateKeys.map(priv => priv -> publicKeyTransform(publicKeyGen(privateKeyTransform(priv))) - .getOrElse(throw new Exception("Public key is always defined for valid private key."))) + privateKeys.map(priv => + priv -> publicKeyTransform(publicKeyGen(privateKeyTransform(priv))) + .getOrElse(throw new Exception("Public key is always defined for valid private key.")) + ) /** * Compute the public key for the private key, if the privateKey represents an invalid value, raise an error in the IO. */ - def computePublicKey(privateKey: PrivateKey): IO[PublicKey] = IO(publicKeyTransform(publicKeyGen(privateKeyTransform(privateKey))) - //Realistically this should never happen because the private key shouldn't contain a value that goes to the zero point. - .getOrElse(throw new Exception("privateKey was invalid."))) + def computePublicKey(privateKey: PrivateKey): IO[PublicKey] = IO( + publicKeyTransform(publicKeyGen(privateKeyTransform(privateKey))) + // Realistically this should never happen because the private key shouldn't contain a value that goes to the zero point. + .getOrElse(throw new Exception("privateKey was invalid.")) + ) /** * Augment the private key with another. This does addition in Fr instead of Fp so it matches up the cycle of the curve. */ - def augmentPrivateKey(p1: PrivateKey, p2: PrivateKey): PrivateKey = { + def augmentPrivateKey(p1: PrivateKey, p2: PrivateKey): PrivateKey = PrivateKey(internal.Fp.bigIntToByteVector(internal.positiveMod(privateKeyTransform(p1).toBigInt + privateKeyTransform(p2).toBigInt, internal.Fp.Order))) - } /** * Using the randomBytes, generate a random element of G_T, which is one of the rth roots of unit in FP12. @@ -102,8 +105,8 @@ class CoreApi( publicSigningKey: PublicSigningKey, privateSigningKey: PrivateSigningKey ): IO[EncryptedValue] = for { - newTempKey <- generateGTElem - privateKey <- randomPrivateKey + newTempKey <- generateGTElem + privateKey <- randomPrivateKey transformedResult <- reencrypt(newTempKey, privateKey, encryptedValue, transformKey, publicSigningKey, privateSigningKey).toIO } yield transformedResult @@ -121,7 +124,7 @@ class CoreApi( publicSigningKey: PublicSigningKey, privateSigningKey: PrivateSigningKey ): IO[EncryptedValue] = for { - privateKey <- randomPrivateKey + privateKey <- randomPrivateKey encryptedResult <- encrypt(privateKey, toPublicKey, plaintext, publicSigningKey, privateSigningKey).toIO } yield encryptedResult @@ -131,11 +134,10 @@ class CoreApi( * @param privateKey - PrivateKey which we want to use to decrypt the EncryptedValue. * @return An error if the key didn't match or something was corrupted in the EncryptedValue, otherwise the recovered plaintext. */ - def decrypt(encryptedValue: EncryptedValue, privateKey: PrivateKey): Either[String, Plaintext] = { + def decrypt(encryptedValue: EncryptedValue, privateKey: PrivateKey): Either[String, Plaintext] = encryptedValueTransform(encryptedValue) .flatMap(e => encryptInstance.decrypt(privateKeyTransform(privateKey), e).leftMap(_.toString)) .map(fp12 => Plaintext(fp12.toHashBytes)) - } def deriveSymmetricKey(p: Plaintext): DecryptedSymmetricKey = DecryptedSymmetricKey(sha256(p)) @@ -161,7 +163,7 @@ class CoreApi( fromPrivateSigningKey: PrivateSigningKey ): IO[TransformKey] = for { reencryptionPrivateKey <- randomPrivateKey - tempKey <- generateGTElem + tempKey <- generateGTElem result <- generateTransformKey(fromPrivateKey, toPublicKey, reencryptionPrivateKey, tempKey, fromPublicSigningKey, fromPrivateSigningKey).toIO } yield result @@ -177,16 +179,15 @@ class CoreApi( privateKey: PrivateKey, publicKey: PublicKey, message: A - ): IO[SchnorrSignature] = { + ): IO[SchnorrSignature] = // Generate random values for K and try to sign until we get one that works randomFp .map(schnorrSigning.sign(privateKeyTransform(privateKey), publicKey.internalKey, message, _, sha256)) .iterateUntil(_.isDefined) .map { maybeSig => - val sig = maybeSig.get //Safe because of above `.isDefined` + val sig = maybeSig.get // Safe because of above `.isDefined` schnorrSignatureTransform(sig) } - } /** * Verify that the signature of a message is valid, given the public key that corresponds to the private key that @@ -205,9 +206,8 @@ class CoreApi( augmentingPrivateKey: PrivateKey, message: A, signature: SchnorrSignature - ): Boolean = { + ): Boolean = schnorrSigning.verify(publicKey.internalKey, privateKeyTransform(augmentingPrivateKey), message, schnorrSignatureTransform(signature), sha256) - } private[recrypt] def generateTransformKey( fromPrivateKey: PrivateKey, @@ -216,7 +216,7 @@ class CoreApi( tempKey: internal.FP12Elem[internal.Fp], publicSigningKey: PublicSigningKey, privateSigningKey: PrivateSigningKey - ) = { + ) = reencryptionKeyTransform( encryptInstance.generateReencryptionKey( privateKeyTransform(fromPrivateKey), @@ -227,7 +227,6 @@ class CoreApi( privateSigningKey ) ) - } private[recrypt] def encrypt( ephemeralPrivateKey: PrivateKey, @@ -250,16 +249,18 @@ class CoreApi( publicSigningKey: PublicSigningKey, privateSigningKey: PrivateSigningKey ) = for { - internalTransformKey <- transformKeyTransform(transformKey) + internalTransformKey <- transformKeyTransform(transformKey) internalEncryptedValue <- encryptedValueTransform(encryptedValue) - reencryptResult <- encryptInstance.reencrypt( - internalTransformKey, - internalEncryptedValue, - privateKeyTransform(newPrivateKey), - newTempKey, - publicSigningKey, - privateSigningKey - ).leftMap(_.toString) + reencryptResult <- encryptInstance + .reencrypt( + internalTransformKey, + internalEncryptedValue, + privateKeyTransform(newPrivateKey), + newTempKey, + publicSigningKey, + privateSigningKey + ) + .leftMap(_.toString) transformedResult <- encryptedValueTransform(reencryptResult) } yield transformedResult @@ -267,9 +268,9 @@ class CoreApi( object CoreApi { import internal.BytesDecoder - //Transform functions to/from all of types in recrypt's internal types to the Scala exposed types. - //Note that in most cases there are 2 methods with the same name, this is because the names here often reflect the names in the - //recrypt core. + // Transform functions to/from all of types in recrypt's internal types to the Scala exposed types. + // Note that in most cases there are 2 methods with the same name, this is because the names here often reflect the names in the + // recrypt core. private[recrypt] def publicKeyTransform(p: PublicKey) = p.internalKey private[recrypt] def publicKeyTransform(p: internal.PublicKey[internal.Fp]) = PublicKey.fromInternal(p) @@ -282,7 +283,7 @@ object CoreApi { private[recrypt] def encryptedMessageTransform(fp12: internal.FP12Elem[internal.Fp]): EncryptedMessage = EncryptedMessage(fp12.toHashBytes) private[recrypt] def reencryptionBlockTransform(r: internal.ReencryptionBlock[internal.Fp]): Either[String, TransformBlock] = for { - publicKey <- publicKeyTransform(r.publicKey).toRight("Public key wasn't valid.") + publicKey <- publicKeyTransform(r.publicKey).toRight("Public key wasn't valid.") randomPublicKey <- publicKeyTransform(r.randomRePublicKey).toRight("randomPublicKey wasn't valid.") result = TransformBlock( publicKey, @@ -296,7 +297,7 @@ object CoreApi { val publicKey = publicKeyTransform(r.publicKey) val randomPublicKey = publicKeyTransform(r.randomTransformPublicKey) for { - tempKey <- encryptedValueTransform(r.encryptedTempKey).leftMap(_ => "Invalid encryptedTempKey.") + tempKey <- encryptedValueTransform(r.encryptedTempKey).leftMap(_ => "Invalid encryptedTempKey.") randomTransformEncryptedTempKey <- encryptedValueTransform(r.randomTransformEncryptedTempKey) .leftMap(_ => "Invalid randomTransformEncryptedTempKey") } yield internal.ReencryptionBlock( @@ -307,19 +308,19 @@ object CoreApi { ) } - private[recrypt] def transformedValueTransform(t: TransformedValue): Either[String, internal.SignedValue[internal.EncryptedValue[internal.Fp]]] = { + private[recrypt] def transformedValueTransform(t: TransformedValue): Either[String, internal.SignedValue[internal.EncryptedValue[internal.Fp]]] = for { fp12 <- BytesDecoder[internal.FP12Elem[internal.Fp]].decode(t.encryptedMessage.bytes).leftMap(_ => "Payload of 'encryptedMessage' could not be converted") ephemeralPublicKey = publicKeyTransform(t.ephemeralPublicKey) authHash = t.authHash reencryptionBlocks <- t.transformBlocks.traverse(transformBlockTransform) } yield internal.SignedValue(t.publicSigningKey, t.signature, internal.ReencryptedValue(ephemeralPublicKey, fp12, authHash, reencryptionBlocks)) - } private[recrypt] def encryptedValueTransform(e: EncryptedValue): Either[String, internal.SignedValue[internal.EncryptedValue[internal.Fp]]] = e match { case e: EncryptedOnceValue => for { - fp12 <- BytesDecoder[internal.FP12Elem[internal.Fp]].decode(e.encryptedMessage.bytes) + fp12 <- BytesDecoder[internal.FP12Elem[internal.Fp]] + .decode(e.encryptedMessage.bytes) .leftMap(_ => "Payload of 'encryptedMessage' could not be converted") ephemeralPublicKey = publicKeyTransform(e.ephemeralPublicKey) authHash = e.authHash @@ -334,9 +335,9 @@ object CoreApi { .map(key => EncryptedOnceValue(key, EncryptedMessage(once.encryptedMessage.toHashBytes), authHash, e.publicSigningKey, e.signature)) .toRight("Invalid ephemeralPublicKey") }, - { reencrypted => + reencrypted => for { - key <- publicKeyTransform(reencrypted.ephemeralPublicKey).toRight("Invalid ephemeralPublicKey.") + key <- publicKeyTransform(reencrypted.ephemeralPublicKey).toRight("Invalid ephemeralPublicKey.") transformBlocks <- reencrypted.encryptionBlocks.traverse(reencryptionBlockTransform) } yield TransformedValue( key, @@ -346,7 +347,6 @@ object CoreApi { e.publicSigningKey, e.signature ) - } ) private[recrypt] def encryptedValueTransform(tempKey: internal.FP12Elem[internal.Fp]) = EncryptedElement(tempKey.toHashBytes) diff --git a/src/main/scala/com/ironcorelabs/recrypt/EncryptedValue.scala b/src/main/scala/com/ironcorelabs/recrypt/EncryptedValue.scala index e06bc47..1368c7a 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/EncryptedValue.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/EncryptedValue.scala @@ -25,16 +25,16 @@ import scodec.bits.ByteVector * transformed (delegated) to another person then it'll be a TransformedValue. */ sealed abstract class EncryptedValue { - def ephemeralPublicKey: PublicKey //Public key corresponding to secret key that was used to encrypt the symmetricKey - def encryptedMessage: EncryptedMessage //The encrypted plaintext + def ephemeralPublicKey: PublicKey // Public key corresponding to secret key that was used to encrypt the symmetricKey + def encryptedMessage: EncryptedMessage // The encrypted plaintext def authHash: AuthHash def publicSigningKey: PublicSigningKey def signature: Signature } final case class TransformedValue( - ephemeralPublicKey: PublicKey, //Public key which was used to produce the encryptedMessage - encryptedMessage: EncryptedMessage, //The encrypted plaintext + ephemeralPublicKey: PublicKey, // Public key which was used to produce the encryptedMessage + encryptedMessage: EncryptedMessage, // The encrypted plaintext authHash: AuthHash, transformBlocks: NonEmptyVector[TransformBlock], publicSigningKey: PublicSigningKey, @@ -42,8 +42,8 @@ final case class TransformedValue( ) extends EncryptedValue final case class EncryptedOnceValue( - ephemeralPublicKey: PublicKey, //Public key which was used to produce the encryptedMessage - encryptedMessage: EncryptedMessage, //The encrypted plaintext + ephemeralPublicKey: PublicKey, // Public key which was used to produce the encryptedMessage + encryptedMessage: EncryptedMessage, // The encrypted plaintext authHash: AuthHash, publicSigningKey: PublicSigningKey, signature: Signature @@ -53,7 +53,7 @@ final case class TransformBlock( publicKey: PublicKey, // Public key corresponding to private key used to encrypt the temp key encryptedTempKey: EncryptedElement, randomTransformPublicKey: PublicKey, // The public key corresponding to the private key used to encrypt the random re-encryption element - //The encrypted temp key value, which is used to go from the reencrypted value to the encrypted value + // The encrypted temp key value, which is used to go from the reencrypted value to the encrypted value randomTransformEncryptedTempKey: EncryptedElement ) diff --git a/src/main/scala/com/ironcorelabs/recrypt/HashedValue.scala b/src/main/scala/com/ironcorelabs/recrypt/HashedValue.scala index 51f75ef..88deda3 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/HashedValue.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/HashedValue.scala @@ -17,8 +17,8 @@ package com.ironcorelabs.recrypt -import scodec.bits.ByteVector import cats.syntax.either._ +import scodec.bits.ByteVector /** * A value (which is a point on the elliptic curve in the extension field) and is valid by construction. @@ -32,9 +32,12 @@ object HashedValue { def apply(bytes: ByteVector): Either[ApiError, HashedValue] = { import internal.Fp.implicits._ - internal.point.HomogeneousPoint.fromXYByteVectorOnTwistedCurve(bytes).leftMap[ApiError] { - case internal.PointNotOnCurve(_, _) => InvalidHashedValue("HashedValue was not a valid point on the curve.") - case internal.InvalidCoordinate(_, _) => InvalidHashedValue("HashedValue was not the correct length.") - }.map(iPoint => new HashedValue(iPoint.toByteVector) { val internalPoint = iPoint }) + internal.point.HomogeneousPoint + .fromXYByteVectorOnTwistedCurve(bytes) + .leftMap[ApiError] { + case internal.PointNotOnCurve(_, _) => InvalidHashedValue("HashedValue was not a valid point on the curve.") + case internal.InvalidCoordinate(_, _) => InvalidHashedValue("HashedValue was not the correct length.") + } + .map(iPoint => new HashedValue(iPoint.toByteVector) { val internalPoint = iPoint }) } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/PublicKey.scala b/src/main/scala/com/ironcorelabs/recrypt/PublicKey.scala index 5c7abe3..4e58635 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/PublicKey.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/PublicKey.scala @@ -17,10 +17,10 @@ package com.ironcorelabs.recrypt -import scodec.bits.ByteVector -import CoreApi.publicKeyTransform import cats.syntax.either._ -import internal.Fp.implicits._ +import com.ironcorelabs.recrypt.CoreApi.publicKeyTransform +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import scodec.bits.ByteVector /** * Public key which can be encrypted to. Ideally this would just be the internal @@ -29,6 +29,7 @@ import internal.Fp.implicits._ * This is guarenteed to be a valid point on the curve by construction. */ sealed abstract case class PublicKey(x: ByteVector, y: ByteVector) { + /** * Augment the public key with another PublicKey. The augmented public key will be the one that is used for any encryption. * Note that if a public key has been augmented, any TransformKeys that are created to delegate decryption from that key @@ -43,7 +44,7 @@ sealed abstract case class PublicKey(x: ByteVector, y: ByteVector) { } object PublicKey { - implicit val hashable: Hashable[PublicKey] = Hashable.by { pk: PublicKey => pk.x ++ pk.y } + implicit val hashable: Hashable[PublicKey] = Hashable.by((pk: PublicKey) => pk.x ++ pk.y) def apply(x: ByteVector, y: ByteVector): Either[ApiError, PublicKey] = internal.PublicKey.fromByteVectors(x, y).leftMap(_ => InvalidPublicKey).map(internalPK => new PublicKey(x, y) { val internalKey = internalPK }) @@ -51,7 +52,7 @@ object PublicKey { /** * Private to the package so we don't expose the internal public key in the public methods. */ - private[recrypt] def fromInternal(p: internal.PublicKey[internal.Fp]): Option[PublicKey] = p.toByteVectors.map { - case (publicX, publicY) => new PublicKey(publicX, publicY) { val internalKey = p } + private[recrypt] def fromInternal(p: internal.PublicKey[internal.Fp]): Option[PublicKey] = p.toByteVectors.map { case (publicX, publicY) => + new PublicKey(publicX, publicY) { val internalKey = p } } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/SchnorrSignature.scala b/src/main/scala/com/ironcorelabs/recrypt/SchnorrSignature.scala index de13422..fc6209b 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/SchnorrSignature.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/SchnorrSignature.scala @@ -38,7 +38,7 @@ sealed abstract case class SchnorrSignature(bytes: ByteVector) { } } -final object SchnorrSignature { +object SchnorrSignature { private val rLengthLong = 32L private val sLengthLong = 32L val LengthLong = rLengthLong + sLengthLong diff --git a/src/main/scala/com/ironcorelabs/recrypt/Sha256.scala b/src/main/scala/com/ironcorelabs/recrypt/Sha256.scala index 360b8e4..7fc791d 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/Sha256.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/Sha256.scala @@ -18,11 +18,12 @@ package com.ironcorelabs.recrypt import scodec.bits.ByteVector + import java.security.MessageDigest -final object Sha256 extends (ByteVector => ByteVector) { - //Since message digests are not thread safe, this should never be used directly. - //Instead use getSha256Copy. +object Sha256 extends (ByteVector => ByteVector) { + // Since message digests are not thread safe, this should never be used directly. + // Instead use getSha256Copy. private[this] val emptySha256 = MessageDigest.getInstance("SHA-256") private def getSha256Copy: MessageDigest = emptySha256.clone().asInstanceOf[MessageDigest] def apply(bytes: ByteVector): ByteVector = ByteVector.view(getSha256Copy.digest(bytes.toArray)) diff --git a/src/main/scala/com/ironcorelabs/recrypt/TransformKey.scala b/src/main/scala/com/ironcorelabs/recrypt/TransformKey.scala index 3f01f5c..1909f8d 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/TransformKey.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/TransformKey.scala @@ -17,13 +17,13 @@ package com.ironcorelabs.recrypt -import CoreApi.{ reencryptionKeyTransform, transformKeyTransform, privateKeyTransform } import cats.syntax.either._ -import syntax.hashable._ +import com.ironcorelabs.recrypt.CoreApi.{privateKeyTransform, reencryptionKeyTransform, transformKeyTransform} +import com.ironcorelabs.recrypt.syntax.hashable._ final case class TransformKey( - ephemeralPublicKey: PublicKey, //The ephemeral public key who encrypted the value - toPublicKey: PublicKey, //The person or device that can decrypt the result - encryptedTempKey: EncryptedElement, //The encrypted temp key value, which is used to go from the reencrypted value to the encrypted value + ephemeralPublicKey: PublicKey, // The ephemeral public key who encrypted the value + toPublicKey: PublicKey, // The person or device that can decrypt the result + encryptedTempKey: EncryptedElement, // The encrypted temp key value, which is used to go from the reencrypted value to the encrypted value hashedTempKey: HashedValue, publicSigningKey: PublicSigningKey, signature: Signature @@ -34,15 +34,15 @@ final case class TransformKey( */ def augment(privateKey: PrivateKey): Either[ApiError, TransformKey] = for { internalSignedKey <- transformKeyTransform(this).leftMap(InvalidTransformKey(_)) - //Note that this doesn't screw up the signing because augmentation tweaks the hashedK, which is not part of the - //bytes that are used for the signature. + // Note that this doesn't screw up the signing because augmentation tweaks the hashedK, which is not part of the + // bytes that are used for the signature. newSignedValue = internalSignedKey.copy(payload = internalSignedKey.payload.augment(privateKeyTransform(privateKey), TransformKey.g1)) result <- reencryptionKeyTransform(newSignedValue).leftMap(InvalidTransformKey(_)) } yield result } object TransformKey { - implicit val hashable: Hashable[TransformKey] = Hashable.by { tk: TransformKey => + implicit val hashable: Hashable[TransformKey] = Hashable.by { (tk: TransformKey) => tk.ephemeralPublicKey.toHashBytes ++ tk.toPublicKey.toHashBytes ++ tk.encryptedTempKey.toHashBytes ++ tk.hashedTempKey.toHashBytes ++ tk.publicSigningKey.toHashBytes } diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/BytesDecoder.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/BytesDecoder.scala index 95ae8c7..1fe225f 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/BytesDecoder.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/BytesDecoder.scala @@ -18,7 +18,6 @@ package com.ironcorelabs.recrypt.internal import cats.syntax.either._ - import scodec.bits.ByteVector trait BytesDecoder[A] { diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/CurvePoints.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/CurvePoints.scala index b1e7c74..8693fa3 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/CurvePoints.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/CurvePoints.scala @@ -17,7 +17,7 @@ package com.ironcorelabs.recrypt.internal -import point.HomogeneousPoint +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint /** * This type holds all the points that are used in our core algorithm for for `FpType`. @@ -29,6 +29,7 @@ import point.HomogeneousPoint final case class CurvePoints[FpType <: BigInt]( g1: HomogeneousPoint[FP2Elem[FpType]], hashElement: HomogeneousPoint[FP2Elem[FpType]], - generator: HomogeneousPoint[FpType]) { + generator: HomogeneousPoint[FpType] +) { val publicKeyGen = new PublicKeyGen[FpType](generator) } diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Ed25519Signing.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Ed25519Signing.scala index 7c7af13..b933273 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Ed25519Signing.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Ed25519Signing.scala @@ -23,10 +23,12 @@ import scodec.bits.ByteVector * An interface which defines how to sign and verify in Recrypt. */ abstract class Ed25519Signing { + /** * Sign message using privateSigningKey. */ def sign[A: Hashable](privateKey: PrivateSigningKey, message: A): Signature + /** * Verify that signature is valid for message using PublicSigningKey */ diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptError.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptError.scala index 21ebbfd..0df5195 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptError.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptError.scala @@ -16,6 +16,7 @@ */ package com.ironcorelabs.recrypt.internal + /** * Classes of errors that happen on Encrypt/Decrypt. */ diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptedValue.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptedValue.scala index 5a075be..749c613 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptedValue.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/EncryptedValue.scala @@ -18,8 +18,8 @@ package com.ironcorelabs.recrypt.internal import cats.data.NonEmptyVector -import scodec.bits.ByteVector import com.ironcorelabs.recrypt.syntax.hashable._ +import scodec.bits.ByteVector /** * The AuthHash is a value included in an encrypted message that can be used when the message @@ -41,7 +41,7 @@ object AuthHash { sealed abstract class EncryptedValue[A <: BigInt] { def fold[B](f: EncryptedOnceValue[A] => B, g: ReencryptedValue[A] => B): B = this match { case e: EncryptedOnceValue[_] => f(e) - case r: ReencryptedValue[_] => g(r) + case r: ReencryptedValue[_] => g(r) } def authHash: AuthHash def ephemeralPublicKey: PublicKey[A] @@ -106,4 +106,3 @@ object ReencryptionBlock { publicKey.toHashBytes ++ tempKey.toHashBytes ++ randomRePublicKey.toHashBytes ++ randomReEncTempKey.toHashBytes } } - diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/ExtensionField.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/ExtensionField.scala index 0008125..f45d715 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/ExtensionField.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/ExtensionField.scala @@ -27,7 +27,7 @@ trait ExtensionField[A <: BigInt] { // Used in frobenius, this is Xi^((p-1)/3) // Fp6Elem[A](Fp2Elem.Zero, Fp2Elem.One, Fp2Elem.Zero).frobenius - //Xi ^ ((p - p % 3) /3) because of the prime we've chosen, p % 3 == 1 + // Xi ^ ((p - p % 3) /3) because of the prime we've chosen, p % 3 == 1 def frobeniusFactor1: FP2Elem[A] // Used in frobenius, this is frobeniusFactor1^2 @@ -37,6 +37,7 @@ trait ExtensionField[A <: BigInt] { // q % 3 == 0 -- For our p // Xi ^ ((q - q % 3)/3) def frobeniusFactorFp12: FP2Elem[A] + /** * v is the thing that cubes to xi * v^3 = u+3, because by definition it is a solution to the equation y^3 - (u + 3) diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/FP12Elem.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/FP12Elem.scala index 8a74217..3140632 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/FP12Elem.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/FP12Elem.scala @@ -17,10 +17,10 @@ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field import cats.kernel.Eq -import spire.implicits._ import cats.syntax.contravariant._ +import spire.algebra.Field +import spire.implicits._ /** * An element of the degree 12 extension of our base finite field Fp. The degree 12 extension is formed on @@ -46,10 +46,10 @@ final case class FP12Elem[A <: BigInt: ExtensionField: Field](elem1: FP6Elem[A], FP12Elem[A](newFp1, newFp2) } - def unary_- : FP12Elem[A] = FP12Elem[A](-elem1, -elem2) //scalastyle:ignore method.name + def unary_- : FP12Elem[A] = FP12Elem[A](-elem1, -elem2) def inverse: FP12Elem[A] = { - //Algorithm 5.19 of El Mrabet--Joye 2017 "Guide to Pairing-Based Cryptography." + // Algorithm 5.19 of El Mrabet--Joye 2017 "Guide to Pairing-Based Cryptography." val (b, a) = (elem1, elem2) val v0 = a.square val v1 = b.square @@ -89,7 +89,7 @@ final case class FP12Elem[A <: BigInt: ExtensionField: Field](elem1: FP6Elem[A], FP12Elem[A](y1, y0) } - def ^(power: BigInt): FP12Elem[A] = { + def ^(power: BigInt): FP12Elem[A] = if (power == BigIntZero) { Field[FP12Elem[A]].one } else if (this == Field[FP12Elem[A]].zero) { @@ -98,17 +98,15 @@ final case class FP12Elem[A <: BigInt: ExtensionField: Field](elem1: FP6Elem[A], throw new Exception("Fp12 elements cannot be taken to negative powers.") } else { val bits = scodec.bits.BitVector(power.toByteArray).toIndexedSeq.dropWhile(!_) - bits.foldLeft(Field[FP12Elem[A]].one) { - case (cur, bit) => - val squareResult = cur.square - if (bit) squareResult * this else squareResult + bits.foldLeft(Field[FP12Elem[A]].one) { case (cur, bit) => + val squareResult = cur.square + if (bit) squareResult * this else squareResult } } - } def conjugate: FP12Elem[A] = FP12Elem[A](-elem1, elem2) - //This is the element to the p power. + // This is the element to the p power. def frobenius: FP12Elem[A] = { val a = elem1.frobenius val b = elem2.frobenius @@ -124,19 +122,30 @@ final case class FP12Elem[A <: BigInt: ExtensionField: Field](elem1: FP6Elem[A], def toFP2: Option[FP2Elem[A]] = elem2.toFP2 - override def toString: String = { + override def toString: String = s"(($elem1) * w + ($elem2))" - } } object FP12Elem { - def create[A <: BigInt: ExtensionField: Field: ModsByPrime](fp1: A, fp2: A, fp3: A, fp4: A, //scalastyle:ignore parameter.number - Need to take all 12. - fp5: A, fp6: A, fp7: A, fp8: A, fp9: A, fp10: A, fp11: A, fp12: A): FP12Elem[A] = FP12Elem[A]( + def create[A <: BigInt: ExtensionField: Field: ModsByPrime]( + fp1: A, + fp2: A, + fp3: A, + fp4: A, + fp5: A, + fp6: A, + fp7: A, + fp8: A, + fp9: A, + fp10: A, + fp11: A, + fp12: A + ): FP12Elem[A] = FP12Elem[A]( FP6Elem.create[A](fp1, fp2, fp3, fp4, fp5, fp6), FP6Elem.create[A](fp7, fp8, fp9, fp10, fp11, fp12) ) - implicit def field[A <: BigInt: ExtensionField: Field: ModsByPrime]: Field[FP12Elem[A]] = new Field.WithDefaultGCD[FP12Elem[A]] { + implicit def field[A <: BigInt: ExtensionField: Field: ModsByPrime]: Field[FP12Elem[A]] = new Field[FP12Elem[A]] { val fp6Zero = Field[FP6Elem[A]].zero def negate(x: FP12Elem[A]): FP12Elem[A] = -x val zero: FP12Elem[A] = FP12Elem[A](fp6Zero, fp6Zero) @@ -146,9 +155,8 @@ object FP12Elem { val one: FP12Elem[A] = FP12Elem[A](fp6Zero, Field[FP6Elem[A]].one) } - implicit def eq[A <: BigInt: Eq]: Eq[FP12Elem[A]] = Eq.instance { - case (FP12Elem(one, two), FP12Elem(onePrime, twoPrime)) => - one === onePrime && two === twoPrime + implicit def eq[A <: BigInt: Eq]: Eq[FP12Elem[A]] = Eq.instance { case (FP12Elem(one, two), FP12Elem(onePrime, twoPrime)) => + one === onePrime && two === twoPrime } implicit def hashable[A <: BigInt: Hashable]: Hashable[FP12Elem[A]] = @@ -164,7 +172,8 @@ object FP12Elem { implicit def byteDecoderFP12Elem[A <: BigInt: ModsByPrime](implicit readFp6A: BytesDecoder[FP6Elem[A]], fieldA: Field[A], - primeFieldA: ExtensionField[A]): BytesDecoder[FP12Elem[A]] = BytesDecoder.forSize(readFp6A.acceptableSize * 2) { b => + primeFieldA: ExtensionField[A] + ): BytesDecoder[FP12Elem[A]] = BytesDecoder.forSize(readFp6A.acceptableSize * 2) { b => val (first, second) = b.splitAt(b.length / 2) for { elem1 <- readFp6A.decode(first) diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/FP2Elem.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/FP2Elem.scala index f48ed16..59e0bbd 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/FP2Elem.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/FP2Elem.scala @@ -17,9 +17,10 @@ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field -import cats.kernel.Eq import cats.implicits._ +import cats.kernel.Eq +import spire.algebra.Field + /** * This is the degree 2 extension of the base field FP. It is formed by attaching the variable to * Fp, subject to the constraint u^2 + 1 = 0. That is, FP2 = Fp[u]/(u^2 + 1) @@ -41,7 +42,7 @@ final case class FP2Elem[A <: BigInt](elem1: A, elem2: A)(implicit mods: ModsByP def *(scalar: Int): FP2Elem[A] = modAndNew(elem1 * scalar, elem2 * scalar) - def unary_- : FP2Elem[A] = modAndNew(-elem1, -elem2) //scalastyle:ignore method.name + def unary_- : FP2Elem[A] = modAndNew(-elem1, -elem2) def square: FP2Elem[A] = { val a2 = elem1 * elem2 @@ -58,21 +59,20 @@ final case class FP2Elem[A <: BigInt](elem1: A, elem2: A)(implicit mods: ModsByP FP2Elem(mods.create(-elem1 * inv), mods.create(elem2 * inv)) } - //This is the element to the p power. - //Some of the reasoning is as follows + // This is the element to the p power. + // Some of the reasoning is as follows // x ^ p -x = 0 == x^p = x - //By the binomial expansion we get: + // By the binomial expansion we get: // (x + (y * u)) ^ p == x^p + p * (middle terms) + (u^p * y^p) // u ^p == -u which is because our p is congruent to 3 mod 4 // x^p + -uy^p == x + -uy def frobenius: FP2Elem[A] = modAndNew(-elem1, elem2) - def ^(power: BigInt): FP2Elem[A] = { //scalastyle:ignore + def ^(power: BigInt): FP2Elem[A] = { val bits = scodec.bits.BitVector(power.toByteArray).toIndexedSeq.dropWhile(!_) - val result = bits.toIndexedSeq.foldLeft(modAndNew(0, 1)) { - case (cur, bit) => - val squareResult = cur * cur - if (bit) squareResult * this else squareResult + val result = bits.toIndexedSeq.foldLeft(modAndNew(0, 1)) { case (cur, bit) => + val squareResult = cur * cur + if (bit) squareResult * this else squareResult } if (power < 0) result.inverse else result } @@ -81,11 +81,11 @@ final case class FP2Elem[A <: BigInt](elem1: A, elem2: A)(implicit mods: ModsByP } -object FP2Elem { //scalastyle:ignore +object FP2Elem { def fromBigInts[A <: BigInt](elem1: BigInt, elem2: BigInt)(implicit mods: ModsByPrime[A]): FP2Elem[A] = FP2Elem(mods.create(elem1), mods.create(elem2)) implicit final def fieldInstance[A <: BigInt](implicit fieldA: Field[A], modsByPrime: ModsByPrime[A]): Field[FP2Elem[A]] = - new Field.WithDefaultGCD[FP2Elem[A]] { + new Field[FP2Elem[A]] { def negate(x: FP2Elem[A]): FP2Elem[A] = -x def zero: FP2Elem[A] = FP2Elem(fieldA.zero, fieldA.zero) @@ -96,14 +96,14 @@ object FP2Elem { //scalastyle:ignore def one: FP2Elem[A] = FP2Elem(fieldA.zero, fieldA.one) } - implicit def eq[A <: BigInt: Eq]: Eq[FP2Elem[A]] = Eq.instance { - case (FP2Elem(x, y), FP2Elem(x2, y2)) => x2.eqv(x) && y2.eqv(y) + implicit def eq[A <: BigInt: Eq]: Eq[FP2Elem[A]] = Eq.instance { case (FP2Elem(x, y), FP2Elem(x2, y2)) => + x2.eqv(x) && y2.eqv(y) } implicit def hashable[A <: BigInt: Hashable]: Hashable[FP2Elem[A]] = Hashable[(A, A)].contramap { case FP2Elem(elem1, elem2) => (elem1, elem2) } implicit def byteDecoderFP2Elem[A <: BigInt](implicit readA: BytesDecoder[A], modsByPrime: ModsByPrime[A]): BytesDecoder[FP2Elem[A]] = BytesDecoder.forSize(readA.acceptableSize * 2) { bytes => val (first, second) = bytes.splitAt(bytes.length / 2) - (readA.decode(first), readA.decode(second)).mapN { FP2Elem(_, _) } + (readA.decode(first), readA.decode(second)).mapN(FP2Elem(_, _)) } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/FP6Elem.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/FP6Elem.scala index 15aff73..5cc020c 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/FP6Elem.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/FP6Elem.scala @@ -17,10 +17,10 @@ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field import cats.kernel.Eq -import cats.syntax.eq._ import cats.syntax.contravariant._ +import cats.syntax.eq._ +import spire.algebra.Field /** * This is the degree 6 extension of the base field, which is formed on top of the degree 2 extension @@ -45,7 +45,7 @@ final case class FP6Elem[A <: BigInt: ModsByPrime](elem1: FP2Elem[A], elem2: FP2 FP6Elem[A](newFp1, newFp2, newFp3) } - def unary_- : FP6Elem[A] = FP6Elem[A](-elem1, -elem2, -elem3) //scalastyle:ignore + def unary_- : FP6Elem[A] = FP6Elem[A](-elem1, -elem2, -elem3) def *(other: FP6Elem[A])(implicit extensionField: ExtensionField[A]): FP6Elem[A] = { val Xi = implicitly[ExtensionField[A]].xi @@ -96,8 +96,8 @@ final case class FP6Elem[A <: BigInt: ModsByPrime](elem1: FP2Elem[A], elem2: FP2 FP6Elem[A](c2, c1, c0) } - //This is the element to the p power. - //a^p + (b^p * v^p) + c^p *(v^p)^2 + // This is the element to the p power. + // a^p + (b^p * v^p) + c^p *(v^p)^2 // v^p == (v ^(p % 3)) * Xi ^ ((p - p % 3) /3) def frobenius(implicit extensionField: ExtensionField[A]): FP6Elem[A] = { val frobeniusFactor1 = extensionField.frobeniusFactor1 @@ -131,7 +131,7 @@ object FP6Elem { def create[A <: BigInt: ModsByPrime](a: A, b: A, a2: A, b2: A, a3: A, b3: A): FP6Elem[A] = FP6Elem[A](FP2Elem[A](a, b), FP2Elem[A](a2, b2), FP2Elem[A](a3, b3)) - implicit def field[A <: BigInt: Field: ExtensionField: ModsByPrime]: Field[FP6Elem[A]] = new Field.WithDefaultGCD[FP6Elem[A]] { + implicit def field[A <: BigInt: Field: ExtensionField: ModsByPrime]: Field[FP6Elem[A]] = new Field[FP6Elem[A]] { def negate(x: FP6Elem[A]): FP6Elem[A] = -x val zero: FP6Elem[A] = { val fp2Zero = Field[FP2Elem[A]].zero @@ -147,9 +147,8 @@ object FP6Elem { } } - implicit def eq[A <: BigInt: Eq]: Eq[FP6Elem[A]] = Eq.instance { - case (FP6Elem(one, two, three), FP6Elem(onePrime, twoPrime, threePrime)) => - one === onePrime && two === twoPrime && three === threePrime + implicit def eq[A <: BigInt: Eq]: Eq[FP6Elem[A]] = Eq.instance { case (FP6Elem(one, two, three), FP6Elem(onePrime, twoPrime, threePrime)) => + one === onePrime && two === twoPrime && three === threePrime } implicit def hashable[A <: BigInt: Hashable]: Hashable[FP6Elem[A]] = Hashable[(FP2Elem[A], FP2Elem[A], FP2Elem[A])].contramap { diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Fp.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Fp.scala index 8960193..4b5a46e 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Fp.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Fp.scala @@ -18,9 +18,9 @@ package com.ironcorelabs.recrypt.internal import cats.kernel.Eq +import cats.syntax.either._ import scodec.bits.ByteVector import spire.algebra.Field -import cats.syntax.either._ /** * Fp represents a value in the field of integers mod some Prime - that is, values in [0, Prime - 1]. @@ -32,7 +32,7 @@ import cats.syntax.either._ * We get the guarantees about Fp's safety by modding anytime someone calls the apply on the companion * object, but without any runtime allocations. */ -final object Fp { +object Fp { def apply(x: BigInt): Impl.T = Impl(x) def apply(b: ByteVector): Impl.T = Impl(b) trait BigIntImpl { @@ -47,14 +47,14 @@ final object Fp { def apply(b: ByteVector): T = apply(byteVectorToBigInt(b)) } - //For info on the Algorithm, etc. Please refer to Fp.scala. - //BNParam for this is + // For info on the Algorithm, etc. Please refer to Fp.scala. + // BNParam for this is final val Prime = BigInt("65000549695646603732796438742359905742825358107623003571877145026864184071783") final val Order = BigInt("65000549695646603732796438742359905742570406053903786389881062969044166799969") val Zero = Fp(BigIntZero) val One = Fp(BigIntOne) - //The leading byte is a 0 since Prime is positive, we don't want that in all the sizes. + // The leading byte is a 0 since Prime is positive, we don't want that in all the sizes. val ExpectedFpLength: Long = Prime.toByteArray.length - 1L val ExpectedOrderLength: Long = Order.toByteArray.length - 1L @@ -62,23 +62,23 @@ final object Fp { * inverse mod a prime is always in Fp, so the cast is safe. */ def inverseModPrime(fp: Fp): Fp = inverse(fp, Prime).getOrElse(Fp.Zero).asInstanceOf[Fp] + /** * Only call this if `i` is very close to the Prime, otherwise it will be inefficient. */ @annotation.tailrec - def fastModPrime(i: BigInt): Fp = { + def fastModPrime(i: BigInt): Fp = if (i >= Fp.Prime) { fastModPrime(i - Prime) } else { Fp(i) } - } def bigIntToByteVector(b: BigInt): ByteVector = { val zeroByte = 0.toByte val byteVector = ByteVector.view(b.toByteArray) - //Drop the leading zero if there is one (Because this value is positive.) Then make sure that the - //byteVector is padded out to ExpectedFpLength + // Drop the leading zero if there is one (Because this value is positive.) Then make sure that the + // byteVector is padded out to ExpectedFpLength byteVector.dropWhile(_ == zeroByte).padLeft(ExpectedFpLength) } @@ -125,13 +125,13 @@ final object Fp { ) } - //Object which contains the implicits for Fp. - final object implicits { // scalastyle:ignore object.name + // Object which contains the implicits for Fp. + object implicits { implicit val hashableFp: Hashable[Fp.Impl.T] = Hashable.by(bigIntToByteVector) implicit val fpEq: Eq[Fp.Impl.T] = Eq.fromUniversalEquals - implicit val fieldForFp: Field[Fp.Impl.T] = new Field.WithDefaultGCD[Fp] { - //These casts are safe because they shouldn't ever produce something that is - //not in Fp. This is demonstrated in unit tests, but not statically. + implicit val fieldForFp: Field[Fp.Impl.T] = new Field[Fp] { + // These casts are safe because they shouldn't ever produce something that is + // not in Fp. This is demonstrated in unit tests, but not statically. def negate(x: Fp): Fp = if (x == Fp.Zero) Fp.Zero else (Fp.Prime - x).asInstanceOf[Fp] val zero: Fp = Fp.Zero def plus(x: Fp, y: Fp): Fp = fastModPrime(x + y) @@ -165,14 +165,15 @@ final object Fp { } implicit val pairingConfigFp: PairingConfig[Fp.Impl.T] = new PairingConfig[Fp.Impl.T] { - //NAF of 6*BNParam + 2 - private[this] val NAF = IndexedSeq(0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0) //scalastyle:ignore + // NAF of 6*BNParam + 2 + private[this] val NAF = IndexedSeq(0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 1, 0, + -1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0) // The reason we drop(2) is because of Algorithm 1 in High-Speed Software Implementation of the Optimal Ate Pairing over Barreto–Naehrig Curves val nafForLoop: IndexedSeq[Int] = NAF.reverse.drop(2) - //This is based on the BNParam. It's the cuberoot of BNParam. It should always be called - //in multiples of 3. + // This is based on the BNParam. It's the cuberoot of BNParam. It should always be called + // in multiples of 3. def bnPow(self: FP12Elem[Fp.Impl.T]): FP12Elem[Fp.Impl.T] = { - //This is a hardcode of the square and multiply for bnPow + // This is a hardcode of the square and multiply for bnPow var x = self var res = x 1.to(8).foreach(_ => x = square(x)) diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Fp480.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Fp480.scala index 7f87d10..c9b13df 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Fp480.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Fp480.scala @@ -18,9 +18,9 @@ package com.ironcorelabs.recrypt.internal import cats.kernel.Eq +import cats.syntax.either._ import scodec.bits.ByteVector import spire.algebra.Field -import cats.syntax.either._ /** * Fp480 represents a value in the field of integers mod some Prime - that is, values in [0, Prime - 1]. @@ -32,7 +32,7 @@ import cats.syntax.either._ * We get the guarantees about Fp480's safety by modding anytime someone calls the apply on the companion * object, but without any runtime allocations. */ -final object Fp480 { +object Fp480 { def apply(x: BigInt): Impl.T = Impl(x) def apply(b: ByteVector): Impl.T = Impl(b) trait BigIntImpl { @@ -46,22 +46,26 @@ final object Fp480 { def apply(x: BigInt): T = positiveMod(x, Prime) def apply(b: ByteVector): T = apply(byteVectorToBigInt(b)) } - //scalastyle:off - final val Prime = BigInt("3121577065842246806003085452055281276803074876175537384188619957989004527066410274868798956582915008874704066849018213144375771284425395508176023") - final val Order = BigInt("3121577065842246806003085452055281276803074876175537384188619957989004525299611739143164276204220965332554591187396064132658995685351714167608049") - //scalastyle:on + + final val Prime = BigInt( + "3121577065842246806003085452055281276803074876175537384188619957989004527066410274868798956582915008874704066849018213144375771284425395508176023" + ) + final val Order = BigInt( + "3121577065842246806003085452055281276803074876175537384188619957989004525299611739143164276204220965332554591187396064132658995685351714167608049" + ) + val Zero = Fp480(BigIntZero) val One = Fp480(BigIntOne) - //The leading byte is a 0 since Prime is positive, we don't want that in all the sizes. + // The leading byte is a 0 since Prime is positive, we don't want that in all the sizes. val ExpectedFp480Length: Long = Prime.toByteArray.length - 1L val ExpectedOrderLength: Long = Order.toByteArray.length - 1L def bigIntToByteVector(b: BigInt): ByteVector = { val zeroByte = 0.toByte val byteVector = ByteVector.view(b.toByteArray) - //Drop the leading zero if there is one (Because this value is positive.) Then make sure that the - //byteVector is padded out to ExpectedFpLength + // Drop the leading zero if there is one (Because this value is positive.) Then make sure that the + // byteVector is padded out to ExpectedFpLength byteVector.dropWhile(_ == zeroByte).padLeft(ExpectedFp480Length) } @@ -69,21 +73,21 @@ final object Fp480 { * inverse mod a prime is always in Fp480, so the cast is safe. */ def inverseModPrime(fp: Fp480): Fp480 = inverse(fp, Prime).getOrElse(Fp480.Zero).asInstanceOf[Fp480] + /** * Only call this if `i` is very close to the Prime, otherwise it will be inefficient. */ @annotation.tailrec - def fastModPrime(i: BigInt): Fp480 = { + def fastModPrime(i: BigInt): Fp480 = if (i >= Fp480.Prime) { fastModPrime(i - Prime) } else { Fp480(i) } - } lazy val curvePoints: CurvePoints[Fp480.Impl.T] = { import implicits._ - //scalastyle:off + CurvePoints( // Fixed point in cyclic group G1 (the trace zero subgroup). // Start with a point that is on the twisted curve y^2 = x^3 + (3 / (u + 3)). @@ -92,12 +96,28 @@ final object Fp480 { // Compute the anti-trace map of that r-torsion element to get a point in the trace-zero subgroup. point.HomogeneousPoint[FP2Elem[Fp480]]( FP2Elem( - Fp480(BigInt("2836796539847730496121374298065944583953504150765508351672461175175719456840753019328265331693934514908570706456436537314841014056269083482678066")), - Fp480(BigInt("2673768771775032355420306564841108930438651217980189126243896874678717443069132673614464990588309533043439946857284622768054880686771881306409642")) + Fp480( + BigInt( + "2836796539847730496121374298065944583953504150765508351672461175175719456840753019328265331693934514908570706456436537314841014056269083482678066" + ) + ), + Fp480( + BigInt( + "2673768771775032355420306564841108930438651217980189126243896874678717443069132673614464990588309533043439946857284622768054880686771881306409642" + ) + ) ), FP2Elem( - Fp480(BigInt("3080607037190881313834826417530769563132997895310223092587326825944478280552006660025218522727539672756392754158719384720663526682905220416822282")), - Fp480(BigInt("2906149584369018327289172171212098825323249826660713579814103802892067659387776431613853400363371122569649698984076618174478076051599518261188038")) + Fp480( + BigInt( + "3080607037190881313834826417530769563132997895310223092587326825944478280552006660025218522727539672756392754158719384720663526682905220416822282" + ) + ), + Fp480( + BigInt( + "2906149584369018327289172171212098825323249826660713579814103802892067659387776431613853400363371122569649698984076618174478076051599518261188038" + ) + ) ), FP2Elem(Zero, One) ), @@ -106,29 +126,52 @@ final object Fp480 { // encoded in ASCII/UTF-8, converted to a BigInt. point.HomogeneousPoint[FP2Elem[Fp480]]( FP2Elem( - Fp480(BigInt("2755895806273995492284787079187941247738254659153318682910850469784894541505170101984499629579667341065183727568252238059654392233777140703184622")), - Fp480(BigInt("630223019374291956078632635377008181978279936792489208439110695275442238629433173084638817027401619964084048824893758705005177091915333122454106")) + Fp480( + BigInt( + "2755895806273995492284787079187941247738254659153318682910850469784894541505170101984499629579667341065183727568252238059654392233777140703184622" + ) + ), + Fp480( + BigInt( + "630223019374291956078632635377008181978279936792489208439110695275442238629433173084638817027401619964084048824893758705005177091915333122454106" + ) + ) ), FP2Elem( - Fp480(BigInt("659567418809487070027824196603118281636508923398279856378657485535700744304348227321440219246561941778839111505653577989859933696546799454574627")), - Fp480(BigInt("2632696014493840722302529499863944843283552594579584896121087553911353425460849587377878627157950485322470437984154786925535244302963434645693127")) + Fp480( + BigInt( + "659567418809487070027824196603118281636508923398279856378657485535700744304348227321440219246561941778839111505653577989859933696546799454574627" + ) + ), + Fp480( + BigInt( + "2632696014493840722302529499863944843283552594579584896121087553911353425460849587377878627157950485322470437984154786925535244302963434645693127" + ) + ) ), FP2Elem( - Fp480(BigInt("2723878025330396352455760809227014699447653800671598495327573996671655085492645713095099955627015617726770647513458138760772123814185152132721554")), - Fp480(BigInt("2520811096583992837832885181589663735998061148584558864774875442611283633943850563303274829680791759077833709816521531207043963496532513260928366")) + Fp480( + BigInt( + "2723878025330396352455760809227014699447653800671598495327573996671655085492645713095099955627015617726770647513458138760772123814185152132721554" + ) + ), + Fp480( + BigInt( + "2520811096583992837832885181589663735998061148584558864774875442611283633943850563303274829680791759077833709816521531207043963496532513260928366" + ) + ) ) ), point.HomogeneousPoint(Fp480(1), Fp480(2), Fp480(1)) ) - //scalastyle:on } - //Object which contains the implicits for Fp480. - final object implicits { // scalastyle:ignore object.name + // Object which contains the implicits for Fp480. + object implicits { implicit val fp480Eq: Eq[Fp480.Impl.T] = Eq.fromUniversalEquals - implicit val fieldForFp480: Field[Fp480.Impl.T] = new Field.WithDefaultGCD[Fp480] { - //These casts are safe because they shouldn't ever produce something that is - //not in Fp480. This is demonstrated in unit tests, but not statically. + implicit val fieldForFp480: Field[Fp480.Impl.T] = new Field[Fp480] { + // These casts are safe because they shouldn't ever produce something that is + // not in Fp480. This is demonstrated in unit tests, but not statically. def negate(x: Fp480): Fp480 = if (x == Fp480.Zero) Fp480.Zero else (Fp480.Prime - x).asInstanceOf[Fp480] val zero: Fp480 = Fp480.Zero def plus(x: Fp480, y: Fp480): Fp480 = fastModPrime(x + y) @@ -146,20 +189,44 @@ final object Fp480 { implicit val extensionFieldFp480: ExtensionField[Fp480.Impl.T] = new ExtensionField[Fp480.Impl.T] { val xi: FP2Elem[Fp480.Impl.T] = FP2Elem(Fp480(1), Fp480(3)) - //scalastyle:off + val frobeniusFactor1: FP2Elem[Fp480.Impl.T] = FP2Elem( - Fp480(BigInt("2705020609406098470693743943193507017690525853579041639836321147125100162418094245778443957282985233325521741487078451689773015537700623376387510")), - Fp480(BigInt("1651643729828744562959031609260204931467006255025965356538853937438900508750440674159520451455470865884696804132950675577710427706655106873786415")) + Fp480( + BigInt( + "2705020609406098470693743943193507017690525853579041639836321147125100162418094245778443957282985233325521741487078451689773015537700623376387510" + ) + ), + Fp480( + BigInt( + "1651643729828744562959031609260204931467006255025965356538853937438900508750440674159520451455470865884696804132950675577710427706655106873786415" + ) + ) ) val frobeniusFactor2: FP2Elem[Fp480.Impl.T] = FP2Elem( - Fp480(BigInt("2306651261022207350847683647334036061609898996050387019709069937614457385067216464366007100887697910705559503143400341307341852524867445116042081")), - Fp480(BigInt("2700715513864156317217817646762981219394581764002749630356081821581587105847754189716578562648186994801551242072586877237522675959303129100251619")) + Fp480( + BigInt( + "2306651261022207350847683647334036061609898996050387019709069937614457385067216464366007100887697910705559503143400341307341852524867445116042081" + ) + ), + Fp480( + BigInt( + "2700715513864156317217817646762981219394581764002749630356081821581587105847754189716578562648186994801551242072586877237522675959303129100251619" + ) + ) ) val frobeniusFactorFp12: FP2Elem[Fp480.Impl.T] = FP2Elem( - Fp480(BigInt("1656507924366244928424688705439191250492553228839737584554076474712325077234544758394965182643615114744030751122897661836350026981040666763359635")), - Fp480(BigInt("411347727129503104504468123876138850111359831064167067331474757563790630947112631916366442374487601276802707186517326847256605909760387475785136")) + Fp480( + BigInt( + "1656507924366244928424688705439191250492553228839737584554076474712325077234544758394965182643615114744030751122897661836350026981040666763359635" + ) + ), + Fp480( + BigInt( + "411347727129503104504468123876138850111359831064167067331474757563790630947112631916366442374487601276802707186517326847256605909760387475785136" + ) + ) ) - //scalastyle:on + /** * v is the thing that cubes to xi * v^3 = u+3, because by definition it is a solution to the equation y^3 - (u + 3) @@ -168,14 +235,16 @@ final object Fp480 { } implicit val pairingConfigFp480: PairingConfig[Fp480.Impl.T] = new PairingConfig[Fp480.Impl.T] { - //NAF of 6*BNParam + 2 - private[this] val NAF = IndexedSeq(0, 0, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, -1, 0, 0, 1, 0, 1, 0) //scalastyle:ignore + // NAF of 6*BNParam + 2 + private[this] val NAF = IndexedSeq(0, 0, 0, -1, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 0, -1, 0, 0, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, + 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, -1, 0, 1, 0, -1, 0, 0, 1, 0, 1, 0) // The reason we drop(2) is because of Algorithm 1 in High-Speed Software Implementation of the Optimal Ate Pairing over Barreto–Naehrig Curves val nafForLoop: IndexedSeq[Int] = NAF.reverse.drop(2) - //This is based on the BNParam. It's the cuberoot of BNParam. It should always be called - //in multiples of 3. + // This is based on the BNParam. It's the cuberoot of BNParam. It should always be called + // in multiples of 3. def bnPow(self: FP12Elem[Fp480.Impl.T]): FP12Elem[Fp480.Impl.T] = { - //This is a hardcode of the square and multiply for bnPow + // This is a hardcode of the square and multiply for bnPow var x = self var res = x 1.to(3).foreach(_ => x = square(x)) diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Hashable.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Hashable.scala index 6cb7304..1c204b0 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Hashable.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Hashable.scala @@ -17,10 +17,11 @@ package com.ironcorelabs.recrypt.internal -import scodec.bits.{ ByteOrdering, ByteVector } import cats._ -import cats.syntax.contravariant._ import cats.data.NonEmptyVector +import cats.syntax.contravariant._ +import scodec.bits.{ByteOrdering, ByteVector} + /** * Typeclass for converting A to a stable byte representation which is used for hashing, which means it will stay consistent * regardless of the changes to the class. @@ -39,7 +40,7 @@ object Hashable { def by[A](f: A => ByteVector): Hashable[A] = (a: A) => f(a) implicit def instance: Contravariant[Hashable] = new Contravariant[Hashable] { - def contramap[A, B](fa: Hashable[A])(f: B => A): Hashable[B] = Hashable.by { b: B => fa(f(b)) } + def contramap[A, B](fa: Hashable[A])(f: B => A): Hashable[B] = Hashable.by((b: B) => fa(f(b))) } implicit val hashableInt: Hashable[Int] = by(i => ByteVector.fromInt(i, 4, ByteOrdering.BigEndian)) @@ -49,21 +50,16 @@ object Hashable { implicit val hashableString: Hashable[String] = by(s => ByteVector.view(s.getBytes("UTF-8"))) implicit def hashableVector[A](implicit hashableA: Hashable[A]): Hashable[Vector[A]] = Hashable.by[Vector[A]] { - _.foldLeft(ByteVector.empty) { (acc, a) => acc ++ hashableA.toByteVector(a) } + _.foldLeft(ByteVector.empty)((acc, a) => acc ++ hashableA.toByteVector(a)) } implicit def hashableNonEmptyVector[A: Hashable]: Hashable[NonEmptyVector[A]] = Hashable[Vector[A]].contramap(_.toVector) - implicit def hashableTuple2[A, B](implicit - hashableA: Hashable[A], - hashableB: Hashable[B]): Hashable[(A, B)] = Hashable.by { - case (a, b) => hashableA(a) ++ hashableB(b) + implicit def hashableTuple2[A, B](implicit hashableA: Hashable[A], hashableB: Hashable[B]): Hashable[(A, B)] = Hashable.by { case (a, b) => + hashableA(a) ++ hashableB(b) } - implicit def hashableTuple3[A, B, C](implicit - hashableA: Hashable[A], - hashableB: Hashable[B], - hashableC: Hashable[C]): Hashable[(A, B, C)] = Hashable.by { + implicit def hashableTuple3[A, B, C](implicit hashableA: Hashable[A], hashableB: Hashable[B], hashableC: Hashable[C]): Hashable[(A, B, C)] = Hashable.by { case (a, b, c) => hashableA(a) ++ hashableB(b) ++ hashableC(c) } @@ -71,8 +67,9 @@ object Hashable { hashableA: Hashable[A], hashableB: Hashable[B], hashableC: Hashable[C], - hashableD: Hashable[D]): Hashable[(A, B, C, D)] = Hashable.by { - case (a, b, c, d) => hashableA(a) ++ hashableB(b) ++ hashableC(c) ++ hashableD(d) + hashableD: Hashable[D] + ): Hashable[(A, B, C, D)] = Hashable.by { case (a, b, c, d) => + hashableA(a) ++ hashableB(b) ++ hashableC(c) ++ hashableD(d) } implicit def hashableTuple5[A, B, C, D, E](implicit @@ -80,8 +77,9 @@ object Hashable { hashableB: Hashable[B], hashableC: Hashable[C], hashableD: Hashable[D], - hashableE: Hashable[E]): Hashable[(A, B, C, D, E)] = Hashable.by { - case (a, b, c, d, e) => hashableA(a) ++ hashableB(b) ++ hashableC(c) ++ hashableD(d) ++ hashableE(e) + hashableE: Hashable[E] + ): Hashable[(A, B, C, D, E)] = Hashable.by { case (a, b, c, d, e) => + hashableA(a) ++ hashableB(b) ++ hashableC(c) ++ hashableD(d) ++ hashableE(e) } implicit def hashable[A](implicit hashableA: Hashable[A]): Hashable[Option[A]] = Hashable.by { maybeA => diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/InternalApi.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/InternalApi.scala index d67cb9b..efa5405 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/InternalApi.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/InternalApi.scala @@ -16,11 +16,11 @@ */ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field -import point.HomogeneousPoint -import cats.data.NonEmptyVector import cats.Eq +import cats.data.NonEmptyVector import cats.implicits._ +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import spire.algebra.Field import spire.implicits._ /** @@ -31,7 +31,8 @@ import spire.implicits._ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: PairingConfig]( hashFunc: Sha256Hash, ed25519Signing: Ed25519Signing, - curvePoints: CurvePoints[FpType])(implicit mods: ModsByPrime[FpType]) { + curvePoints: CurvePoints[FpType] +)(implicit mods: ModsByPrime[FpType]) { type ErrorOr[A] = Either[EncryptError, A] private[this] val OneByte = 1.toByte @@ -92,8 +93,9 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing goodEncryptedValue <- verifySignedValue(signedEncryptedValue).toRight(SignatureFailed(signedEncryptedValue)) unverifiedPlaintext = goodEncryptedValue.fold(decryptEncryptedOnce(privateKey, _), decryptReencryptedValue(privateKey, _)) computedAuthHash = AuthHash.create(hashFunc, goodEncryptedValue.ephemeralPublicKey, unverifiedPlaintext) - result <- if (goodEncryptedValue.authHash != computedAuthHash) AuthHashMatchFailed(signedEncryptedValue).asLeft - else unverifiedPlaintext.asRight + result <- + if (goodEncryptedValue.authHash != computedAuthHash) AuthHashMatchFailed(signedEncryptedValue).asLeft + else unverifiedPlaintext.asRight } yield result /** @@ -104,7 +106,7 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing */ final private[internal] def decryptEncryptedOnce(privateKey: PrivateKey[FpType], encryptedValue: EncryptedOnceValue[FpType]): FP12Elem[FpType] = { val EncryptedOnceValue(ephemPubKey, encryptedMessage, _) = encryptedValue - //This is because + // This is because // m*pair(P,Q)*pair(P,-Q) = m*pair(P,Q)*pair(P,Q)^(-1) = m val maybePlaintext = encryptedMessage * pair(ephemPubKey.value.negate.times(privateKey.toBigInt), g1) maybePlaintext @@ -155,19 +157,17 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing raReK: FP12Elem[FpType], publicSigningKey: PublicSigningKey, privateSigningKey: PrivateSigningKey - ): ErrorOr[SignedValue[EncryptedValue[FpType]]] = { + ): ErrorOr[SignedValue[EncryptedValue[FpType]]] = ( verifySignedValue(signedEncryptedValue).toRight(SignatureFailed(signedEncryptedValue)), verifySignedValue(signedReencryptionKey).toRight(ReencryptionKeyIsCorrupt(signedReencryptionKey)) ).mapN { (encryptedValue, reencryptionKey) => - val reencryptedValue: EncryptedValue[FpType] = encryptedValue.fold[EncryptedValue[FpType]]( - reencryptEncryptedOnce(reencryptionKey, _, raRePriKey, raReK), - reencryptReencryptedValue(reencryptionKey, _, raRePriKey, raReK) - ) - signValue(reencryptedValue, publicSigningKey, privateSigningKey) - } - - } + val reencryptedValue: EncryptedValue[FpType] = encryptedValue.fold[EncryptedValue[FpType]]( + reencryptEncryptedOnce(reencryptionKey, _, raRePriKey, raReK), + reencryptReencryptedValue(reencryptionKey, _, raRePriKey, raReK) + ) + signValue(reencryptedValue, publicSigningKey, privateSigningKey) + } /** * Verifies the Ed25519 signature on a signed value. @@ -239,7 +239,7 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing // The algorithm specifies that we should operate on the last element of the reencryptionBlocks val reencryptionBlockL = reencryptionBlocks.toVector.last // Here anything that is suffixed with `L` means it was a member of the last element - val ReencryptionBlock(reencryptionPubKeyL, encryptedKL, randomReencryptionPubKeyL, randomReencryptionEncryptedKL) = reencryptionBlockL //scalastyle:ignore + val ReencryptionBlock(reencryptionPubKeyL, encryptedKL, randomReencryptionPubKeyL, randomReencryptionEncryptedKL) = reencryptionBlockL val encryptedKPrimel = encryptedKL * pair(reencryptionPubKeyL.value, hashedK) // re-encrypted K val randomReencryptionPubKey = publicKeyGen(randomReencryptionPriKey) @@ -247,7 +247,8 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing // Modify the random rencryptionEncryptedK with the new randomReencryptionK val randomReencryptionKLPrime = randomReencryptionEncryptedKL * pair(randomReencryptionPubKeyL.value, hash2(randomReencryptionTempKey).add(hashedK)) val reencryptionBlockLPrime = reencryptionBlockL.withNewTempKey(encryptedKPrimel, randomReencryptionKLPrime) - val newReencryptionBlock = ReencryptionBlock(reencryptionPublicKey, encryptedTempKey, randomReencryptionPubKey, randomReencryptionEncryptedTempKey) //scalastyle:ignore + val newReencryptionBlock = + ReencryptionBlock(reencryptionPublicKey, encryptedTempKey, randomReencryptionPubKey, randomReencryptionEncryptedTempKey) // Because we modified the last block, replace it and append the new block as well. val newBlocksVector = fromVectorAndNonEmpty(reencryptionBlocks.toVector.init, NonEmptyVector.of(reencryptionBlockLPrime, newReencryptionBlock)) reencryptedValue.copy(encryptionBlocks = newBlocksVector) @@ -262,15 +263,17 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing final private[internal] def decryptReencryptedValue(privateKey: PrivateKey[FpType], reencryptedValue: ReencryptedValue[FpType]): FP12Elem[FpType] = reencryptedValue.encryptionBlocks match { case encryptionBlocks => - //Here anything that is suffixed with `L` means it was a member of the last element + // Here anything that is suffixed with `L` means it was a member of the last element val reencryptionBlockL = encryptionBlocks.toVector.last val ReencryptionBlock(rePubKeyl, encryptedKl, raRePubKeyl, raReEncKl) = reencryptionBlockL val secondToLastK = encryptedKl * pair(rePubKeyl.value.negate.times(privateKey.toBigInt), g1) val secondToLastRandomReencryptionK = raReEncKl * pair(raRePubKeyl.value.negate.times(privateKey.toBigInt), g1) - //We're going through the list backwards because we unravel the reencryption blocks from last to first, the last one is special so it's done first. + // We're going through the list backwards because we unravel the reencryption blocks from last to first, the last one is special so it's done first. val (firstK, firstRandomReencryptionK) = encryptionBlocks.toVector.reverse.tail.foldLeft((secondToLastK, secondToLastRandomReencryptionK)) { - case ((currentK, currentRandomReencryptionK), - ReencryptionBlock(nextReencryptionPubKey, nextEncryptedK, nextRandomReencryptionPubKey, nextRandomReencryptionK)) => + case ( + (currentK, currentRandomReencryptionK), + ReencryptionBlock(nextReencryptionPubKey, nextEncryptedK, nextRandomReencryptionPubKey, nextRandomReencryptionK) + ) => val currentKHash = hash2(currentK) val nextK = nextEncryptedK * pair(nextReencryptionPubKey.value.negate, currentKHash) val nextRandomReencyptionK = nextRandomReencryptionK * pair( @@ -289,10 +292,9 @@ class InternalApi[FpType <: BigInt: Hashable: Field: ExtensionField: Eq: Pairing * @return a point in G1, in homogeneous coordinates. */ final def hash2(fp12: FP12Elem[FpType]): HomogeneousPoint[FP2Elem[FpType]] = { - //Produce a 512 bit byte vector, which ensures we have a big enough value for 480 and Fp - //We use a constant value combined with the entire fp12 element so we don't leak information about the fp12 structure. + // Produce a 512 bit byte vector, which ensures we have a big enough value for 480 and Fp + // We use a constant value combined with the entire fp12 element so we don't leak information about the fp12 structure. val bytes = hashFunc((ZeroByte, fp12)) ++ hashFunc((OneByte, fp12)) - hashElement.times(mods.create(bytes)) //Multiplation, which will always occur times the appropriate modded Fp element. + hashElement.times(mods.create(bytes)) // Multiplation, which will always occur times the appropriate modded Fp element. } } - diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Key.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Key.scala index 3f051dc..dc1e308 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Key.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Key.scala @@ -16,12 +16,12 @@ */ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field -import point.HomogeneousPoint -import scodec.bits.ByteVector import cats.Eq -import cats.syntax.either._ import cats.syntax.contravariant._ +import cats.syntax.either._ +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import scodec.bits.ByteVector +import spire.algebra.Field import spire.implicits._ /** @@ -63,12 +63,12 @@ final case class PublicKey[FpType] private[internal] (value: HomogeneousPoint[Fp object PublicKey { def fromByteVectors[A: Field: Eq](x: ByteVector, y: ByteVector)(implicit bytesDecoder: BytesDecoder[A]): Either[PointError, PublicKey[A]] = for { - ax <- bytesDecoder.decode(x).leftMap(decodeError => InvalidCoordinate(x, decodeError.toString)) - ay <- bytesDecoder.decode(y).leftMap(decodeError => InvalidCoordinate(x, decodeError.toString)) + ax <- bytesDecoder.decode(x).leftMap(decodeError => InvalidCoordinate(x, decodeError.toString)) + ay <- bytesDecoder.decode(y).leftMap(decodeError => InvalidCoordinate(x, decodeError.toString)) point <- HomogeneousPoint(ax, ay) } yield new PublicKey(point) - implicit def hashable[A: Hashable]: Hashable[PublicKey[A]] = Hashable[Option[(A, A)]].contramap { _.value.normalize } - implicit def eq[A: Eq]: Eq[PublicKey[A]] = Eq.by { _.value.normalize } + implicit def hashable[A: Hashable]: Hashable[PublicKey[A]] = Hashable[Option[(A, A)]].contramap(_.value.normalize) + implicit def eq[A: Eq]: Eq[PublicKey[A]] = Eq.by(_.value.normalize) } /** @@ -77,11 +77,12 @@ object PublicKey { * so it can be decrypted using the delegatee's private key. */ final case class ReencryptionKey[FpType <: BigInt]( - rePublicKey: PublicKey[FpType], //An ephemeral key that is randomly chosen when this reencryption key is generated - toPublicKey: PublicKey[FpType], //The person or device that can decrypt the result - encryptedK: FP12Elem[FpType], //A random value in G_T, encrypted to the toPublicKey + rePublicKey: PublicKey[FpType], // An ephemeral key that is randomly chosen when this reencryption key is generated + toPublicKey: PublicKey[FpType], // The person or device that can decrypt the result + encryptedK: FP12Elem[FpType], // A random value in G_T, encrypted to the toPublicKey hashedK: HomogeneousPoint[FP2Elem[FpType]] // A hashed version of the random value from G_T, used to perform the transform ) { + /** * Augment the transform key. It's augmented using the inverse of the augmentation key to "undo" * the augmentation we did in the public key that created this key. @@ -92,7 +93,7 @@ final case class ReencryptionKey[FpType <: BigInt]( object ReencryptionKey { implicit def hashable[A <: BigInt: Hashable]: Hashable[ReencryptionKey[A]] = Hashable[(PublicKey[A], PublicKey[A], FP12Elem[A])].contramap { - //Note that the hashedK is not included in the hashable bytes. + // Note that the hashedK is not included in the hashable bytes. case ReencryptionKey(rePublicKey, toPublicKey, encryptedK, _) => (rePublicKey, toPublicKey, encryptedK) } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/Pairing.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/Pairing.scala index 4684b23..c0d3208 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/Pairing.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/Pairing.scala @@ -17,13 +17,13 @@ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field -import point.{ HomogeneousPoint } import cats.Eq +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import spire.algebra.Field class Pairing[FpType <: BigInt: Field: ExtensionField](implicit fpTypePairingConfig: PairingConfig[FpType], mods: ModsByPrime[FpType]) { - //These are used in the frobenius method below - val w: FP12Elem[FpType] = FP12Elem[FpType](Field[FP6Elem[FpType]].one, Field[FP6Elem[FpType]].zero) //w^2 = v + // These are used in the frobenius method below + val w: FP12Elem[FpType] = FP12Elem[FpType](Field[FP6Elem[FpType]].one, Field[FP6Elem[FpType]].zero) // w^2 = v private[this] val wSquared = w.square private[this] val wCubed = wSquared * w final val FrobeniusFactor1: FP12Elem[FpType] = wSquared.frobenius * wSquared.inverse @@ -31,7 +31,7 @@ class Pairing[FpType <: BigInt: Field: ExtensionField](implicit fpTypePairingCon def frobenius(point: HomogeneousPoint[FP2Elem[FpType]])(implicit eqFpType: Eq[FpType]): HomogeneousPoint[FP2Elem[FpType]] = point match { case HomogeneousPoint(x, y, z) => - //Frobenius endomorphism of the twisted curve. This will be used in the pairing. + // Frobenius endomorphism of the twisted curve. This will be used in the pairing. val newX = (FrobeniusFactor1 * x.frobenius).toFP2.getOrElse(throw new Exception(s"Cannot go to Fp2 for x on '$x'")) val newY = (FrobeniusFactor2 * y.frobenius).toFP2.getOrElse(throw new Exception(s"Cannot go to Fp2 for y on '$y'")) HomogeneousPoint(newX, newY, z.frobenius) @@ -41,11 +41,11 @@ class Pairing[FpType <: BigInt: Field: ExtensionField](implicit fpTypePairingCon // Script l with addition in the denominator from Miller's Algorithm // Used in step 6 or 8 of Algorithm 1 in High-Speed Software Implementation of the Optimal Ate Pairing over Barreto–Naehrig Curves def addLineEval(px: FpType, py: FpType, q: HomogeneousPoint[FP2Elem[FpType]], r: HomogeneousPoint[FP2Elem[FpType]]): (FP12Elem[FpType], FP2Elem[FpType]) = { - val numerator = (r.y * q.z - q.y * r.z) - val denominator = (r.x * q.z - q.x * r.z) + val numerator = r.y * q.z - q.y * r.z + val denominator = r.x * q.z - q.x * r.z finalizeEval(q, px, py, numerator, denominator) } - //returns the value at P of the function whose zero-set is the line through Q and R. + // returns the value at P of the function whose zero-set is the line through Q and R. // Script l with multiplication in the denominator from Miller's Algorithm // Used in step 4 of Algorithm 1 in High-Speed Software Implementation of the Optimal Ate Pairing over Barreto–Naehrig Curves def doubleLineEval(px: FpType, py: FpType, r: HomogeneousPoint[FP2Elem[FpType]]): (FP12Elem[FpType], FP2Elem[FpType]) = { @@ -57,53 +57,58 @@ class Pairing[FpType <: BigInt: Field: ExtensionField](implicit fpTypePairingCon private def finalizeEval(q: HomogeneousPoint[FP2Elem[FpType]], px: FpType, py: FpType, numerator: FP2Elem[FpType], denominator: FP2Elem[FpType]) = { val zero = Field[FP2Elem[FpType]].zero val zerqFp = Field[FpType].zero - (FP12Elem( - FP6Elem(zero, q.x * numerator - q.y * denominator, -q.z * numerator * FP2Elem(zerqFp, px)), - FP6Elem(zero, zero, q.z * denominator * FP2Elem(zerqFp, py)) - ), q.z * denominator) + ( + FP12Elem( + FP6Elem(zero, q.x * numerator - q.y * denominator, -q.z * numerator * FP2Elem(zerqFp, px)), + FP6Elem(zero, zero, q.z * denominator * FP2Elem(zerqFp, py)) + ), + q.z * denominator + ) } - //Final exponentiation: compute the value f^((p^12 - 1) / r). This maps f to one of the rth roots of unity. - //The exponent is factored, which allows the computation to be done in two parts (each with several steps): + // Final exponentiation: compute the value f^((p^12 - 1) / r). This maps f to one of the rth roots of unity. + // The exponent is factored, which allows the computation to be done in two parts (each with several steps): // The easy part, which consists entirely of calls to frobenius and inverse. // The hard part, which involves expressing the exponent as a polynomial in x = 1868033. - def finalExponentiation(initialF: FP12Elem[FpType]): FP12Elem[FpType] = { //scalastyle:off + def finalExponentiation(initialF: FP12Elem[FpType]): FP12Elem[FpType] = { var f = initialF - //Easy part - //"Computing f^((p^6-1)(p^2+1))..." + // Easy part + // "Computing f^((p^6-1)(p^2+1))..." var g = 0.to(5).foldLeft(f) { case (acc, _) => acc.frobenius } - f = g * f.inverse // f = f^(p^6-1) + f = g * f.inverse // f = f^(p^6-1) f = f.frobenius.frobenius * f // f = f^(p^2+1) - //Hard part: compute f = f^((p^4 - p^2 + 1)/r) - Section 7 of Devegili Scott Dahab Pairings over BN curves - Algorithm 3 - //At this point, f has the convenient property that f^(p^6+1) == 1. - //Thus, f^(-1) == f^p^6 == frobenius^6(f) - //We also express the exponent as a polynomial in x=1868033. See Section 7 and in particular Algorithm 3 in Devegili--Scott--Dahab "Implementing Pairings over Barreto--Naehrig Curves" - //(p^4 - p^2 + 1)/r = p^3 + p^2(6t^2+1) + p(-36t^3-18t^2-12t+1) + (-36t^3-30t^2-18t-2), where t is the BNParam + // Hard part: compute f = f^((p^4 - p^2 + 1)/r) - Section 7 of Devegili Scott Dahab Pairings over BN curves - Algorithm 3 + // At this point, f has the convenient property that f^(p^6+1) == 1. + // Thus, f^(-1) == f^p^6 == frobenius^6(f) + // We also express the exponent as a polynomial in x=1868033. See Section 7 and in particular Algorithm 3 in Devegili--Scott--Dahab "Implementing Pairings over Barreto--Naehrig Curves" + // (p^4 - p^2 + 1)/r = p^3 + p^2(6t^2+1) + p(-36t^3-18t^2-12t+1) + (-36t^3-30t^2-18t-2), where t is the BNParam val fInv = f.conjugate // f is unitary (See explanation in Beuchet--Gonzalez-Diaz--Mitsunari et. al. bottom of page 4), so f^(-1) == \overline{f} - g = fpTypePairingConfig.square(fInv) //g = f^(-2) - g = fpTypePairingConfig.square(g) * g //g = g^3 - g = fpTypePairingConfig.bnPow(g) //g = g^x, where x = 1868033 = cube root of BNParam - g = fpTypePairingConfig.bnPow(g) //g = g^x - g = fpTypePairingConfig.bnPow(g) //g = g^x = f^(-6x^3) - val a = g * fpTypePairingConfig.square(fpTypePairingConfig.square(fInv)) * fInv //a = f^-(6*x^3-5) - var b = a.frobenius //b = a^p - b = a * b //b = a^(p+1) - val g1 = f.frobenius //g1 = f^p - val g2 = g1.frobenius //g2 = g2^p - val g3 = g2.frobenius //g3 = g2^p = f^(p^3) - val g4 = b * fpTypePairingConfig.square(g1) * g2 //g4 = b*g1^2*g2 - var g5 = fpTypePairingConfig.square(g4) //g5 = g4^2 - g5 = fpTypePairingConfig.square(g5) * g5 //g5 = g5^3 = g4^6 - g5 = fpTypePairingConfig.bnPow(g5) //g5^x - g5 = fpTypePairingConfig.bnPow(g5) //g5^x - g5 = fpTypePairingConfig.bnPow(g5) //g5^x - g5 = fpTypePairingConfig.bnPow(g5) //g5^x - g5 = fpTypePairingConfig.bnPow(g5) //g5^x - g5 = fpTypePairingConfig.bnPow(g5) //g5^x + g = fpTypePairingConfig.square(fInv) // g = f^(-2) + g = fpTypePairingConfig.square(g) * g // g = g^3 + g = fpTypePairingConfig.bnPow(g) // g = g^x, where x = 1868033 = cube root of BNParam + g = fpTypePairingConfig.bnPow(g) // g = g^x + g = fpTypePairingConfig.bnPow(g) // g = g^x = f^(-6x^3) + val a = g * fpTypePairingConfig.square(fpTypePairingConfig.square(fInv)) * fInv // a = f^-(6*x^3-5) + var b = a.frobenius // b = a^p + b = a * b // b = a^(p+1) + val g1 = f.frobenius // g1 = f^p + val g2 = g1.frobenius // g2 = g2^p + val g3 = g2.frobenius // g3 = g2^p = f^(p^3) + val g4 = b * fpTypePairingConfig.square(g1) * g2 // g4 = b*g1^2*g2 + var g5 = fpTypePairingConfig.square(g4) // g5 = g4^2 + g5 = fpTypePairingConfig.square(g5) * g5 // g5 = g5^3 = g4^6 + g5 = fpTypePairingConfig.bnPow(g5) // g5^x + g5 = fpTypePairingConfig.bnPow(g5) // g5^x + g5 = fpTypePairingConfig.bnPow(g5) // g5^x + g5 = fpTypePairingConfig.bnPow(g5) // g5^x + g5 = fpTypePairingConfig.bnPow(g5) // g5^x + g5 = fpTypePairingConfig.bnPow(g5) // g5^x val g6 = g1 * f - g3 * g5 * g4 * b * fpTypePairingConfig.square(fpTypePairingConfig.square(fpTypePairingConfig.square(g6))) * g6 * a * fpTypePairingConfig.square(fpTypePairingConfig.square(f)) - } //scalastyle:on + g3 * g5 * g4 * b * fpTypePairingConfig.square(fpTypePairingConfig.square(fpTypePairingConfig.square(g6))) * g6 * a * fpTypePairingConfig.square( + fpTypePairingConfig.square(f) + ) + } // This is the optimal Ate pairing, as introduced in the paper "The Eta Pairing Revisited" by // Hess, et al., from 2006. Our implementation is based on the paper "High-Speed Software @@ -115,32 +120,31 @@ class Pairing[FpType <: BigInt: Field: ExtensionField](implicit fpTypePairingCon var f2 = Field[FP2Elem[FpType]].one val negQ = pointQ.negate - //The NAFforLoop is the Non adjacent form of the loopLength. - val pointResult = fpTypePairingConfig.nafForLoop.foldLeft(pointQ) { - case (accPoint, nafValue) => - var pointR = accPoint - var pointS = pointR.double - val (ell1, ell2) = doubleLineEval(px, py, pointR) - f1 = ell1 * f1.square - f2 = ell2 * f2.square + // The NAFforLoop is the Non adjacent form of the loopLength. + val pointResult = fpTypePairingConfig.nafForLoop.foldLeft(pointQ) { case (accPoint, nafValue) => + var pointR = accPoint + var pointS = pointR.double + val (ell1, ell2) = doubleLineEval(px, py, pointR) + f1 = ell1 * f1.square + f2 = ell2 * f2.square + pointR = pointS + if (nafValue == -1) { + pointS = negQ.add(pointR) + val (ell1, ell2) = addLineEval(px, py, negQ, pointR) + f1 *= ell1 + f2 *= ell2 + pointR = pointS + pointR + } else if (nafValue == 1) { + pointS = pointQ.add(pointR) + val (ell1, ell2) = addLineEval(px, py, pointQ, pointR) + f1 *= ell1 + f2 *= ell2 pointR = pointS - if (nafValue == -1) { - pointS = negQ.add(pointR) - val (ell1, ell2) = addLineEval(px, py, negQ, pointR) - f1 *= ell1 - f2 *= ell2 - pointR = pointS - pointR - } else if (nafValue == 1) { - pointS = pointQ.add(pointR) - val (ell1, ell2) = addLineEval(px, py, pointQ, pointR) - f1 *= ell1 - f2 *= ell2 - pointR = pointS - pointR - } else { - pointR - } + pointR + } else { + pointR + } } val pointQ1 = frobenius(pointQ) val pointQ2 = frobenius(pointQ1) diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/PairingConfig.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/PairingConfig.scala index 0ddca8e..eaedf99 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/PairingConfig.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/PairingConfig.scala @@ -17,8 +17,8 @@ package com.ironcorelabs.recrypt.internal -import spire.implicits._ import spire.algebra.Field +import spire.implicits._ /** * This type represents the infomation to configure the pairing for a particular FpType. @@ -34,11 +34,13 @@ abstract class PairingConfig[FpType <: BigInt] { val z2 = z * extension.xi + 1 FP12Elem[FpType](a2, FP6Elem(y, x, z2)) } + /** * raising of the fp12 to the cuberoot of the BNParam for FpType. * This is usually a hand optimized version of the square and multiply. */ def bnPow(fp12: FP12Elem[FpType]): FP12Elem[FpType] + /** * The naf which is used for the miller loop. In both our cases it's the NAF of 6*BNParam + 2 reversed with the last 2 dropped off. */ diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/SchnorrSignature.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/SchnorrSignature.scala index 6f4184e..c807b01 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/SchnorrSignature.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/SchnorrSignature.scala @@ -17,27 +17,28 @@ package com.ironcorelabs.recrypt.internal -import spire.algebra.Field -import spire.implicits._ import cats.Eq import scodec.bits.ByteVector +import spire.algebra.Field +import spire.implicits._ // Both r and s will be positive values less than the order that was used to produce it. // r will be greater than zero. final case class SchnorrSignature(r: BigInt, s: BigInt) class SchnorrSigning[B <: BigInt: Eq: Hashable: Field](generator: point.HomogeneousPoint[B], order: BigInt, frByteSize: Long)(implicit mods: ModsByPrime[B]) { - //Defining this locally as it's possibly not what some people would want. - //We want to drop all the leading 0s and ensure that the value is padded to the correct length for Fr. + // Defining this locally as it's possibly not what some people would want. + // We want to drop all the leading 0s and ensure that the value is padded to the correct length for Fr. implicit val hashableBigInt: Hashable[BigInt] = Hashable.by(bigIntToByteVector) private def bigIntToByteVector(b: BigInt): ByteVector = { val zeroByte = 0.toByte val byteVector = ByteVector.view(b.toByteArray) - //Drop the leading zero if there is one (Because this value is positive.) Then make sure that the - //byteVector is padded out to frByteSize + // Drop the leading zero if there is one (Because this value is positive.) Then make sure that the + // byteVector is padded out to frByteSize byteVector.dropWhile(_ == zeroByte).padLeft(frByteSize) } val publicKeyGen = PublicKeyGen(generator) + /** * Sign a message using our PRE privateKey. Also requires the corresponding (augmented) public key, which is * included in the hash in order to prevent forgery attacks. @@ -56,7 +57,7 @@ class SchnorrSigning[B <: BigInt: Eq: Hashable: Field](generator: point.Homogene message: A, k: BigInt, sha256: Sha256Hash - ): Option[SchnorrSignature] = { + ): Option[SchnorrSignature] = if (k >= order) { // If g * k == the zero point, return None. This will only happen if (k mod Curve.Order) == 0 // Also reject any values for k that are larger than Curve.Order. Though they would wrap around, @@ -64,22 +65,19 @@ class SchnorrSigning[B <: BigInt: Eq: Hashable: Field](generator: point.Homogene // to handle a return of None, just do that for any k >= Curve.Order, and let the caller retry. None } else { - generator.times(k).normalize.flatMap { - case (px, _) => { - val r = positiveMod(px, order) - if (r == BigIntZero) - // Also need caller to try agian if we end up with a non-zero point that happens to have (x mod Curve.Order) == 0 - None - else { - //Create a value that's bigger than the Fp or Fp480 so either one will have a sufficiently large h - val h = mods.create(sha256((r, publicKey, message)) ++ sha256((publicKey, message, r))) - val s = positiveMod(k - h * privateKey.fp, order) - Some(SchnorrSignature(r, s)) - } + generator.times(k).normalize.flatMap { case (px, _) => + val r = positiveMod(px, order) + if (r == BigIntZero) + // Also need caller to try agian if we end up with a non-zero point that happens to have (x mod Curve.Order) == 0 + None + else { + // Create a value that's bigger than the Fp or Fp480 so either one will have a sufficiently large h + val h = mods.create(sha256((r, publicKey, message)) ++ sha256((publicKey, message, r))) + val s = positiveMod(k - h * privateKey.fp, order) + Some(SchnorrSignature(r, s)) } } } - } /** * Verify that signature of the message is valid using public key. This is complicated by the fact that the public diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/SignedValue.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/SignedValue.scala index 71966ad..a938f10 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/SignedValue.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/SignedValue.scala @@ -26,12 +26,12 @@ import cats.syntax.contravariant._ final case class SignedValue[A](publicSigningKey: PublicSigningKey, signature: Signature, payload: A) object SignedValue { - //Used to create a value which will be signed, later. This should only be done immediately before - //signing. Tests ensure that the signature isn't part of the "hashable" instance. + // Used to create a value which will be signed, later. This should only be done immediately before + // signing. Tests ensure that the signature isn't part of the "hashable" instance. def withEmptySignature[A](publicSigningKey: PublicSigningKey, payload: A): SignedValue[A] = SignedValue(publicSigningKey, Signature.empty, payload) implicit def hashable[A](implicit hashableA: Hashable[A]): Hashable[SignedValue[A]] = - Hashable[(PublicSigningKey, A)].contramap { - case SignedValue(key, _, payload) => (key, payload) + Hashable[(PublicSigningKey, A)].contramap { case SignedValue(key, _, payload) => + (key, payload) } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/SigningKey.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/SigningKey.scala index b51aa35..d1c638f 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/SigningKey.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/SigningKey.scala @@ -22,8 +22,8 @@ import scodec.bits.ByteVector final case class PublicSigningKey(bytes: ByteVector) extends AnyVal object PublicSigningKey { - implicit val hashable: Hashable[PublicSigningKey] = Hashable.by { - case PublicSigningKey(bytes) => bytes + implicit val hashable: Hashable[PublicSigningKey] = Hashable.by { case PublicSigningKey(bytes) => + bytes } val empty: PublicSigningKey = PublicSigningKey(ByteVector.empty) } @@ -39,4 +39,3 @@ final case class Signature(bytes: ByteVector) extends AnyVal object Signature { val empty = Signature(ByteVector.empty) } - diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/package.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/package.scala index 76a2e16..e133822 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/package.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/package.scala @@ -18,6 +18,7 @@ package com.ironcorelabs.recrypt import cats.data.NonEmptyVector + /** * Internal is a namespace that houses all the internal types and algorithms for the implementation. This is not meant to be * used by public consumers of recrypt. @@ -53,7 +54,7 @@ package object internal { def gcde(a: BigInt, b: BigInt): (BigInt, BigInt, BigInt) = { @annotation.tailrec def f(t: (BigInt, BigInt, BigInt), t1: (BigInt, BigInt, BigInt)): (BigInt, BigInt, BigInt) = (t, t1) match { - case (t, (BigIntZero, _, _)) => t + case (t, (BigIntZero, _, _)) => t case ((a1, sa, ta), t @ (b1, sb, tb)) => val (q, r) = divMod(a1, b1) f(t, (r, sa - (q * sb), ta - (q * tb))) @@ -77,12 +78,12 @@ package object internal { * @return - Immutable vector which represents the NAF of value. */ def createNAF(value: BigInt): Vector[Int] = { - //Mutable collection which has all 0s in it. + // Mutable collection which has all 0s in it. val naf = scala.collection.mutable.IndexedSeq.fill(nbits(value) + 1)(0) var i = 0 var n = value - while (n > 0) { + while (n > 0) if (n % BigIntTwo != 0) { naf(i) = (BigIntTwo - (n % BigIntFour)).toInt n -= naf(i) @@ -90,11 +91,10 @@ package object internal { n /= BigIntTwo i += 1 } - } naf.toVector } - //We assume the byteVector is meant to represent a positive integer. + // We assume the byteVector is meant to represent a positive integer. def byteVectorToBigInt(b: scodec.bits.ByteVector): BigInt = BigInt((0.toByte +: b).toArray) /** diff --git a/src/main/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPoint.scala b/src/main/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPoint.scala index afb5de8..d118d3c 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPoint.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPoint.scala @@ -17,15 +17,15 @@ package com.ironcorelabs.recrypt.internal package point -import spire.algebra.Field import algebra.ring.AdditiveCommutativeGroup -import spire.implicits._ +import cats.instances.either._ import cats.kernel.Eq -import scodec.bits.ByteVector import cats.syntax.apply._ -import cats.instances.either._ -import cats.syntax.either._ import cats.syntax.contravariant._ +import cats.syntax.either._ +import scodec.bits.ByteVector +import spire.algebra.Field +import spire.implicits._ object HomogeneousPoint { implicit def aGroup[A: Field: Eq]: AdditiveCommutativeGroup[HomogeneousPoint[A]] = new AdditiveCommutativeGroup[HomogeneousPoint[A]] { @@ -38,7 +38,7 @@ object HomogeneousPoint { } implicit def eq[A](implicit aEq: Eq[A], field: Field[A]): Eq[HomogeneousPoint[A]] = Eq.instance { case (HomogeneousPoint(x, y, z), HomogeneousPoint(x1, y1, z1)) => - //This is to save doing inverses on z and z1. For equality we can instead do the multiplation instead. + // This is to save doing inverses on z and z1. For equality we can instead do the multiplation instead. (aEq.eqv(z, z1) && aEq.eqv(x, x1) && aEq.eqv(y, y1)) || (aEq.eqv(x * z1, x1 * z) && aEq.eqv(y * z1, y1 * z)) } @@ -47,10 +47,11 @@ object HomogeneousPoint { */ implicit def hashable[A](implicit A: Hashable[A]): Hashable[HomogeneousPoint[A]] = Hashable[Option[(A, A)]].contramap(_.normalize) - //This will take 2 FP2Elem points which are concatenated. - //If the point isn't on the curve or if the bytes didn't represent 2 FP2Elems, left. Otherwise Right(HomogeneousPoint[FP12Elem]) + // This will take 2 FP2Elem points which are concatenated. + // If the point isn't on the curve or if the bytes didn't represent 2 FP2Elems, left. Otherwise Right(HomogeneousPoint[FP12Elem]) def fromXYByteVectorOnTwistedCurve[A <: BigInt: BytesDecoder: Field: ExtensionField: Eq: ModsByPrime]( - bytes: ByteVector): Either[PointError, HomogeneousPoint[FP2Elem[A]]] = { + bytes: ByteVector + ): Either[PointError, HomogeneousPoint[FP2Elem[A]]] = { val twistedCurveConstCoeff: FP2Elem[A] = implicitly[ExtensionField[A]].xi.reciprocal * 3 // 3 / (u + 3) //COLT: Should move to prime field maybe? val (first, second) = bytes.splitAt(bytes.size / 2) @@ -59,21 +60,19 @@ object HomogeneousPoint { BytesDecoder[FP2Elem[A]].decode(second).leftMap(_ => InvalidCoordinate(first, "Bytes for y coordinate didn't represent a valid FP2Elem")) ).tupled - candidateXY.flatMap { - case (x, y) => - if (y.pow(2) === (x.pow(3) + twistedCurveConstCoeff)) - HomogeneousPoint[FP2Elem[A]](x, y, Field[FP2Elem[A]].one).asRight - else - PointNotOnCurve(x, y).asLeft + candidateXY.flatMap { case (x, y) => + if (y.pow(2) === (x.pow(3) + twistedCurveConstCoeff)) + HomogeneousPoint[FP2Elem[A]](x, y, Field[FP2Elem[A]].one).asRight + else + PointNotOnCurve(x, y).asLeft } } - def apply[A: Field: Eq](x: A, y: A): Either[PointError, HomogeneousPoint[A]] = { + def apply[A: Field: Eq](x: A, y: A): Either[PointError, HomogeneousPoint[A]] = if (x.pow(3) + 3 == y.pow(2)) withoutCurveValidation(x, y).asRight else PointNotOnCurve(x, y).asLeft - } def withoutCurveValidation[A: Field: Eq](x: A, y: A): HomogeneousPoint[A] = HomogeneousPoint(x, y, Field[A].one) @@ -85,12 +84,14 @@ object HomogeneousPoint { * * Note that this value is *not* verified to be on the curve. If you want to do that, it'll have to be done as part of the translation * for whatever A type the coordinate represents. + * + * Use the two-argument HomogeneousPoint.apply when you need the curve check. */ -final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: Field[A], eqA: Eq[A]) { +final case class HomogeneousPoint[A](x: A, y: A, z: A)(implicit aField: Field[A], eqA: Eq[A]) { private[this] val ZeroA: A = aField.zero private[this] def zeroPoint: HomogeneousPoint[A] = HomogeneousPoint(aField.zero, aField.one, aField.zero) def negate: HomogeneousPoint[A] = HomogeneousPoint[A](x, -y, z) - def double: HomogeneousPoint[A] = { + def double: HomogeneousPoint[A] = if (isZero) { this } else if (y === ZeroA) { @@ -107,8 +108,7 @@ final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: val z2 = eightTimesYsquaredTimesZ * y * zSquared HomogeneousPoint[A](x2, y2, z2) } - } - def add(p: HomogeneousPoint[A]): HomogeneousPoint[A] = { + def add(p: HomogeneousPoint[A]): HomogeneousPoint[A] = if (isZero) { p } else if (p.isZero) { @@ -116,8 +116,8 @@ final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: } else { p match { case HomogeneousPoint(x2, y2, z2) if x === x2 && y === -y2 && z === z2 => zeroPoint - case h @ HomogeneousPoint(_, _, _) if h === this => double - case HomogeneousPoint(x2, y2, z2) => + case h @ HomogeneousPoint(_, _, _) if h === this => double + case HomogeneousPoint(x2, y2, z2) => val yTimesZ2 = y * z2 val xTimesZ2 = x * z2 val x2TimesZ = x2 * z @@ -135,8 +135,7 @@ final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: HomogeneousPoint[A](x3, y3, z3) } } - } - def times(multiple: BigInt): HomogeneousPoint[A] = { + def times(multiple: BigInt): HomogeneousPoint[A] = if (isZero) { this } else if (y === ZeroA) { @@ -156,7 +155,6 @@ final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: result } } - } def toByteVector(implicit h: Hashable[A]): ByteVector = { val zInv = Field[A].one / z @@ -165,12 +163,11 @@ final case class HomogeneousPoint[A] private (x: A, y: A, z: A)(implicit aField: def isZero: Boolean = z == ZeroA - def normalize: Option[(A, A)] = { + def normalize: Option[(A, A)] = if (isZero) { None } else { val zInv = z.reciprocal Some((x * zInv, y * zInv)) } - } } diff --git a/src/main/scala/com/ironcorelabs/recrypt/package.scala b/src/main/scala/com/ironcorelabs/recrypt/package.scala index 1382c53..d27006d 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/package.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/package.scala @@ -20,7 +20,7 @@ package com.ironcorelabs import cats.effect.IO package object recrypt { - //Re export some of the types + // Re export some of the types type PrivateSigningKey = internal.PrivateSigningKey val PrivateSigningKey = internal.PrivateSigningKey diff --git a/src/main/scala/com/ironcorelabs/recrypt/syntax/hashable.scala b/src/main/scala/com/ironcorelabs/recrypt/syntax/hashable.scala index 7398c71..dc783cd 100644 --- a/src/main/scala/com/ironcorelabs/recrypt/syntax/hashable.scala +++ b/src/main/scala/com/ironcorelabs/recrypt/syntax/hashable.scala @@ -20,7 +20,7 @@ package syntax import scodec.bits.ByteVector -object hashable extends HashableSyntaxBase //scalastyle:ignore +object hashable extends HashableSyntaxBase trait HashableSyntaxBase { implicit class HashableSyntax[A](val a: A) { diff --git a/src/test/scala/com/ironcorelabs/recrypt/ApiTest.scala b/src/test/scala/com/ironcorelabs/recrypt/ApiTest.scala index ff0b9cf..eb23618 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/ApiTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/ApiTest.scala @@ -17,16 +17,16 @@ package com.ironcorelabs.recrypt -import scodec.bits._ import cats.effect.IO import cats.effect.unsafe.implicits.global +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import scodec.bits._ import spire.algebra.Field -import internal.Fp.implicits._ class ApiTest extends TestBase { import ApiTest._ private val randomIO = { - //Start with a known value, we'll just add one to it each time + // Start with a known value, we'll just add one to it each time var i = 100L val hashFunc = java.security.MessageDigest.getInstance("SHA-256").digest(_: Array[Byte]) IO { @@ -37,7 +37,7 @@ class ApiTest extends TestBase { val privateSigningKey = PrivateSigningKey.empty val publicSigningKey = PublicSigningKey.empty - //This is very clearly not a "correct" signature, but it does test that the message calculated on verify is correct. + // This is very clearly not a "correct" signature, but it does test that the message calculated on verify is correct. val api = new Api(randomIO, Ed25519Signing((_, bytes) => Signature(bytes), (_, message, sig) => message == sig.bytes)) "augmentPrivateKey" should { @@ -53,14 +53,14 @@ class ApiTest extends TestBase { "end to end encrypt/decrypt" should { "yield expected result using unaugmented keys" in { val io = for { - plaintext <- api.generatePlaintext + plaintext <- api.generatePlaintext masterKeys <- api.generateKeyPair (masterPrivate, masterPublic) = masterKeys deviceKeys <- api.generateKeyPair (devicePrivate, devicePublic) = deviceKeys - encryptedMessage <- api.encrypt(plaintext, masterPublic, publicSigningKey, privateSigningKey) + encryptedMessage <- api.encrypt(plaintext, masterPublic, publicSigningKey, privateSigningKey) masterToDeviceTransformKey <- api.generateTransformKey(masterPrivate, devicePublic, publicSigningKey, privateSigningKey) - transformedMessage <- api.transform(encryptedMessage, masterToDeviceTransformKey, publicSigningKey, privateSigningKey) + transformedMessage <- api.transform(encryptedMessage, masterToDeviceTransformKey, publicSigningKey, privateSigningKey) } yield plaintext -> api.decrypt(transformedMessage, devicePrivate) val (expectedResult, actualResult) = io.unsafeRunSync() actualResult.value shouldBe expectedResult @@ -68,24 +68,24 @@ class ApiTest extends TestBase { "yield expected result using augmented keys" in { val io = for { - plaintext <- api.generatePlaintext + plaintext <- api.generatePlaintext masterKeys <- api.generateKeyPair (masterPrivate, clientGeneratedPublic) = masterKeys deviceKeys <- api.generateKeyPair (devicePrivate, devicePublic) = deviceKeys - //These keys would be kept secret by a 2nd party, in this case the "server" + // These keys would be kept secret by a 2nd party, in this case the "server" serverKeys <- api.generateKeyPair (serverPrivate, serverPublic) = serverKeys - //the client sends `clientGeneratedPublic` to the server and the server will augment it. All - //future data will be encrypted to the augmented public. - masterPublic <- clientGeneratedPublic.augment(serverPublic).toIO + // the client sends `clientGeneratedPublic` to the server and the server will augment it. All + // future data will be encrypted to the augmented public. + masterPublic <- clientGeneratedPublic.augment(serverPublic).toIO encryptedMessage <- api.encrypt(plaintext, masterPublic, publicSigningKey, privateSigningKey) - //This is the transform key computed by the client. + // This is the transform key computed by the client. masterToDeviceTransformKey <- api.generateTransformKey(masterPrivate, devicePublic, publicSigningKey, privateSigningKey) - //2nd party will compute this, in our case the server. + // 2nd party will compute this, in our case the server. augmentedTransformKey <- masterToDeviceTransformKey.augment(serverPrivate).toIO - transformedMessage <- api.transform(encryptedMessage, augmentedTransformKey, publicSigningKey, privateSigningKey) - //Even though we augmented, this should work on the client per normal. + transformedMessage <- api.transform(encryptedMessage, augmentedTransformKey, publicSigningKey, privateSigningKey) + // Even though we augmented, this should work on the client per normal. } yield plaintext -> api.decrypt(transformedMessage, devicePrivate) val (expectedResult, actualResult) = io.unsafeRunSync() actualResult.value shouldBe expectedResult @@ -93,7 +93,7 @@ class ApiTest extends TestBase { "yield expected result using 2 levels of augmented keys" in { val io = for { - plaintext <- api.generatePlaintext + plaintext <- api.generatePlaintext masterKeys <- api.generateKeyPair (masterGroupPrivate, clientGeneratedGroupPublic) = masterKeys userKeys <- api.generateKeyPair @@ -104,16 +104,16 @@ class ApiTest extends TestBase { (serverGroupPrivate, serverGroupPublic) = groupServerKeys userServerKeys <- api.generateKeyPair (serverUserPrivate, serverUserPublic) = userServerKeys - //Augment the group and user keys (which would be done by the proxy server) - masterGroupPublic <- clientGeneratedGroupPublic.augment(serverGroupPublic).toIO - masterUserPublic <- clientGeneratedUserPublic.augment(serverUserPublic).toIO - groupToUserTransformKey <- api.generateTransformKey(masterGroupPrivate, masterUserPublic, publicSigningKey, privateSigningKey) - userToDeviceTransformKey <- api.generateTransformKey(masterUserPrivate, devicePublic, publicSigningKey, privateSigningKey) - augmentedGroupToUserTransform <- groupToUserTransformKey.augment(serverGroupPrivate).toIO + // Augment the group and user keys (which would be done by the proxy server) + masterGroupPublic <- clientGeneratedGroupPublic.augment(serverGroupPublic).toIO + masterUserPublic <- clientGeneratedUserPublic.augment(serverUserPublic).toIO + groupToUserTransformKey <- api.generateTransformKey(masterGroupPrivate, masterUserPublic, publicSigningKey, privateSigningKey) + userToDeviceTransformKey <- api.generateTransformKey(masterUserPrivate, devicePublic, publicSigningKey, privateSigningKey) + augmentedGroupToUserTransform <- groupToUserTransformKey.augment(serverGroupPrivate).toIO augmentedUserToDeviceTransform <- userToDeviceTransformKey.augment(serverUserPrivate).toIO - //Encrypt to the augmented key of the group. - encryptedMessage <- api.encrypt(plaintext, masterGroupPublic, publicSigningKey, privateSigningKey) - transformedToUserMessage <- api.transform(encryptedMessage, augmentedGroupToUserTransform, publicSigningKey, privateSigningKey) + // Encrypt to the augmented key of the group. + encryptedMessage <- api.encrypt(plaintext, masterGroupPublic, publicSigningKey, privateSigningKey) + transformedToUserMessage <- api.transform(encryptedMessage, augmentedGroupToUserTransform, publicSigningKey, privateSigningKey) transformedToDeviceMessage <- api.transform(transformedToUserMessage, augmentedUserToDeviceTransform, publicSigningKey, privateSigningKey) } yield plaintext -> api.decrypt(transformedToDeviceMessage, devicePrivate) val (expectedResult, actualResult) = io.unsafeRunSync() @@ -122,18 +122,18 @@ class ApiTest extends TestBase { "yield expected result using 2 levels" in { val io = for { - plaintext <- api.generatePlaintext + plaintext <- api.generatePlaintext masterKeys <- api.generateKeyPair (masterGroupPrivate, masterGroupPublic) = masterKeys userKeys <- api.generateKeyPair (masterUserPrivate, masterUserPublic) = userKeys deviceKeys <- api.generateKeyPair (devicePrivate, devicePublic) = deviceKeys - groupToUserTransformKey <- api.generateTransformKey(masterGroupPrivate, masterUserPublic, publicSigningKey, privateSigningKey) + groupToUserTransformKey <- api.generateTransformKey(masterGroupPrivate, masterUserPublic, publicSigningKey, privateSigningKey) userToDeviceTransformKey <- api.generateTransformKey(masterUserPrivate, devicePublic, publicSigningKey, privateSigningKey) - //Encrypt to the augmented key of the group. - encryptedMessage <- api.encrypt(plaintext, masterGroupPublic, publicSigningKey, privateSigningKey) - transformedToUserMessage <- api.transform(encryptedMessage, groupToUserTransformKey, publicSigningKey, privateSigningKey) + // Encrypt to the augmented key of the group. + encryptedMessage <- api.encrypt(plaintext, masterGroupPublic, publicSigningKey, privateSigningKey) + transformedToUserMessage <- api.transform(encryptedMessage, groupToUserTransformKey, publicSigningKey, privateSigningKey) transformedToDeviceMessage <- api.transform(transformedToUserMessage, userToDeviceTransformKey, publicSigningKey, privateSigningKey) } yield plaintext -> api.decrypt(transformedToDeviceMessage, devicePrivate) val (expectedResult, actualResult) = io.unsafeRunSync() @@ -142,12 +142,12 @@ class ApiTest extends TestBase { "work with transform to same key" in { val io = for { - plaintext <- api.generatePlaintext + plaintext <- api.generatePlaintext masterKeys <- api.generateKeyPair (masterPrivate, masterPublic) = masterKeys - encryptedMessage <- api.encrypt(plaintext, masterPublic, publicSigningKey, privateSigningKey) + encryptedMessage <- api.encrypt(plaintext, masterPublic, publicSigningKey, privateSigningKey) masterToMasterTransformKey <- api.generateTransformKey(masterPrivate, masterPublic, publicSigningKey, privateSigningKey) - transformedMessage <- api.transform(encryptedMessage, masterToMasterTransformKey, publicSigningKey, privateSigningKey) + transformedMessage <- api.transform(encryptedMessage, masterToMasterTransformKey, publicSigningKey, privateSigningKey) } yield plaintext -> api.decrypt(transformedMessage, masterPrivate) val (expectedResult, actualResult) = io.unsafeRunSync() actualResult.value shouldBe expectedResult @@ -155,15 +155,17 @@ class ApiTest extends TestBase { } "deriveSymmetricKey" should { - val plaintext = Plaintext(hex"0x28c0f558c02d983d7c652f16acbe91a566ac420fe02e41cf6d4f09a107f75cf76b6776ebb53365100ebeb7fa332995ae7bdddf0779fe79e1f43d5c51a73ced0a8cf5789804a79960ccf1a64bd55a923f4786d31ec06bf33e739254016d077b838e739f85586087e52ab659471df3904035e5e1f7ad6ac7b9f9dba6daf39e3f882b583e309c03e35ae7dfd4ed063b6c226bb3338627772e4c9a556fee7f3f96030ae1e265654fc322015a1c2d50eb273cd8b0e1e0353e6b09749343b5fe72ae2f302bebc527aca6ec465a95c4b41efe174eb5165993a30a922434a6f45cbafda201d6540bf2202c65751c90e4cd87e1b690997d9cd23474ef9ace4def3f17cbdd648c8545eaceb3f28c166f720fd8dd87b47523c55a52e32f8c1595a586763276411e8bd4400fac41234277cc560e919f76b21d757cda7c253078927e75482ee2759b222bf4fb070ab3032c9556a069d754efc3c0e63533311b29334108a5121a7e4018782324bf2c1517b6fe4df7a1bbb34c985c6d0796ff1e18ed80fd78d402") + val plaintext = Plaintext( + hex"0x28c0f558c02d983d7c652f16acbe91a566ac420fe02e41cf6d4f09a107f75cf76b6776ebb53365100ebeb7fa332995ae7bdddf0779fe79e1f43d5c51a73ced0a8cf5789804a79960ccf1a64bd55a923f4786d31ec06bf33e739254016d077b838e739f85586087e52ab659471df3904035e5e1f7ad6ac7b9f9dba6daf39e3f882b583e309c03e35ae7dfd4ed063b6c226bb3338627772e4c9a556fee7f3f96030ae1e265654fc322015a1c2d50eb273cd8b0e1e0353e6b09749343b5fe72ae2f302bebc527aca6ec465a95c4b41efe174eb5165993a30a922434a6f45cbafda201d6540bf2202c65751c90e4cd87e1b690997d9cd23474ef9ace4def3f17cbdd648c8545eaceb3f28c166f720fd8dd87b47523c55a52e32f8c1595a586763276411e8bd4400fac41234277cc560e919f76b21d757cda7c253078927e75482ee2759b222bf4fb070ab3032c9556a069d754efc3c0e63533311b29334108a5121a7e4018782324bf2c1517b6fe4df7a1bbb34c985c6d0796ff1e18ed80fd78d402" + ) "produce known value" in { - //If we're breaking this we better have versioned the api. + // If we're breaking this we better have versioned the api. api.deriveSymmetricKey(plaintext) shouldBe DecryptedSymmetricKey(hex"0x0e62a3e388cb0ca3279792353f7fcad75acf180d430a5c69e0a68be96520f454") } } "end to end Schnorr signing" should { - //We don't support this in general because we lose type safety. For tests we'll just allow it. + // We don't support this in general because we lose type safety. For tests we'll just allow it. implicit val hashableByteVector = Hashable.by[ByteVector](identity) val message = hex"deadbeef" "round-trip successfully" in { @@ -173,7 +175,7 @@ class ApiTest extends TestBase { serverKeys <- api.generateKeyPair (serverPrivate, serverPublic) = serverKeys masterPublic <- clientPublic.augment(serverPublic).toIO - signature <- api.schnorrSign(masterPrivate, masterPublic, message) + signature <- api.schnorrSign(masterPrivate, masterPublic, message) } yield api.schnorrVerify(masterPublic, serverPrivate, message, signature) io.unsafeRunSync() shouldBe true } @@ -184,7 +186,7 @@ class ApiTest extends TestBase { serverKeys <- api.generateKeyPair (serverPrivate, serverPublic) = serverKeys masterPublic <- clientPublic.augment(serverPublic).toIO - signature <- api.schnorrSign(masterPrivate, masterPublic, message) + signature <- api.schnorrSign(masterPrivate, masterPublic, message) } yield api.schnorrVerify(masterPublic, serverPrivate, hex"deadfeeb", signature) io.unsafeRunSync() shouldBe false } @@ -192,19 +194,33 @@ class ApiTest extends TestBase { "derivePrivateKey" should { import syntax.hashable._ - val plaintext = Plaintext(hex"0x28c0f558c02d983d7c652f16acbe91a566ac420fe02e41cf6d4f09a107f75cf76b6776ebb53365100ebeb7fa332995ae7bdddf0779fe79e1f43d5c51a73ced0a8cf5789804a79960ccf1a64bd55a923f4786d31ec06bf33e739254016d077b838e739f85586087e52ab659471df3904035e5e1f7ad6ac7b9f9dba6daf39e3f882b583e309c03e35ae7dfd4ed063b6c226bb3338627772e4c9a556fee7f3f96030ae1e265654fc322015a1c2d50eb273cd8b0e1e0353e6b09749343b5fe72ae2f302bebc527aca6ec465a95c4b41efe174eb5165993a30a922434a6f45cbafda201d6540bf2202c65751c90e4cd87e1b690997d9cd23474ef9ace4def3f17cbdd648c8545eaceb3f28c166f720fd8dd87b47523c55a52e32f8c1595a586763276411e8bd4400fac41234277cc560e919f76b21d757cda7c253078927e75482ee2759b222bf4fb070ab3032c9556a069d754efc3c0e63533311b29334108a5121a7e4018782324bf2c1517b6fe4df7a1bbb34c985c6d0796ff1e18ed80fd78d402") + val plaintext = Plaintext( + hex"0x28c0f558c02d983d7c652f16acbe91a566ac420fe02e41cf6d4f09a107f75cf76b6776ebb53365100ebeb7fa332995ae7bdddf0779fe79e1f43d5c51a73ced0a8cf5789804a79960ccf1a64bd55a923f4786d31ec06bf33e739254016d077b838e739f85586087e52ab659471df3904035e5e1f7ad6ac7b9f9dba6daf39e3f882b583e309c03e35ae7dfd4ed063b6c226bb3338627772e4c9a556fee7f3f96030ae1e265654fc322015a1c2d50eb273cd8b0e1e0353e6b09749343b5fe72ae2f302bebc527aca6ec465a95c4b41efe174eb5165993a30a922434a6f45cbafda201d6540bf2202c65751c90e4cd87e1b690997d9cd23474ef9ace4def3f17cbdd648c8545eaceb3f28c166f720fd8dd87b47523c55a52e32f8c1595a586763276411e8bd4400fac41234277cc560e919f76b21d757cda7c253078927e75482ee2759b222bf4fb070ab3032c9556a069d754efc3c0e63533311b29334108a5121a7e4018782324bf2c1517b6fe4df7a1bbb34c985c6d0796ff1e18ed80fd78d402" + ) "produce known value" in { - //If we're breaking this we better have versioned the api. - api.derivePrivateKey(plaintext) shouldBe PrivateKey(internal.Fp(BigInt("6506662011482432737221024072896425758901435651355026438261435484249092322388")).toHashBytes) + // If we're breaking this we better have versioned the api. + api.derivePrivateKey(plaintext) shouldBe PrivateKey( + internal.Fp(BigInt("6506662011482432737221024072896425758901435651355026438261435484249092322388")).toHashBytes + ) } } "transformKeyTransform" should { val transformKey = TransformKey( - PublicKey(hex"0x496929ec2914555bfd15c3313f01706505132d92d1cf72f41a7271902c7df443", hex"0x55c873a4de831450c3ea005557ffecdbbd11918a6c66830513860cd767dde192").value, - PublicKey(hex"0x628f84de59e7dbdd2c3064bb23a7769f5ac4e350dad330a816cbf2251506c6f7", hex"0x660557c7f5a3102a508a7488a6de2f13c635fff239d68e064e9218f0e3980ef2").value, - EncryptedElement(hex"0x3f0249c3c238ef3f7009d2eddf8737c0ff1020256a42cf4c1f5b728266af924d878fbe6caac0b9fcb5785bb262a69cff0f654a073c118100a5b70795ba5df9c62faeda574cdc5b00f8a750b84ff36ffea80f7a5bf7d408dd9a6f5163043c94c30eda58e30cbf738404455ecd018a4dde91a00b1c7adcca4d66f8c8609cc3ece853b011c91656d8927cca3497caac2dd790a51c9cb381371a4ba60202278a6c156f92764941362bd779f72296f545b7dfe0dcc76109906e141e2b2b927b77a6c96cc1c71d9367775c34711ade6a98650ea7efdcb1376fd70316a98126e5f8a0a814dac11961efe62c09c6bb0e6e10d8a1ff9f022aa81501bdb8c6e6afd2719862376eb2087241260033b5ee00e09da6c5ef99bc67c3b856f73fae7fb1f8b9e59625a4a69b1a36658ec728c4dbc6dd83007550bbe03dbcb9a8a474cb75dde0a4b58e43d5a15d85000cce2dca1232523d6eba70bd006ca690dce649908eaded30ae0f52b6ca0a73183e25947de43d8100200d4e6debb9a6409413753ae1f4faf8f1"), - HashedValue(hex"0x4a40fc771f0c5625d2ef6783013c52eece1697e71c6f82c3aa58396485c2a6c1713527192c3a7ed9103aca79a39f08a154723602bb768655fdd499f8062b461a5752395183b7743fb6ed688a856ef42aae259df29f52678ef0fccb91adb5374d10820c4e85917c4a1906cb06f537158c0556ecfaa55c874f388823ab9270a536").value, + PublicKey( + hex"0x496929ec2914555bfd15c3313f01706505132d92d1cf72f41a7271902c7df443", + hex"0x55c873a4de831450c3ea005557ffecdbbd11918a6c66830513860cd767dde192" + ).value, + PublicKey( + hex"0x628f84de59e7dbdd2c3064bb23a7769f5ac4e350dad330a816cbf2251506c6f7", + hex"0x660557c7f5a3102a508a7488a6de2f13c635fff239d68e064e9218f0e3980ef2" + ).value, + EncryptedElement( + hex"0x3f0249c3c238ef3f7009d2eddf8737c0ff1020256a42cf4c1f5b728266af924d878fbe6caac0b9fcb5785bb262a69cff0f654a073c118100a5b70795ba5df9c62faeda574cdc5b00f8a750b84ff36ffea80f7a5bf7d408dd9a6f5163043c94c30eda58e30cbf738404455ecd018a4dde91a00b1c7adcca4d66f8c8609cc3ece853b011c91656d8927cca3497caac2dd790a51c9cb381371a4ba60202278a6c156f92764941362bd779f72296f545b7dfe0dcc76109906e141e2b2b927b77a6c96cc1c71d9367775c34711ade6a98650ea7efdcb1376fd70316a98126e5f8a0a814dac11961efe62c09c6bb0e6e10d8a1ff9f022aa81501bdb8c6e6afd2719862376eb2087241260033b5ee00e09da6c5ef99bc67c3b856f73fae7fb1f8b9e59625a4a69b1a36658ec728c4dbc6dd83007550bbe03dbcb9a8a474cb75dde0a4b58e43d5a15d85000cce2dca1232523d6eba70bd006ca690dce649908eaded30ae0f52b6ca0a73183e25947de43d8100200d4e6debb9a6409413753ae1f4faf8f1" + ), + HashedValue( + hex"0x4a40fc771f0c5625d2ef6783013c52eece1697e71c6f82c3aa58396485c2a6c1713527192c3a7ed9103aca79a39f08a154723602bb768655fdd499f8062b461a5752395183b7743fb6ed688a856ef42aae259df29f52678ef0fccb91adb5374d10820c4e85917c4a1906cb06f537158c0556ecfaa55c874f388823ab9270a536" + ).value, publicSigningKey, Signature(hex"0xaaaaa") ) @@ -217,7 +233,9 @@ class ApiTest extends TestBase { "hashedValueTransform" should { "roundtrip" in { - val initialValue: HashedValue = HashedValue(hex"0x4a40fc771f0c5625d2ef6783013c52eece1697e71c6f82c3aa58396485c2a6c1713527192c3a7ed9103aca79a39f08a154723602bb768655fdd499f8062b461a5752395183b7743fb6ed688a856ef42aae259df29f52678ef0fccb91adb5374d10820c4e85917c4a1906cb06f537158c0556ecfaa55c874f388823ab9270a536").value + val initialValue: HashedValue = HashedValue( + hex"0x4a40fc771f0c5625d2ef6783013c52eece1697e71c6f82c3aa58396485c2a6c1713527192c3a7ed9103aca79a39f08a154723602bb768655fdd499f8062b461a5752395183b7743fb6ed688a856ef42aae259df29f52678ef0fccb91adb5374d10820c4e85917c4a1906cb06f537158c0556ecfaa55c874f388823ab9270a536" + ).value val internal = CoreApi.hashedValueTransform(initialValue).value val result = CoreApi.hashedValueTransform(internal) result.value shouldBe initialValue @@ -226,7 +244,10 @@ class ApiTest extends TestBase { "publicKeyTransform" should { "roundtrip" in { - val publicKey = PublicKey(hex"0x496929ec2914555bfd15c3313f01706505132d92d1cf72f41a7271902c7df443", hex"0x55c873a4de831450c3ea005557ffecdbbd11918a6c66830513860cd767dde192").value + val publicKey = PublicKey( + hex"0x496929ec2914555bfd15c3313f01706505132d92d1cf72f41a7271902c7df443", + hex"0x55c873a4de831450c3ea005557ffecdbbd11918a6c66830513860cd767dde192" + ).value val internal = CoreApi.publicKeyTransform(publicKey) val result = CoreApi.publicKeyTransform(internal).value result shouldBe publicKey @@ -234,30 +255,28 @@ class ApiTest extends TestBase { } "generateGTElem" should { - "always produce an rth root" in { + "always produce an rth root" in 1.to(100).foreach { _ => val gTElem = api.generateGTElem.unsafeRunSync() val rthPow = gTElem ^ internal.Fp.Order rthPow shouldBe Field[internal.FP12Elem[internal.Fp]].one } - } } "generatePlaintext" should { val fp12One = Field[internal.FP12Elem[internal.Fp]].one - "always produce an rth root" in { + "always produce an rth root" in 1.to(20).foreach { _ => val plaintext = api.generatePlaintext.unsafeRunSync() val fp12 = CoreApi.plaintextTransform(plaintext).getOrElse(fp12One) val rthPow = fp12 ^ internal.Fp.Order rthPow shouldBe fp12One } - } } } object ApiTest { - //Hacky syntax to allow us to throw the messages if we want (in the tests). + // Hacky syntax to allow us to throw the messages if we want (in the tests). implicit class EitherApiErrorSyntax[A](val either: Either[ApiError, A]) { def toIO: IO[A] = either.fold(message => IO.raiseError(new Exception(message.toString)), IO.pure) } diff --git a/src/test/scala/com/ironcorelabs/recrypt/TestBase.scala b/src/test/scala/com/ironcorelabs/recrypt/TestBase.scala index 85177ef..e05a9ac 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/TestBase.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/TestBase.scala @@ -17,17 +17,9 @@ package com.ironcorelabs.recrypt -import org.scalatest.{ BeforeAndAfterAll, OptionValues } -import cats.scalatest.EitherValues -import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec +import org.scalatest.{BeforeAndAfterAll, EitherValues, OptionValues} +import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks -abstract class TestBase - extends AnyWordSpec - with Matchers - with OptionValues - with BeforeAndAfterAll - with ScalaCheckDrivenPropertyChecks - with EitherValues { -} +abstract class TestBase extends AnyWordSpec with Matchers with OptionValues with BeforeAndAfterAll with ScalaCheckDrivenPropertyChecks with EitherValues {} diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/Arbitraries.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/Arbitraries.scala index 9a76929..d331098 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/Arbitraries.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/Arbitraries.scala @@ -17,20 +17,29 @@ package com.ironcorelabs.recrypt.internal -import point.HomogeneousPoint -import org.scalacheck.{ Arbitrary, Gen } +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import org.scalacheck.{Arbitrary, Gen} import spire.algebra.Field object Arbitraries { - ///This is the scalacheck generator, but with no 0s. + /// This is the scalacheck generator, but with no 0s. val nonZeroBigInt: Gen[BigInt] = { val long: Gen[Long] = Gen.choose(Long.MinValue, Long.MaxValue).map(x => if (x == 0) 1L else x) val gen1: Gen[BigInt] = for { x <- long } yield BigInt(x) - val gen2: Gen[BigInt] = for { x <- gen1; y <- long } yield x * y - val gen3: Gen[BigInt] = for { x <- gen2; y <- long } yield x * y - val gen4: Gen[BigInt] = for { x <- gen3; y <- long } yield x * y + val gen2: Gen[BigInt] = for { + x <- gen1 + y <- long + } yield x * y + val gen3: Gen[BigInt] = for { + x <- gen2 + y <- long + } yield x * y + val gen4: Gen[BigInt] = for { + x <- gen3 + y <- long + } yield x * y val gen0: Gen[BigInt] = Gen.oneOf( @@ -41,7 +50,8 @@ object Arbitraries { BigInt(Long.MaxValue), BigInt(Long.MinValue), BigInt(Long.MaxValue) + 1, - BigInt(Long.MinValue) - 1) + BigInt(Long.MinValue) - 1 + ) Gen.frequency((5, gen0), (5, gen1), (4, gen2), (3, gen3), (2, gen4)) } @@ -57,8 +67,8 @@ object Arbitraries { implicit def fp2Arb[A <: BigInt: ModsByPrime: Gen]: Arbitrary[FP2Elem[A]] = Arbitrary(fp2Gen[A]) implicit def fp6Gen[A <: BigInt: ModsByPrime](implicit genFp2A: Gen[FP2Elem[A]]): Gen[FP6Elem[A]] = for { - one <- genFp2A - two <- genFp2A + one <- genFp2A + two <- genFp2A three <- genFp2A } yield FP6Elem(one, two, three) @@ -67,13 +77,15 @@ object Arbitraries { two <- genFp6A } yield FP12Elem(one, two)) - //Legal Points are ones that satisfy the equation y^2 = x^3 + 3. - //Generate them by just multiplying the generator point. + // Legal Points are ones that satisfy the equation y^2 = x^3 + 3. + // Generate them by just multiplying the generator point. implicit val homogeneousPointArbFp: Arbitrary[HomogeneousPoint[Fp]] = Arbitrary[HomogeneousPoint[Fp]](nonZeroFpGen.map(Fp.curvePoints.generator.times(_))) - implicit val homogeneousPointArbFp480: Arbitrary[HomogeneousPoint[Fp480]] = Arbitrary[HomogeneousPoint[Fp480]](nonZeroFp480Gen.map(Fp480.curvePoints.generator.times(_))) + implicit val homogeneousPointArbFp480: Arbitrary[HomogeneousPoint[Fp480]] = + Arbitrary[HomogeneousPoint[Fp480]](nonZeroFp480Gen.map(Fp480.curvePoints.generator.times(_))) implicit val homogeneousPointArb: Arbitrary[HomogeneousPoint[FP2Elem[Fp]]] = Arbitrary[HomogeneousPoint[FP2Elem[Fp]]](fpGen.map(Fp.curvePoints.g1.times(_))) - implicit val homogeneousPointArbFP2Elem480: Arbitrary[HomogeneousPoint[FP2Elem[Fp480]]] = Arbitrary[HomogeneousPoint[FP2Elem[Fp480]]](fp480Gen.map(Fp480.curvePoints.g1.times(_))) + implicit val homogeneousPointArbFP2Elem480: Arbitrary[HomogeneousPoint[FP2Elem[Fp480]]] = + Arbitrary[HomogeneousPoint[FP2Elem[Fp480]]](fp480Gen.map(Fp480.curvePoints.g1.times(_))) implicit val arbPrivateKey: Arbitrary[PrivateKey[Fp]] = Arbitrary[PrivateKey[Fp]](nonZeroFpGen.map(PrivateKey(_))) diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/EncryptedValueTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/EncryptedValueTest.scala index 0d39e99..aa08ab1 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/EncryptedValueTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/EncryptedValueTest.scala @@ -17,9 +17,9 @@ package com.ironcorelabs.recrypt.internal import cats.data.NonEmptyVector -import scodec.bits._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ import com.ironcorelabs.recrypt.syntax.hashable._ -import Fp.implicits._ +import scodec.bits._ class EncryptedValueTest extends com.ironcorelabs.recrypt.TestBase { val keyGen = Fp.curvePoints.publicKeyGen @@ -38,9 +38,11 @@ class EncryptedValueTest extends com.ironcorelabs.recrypt.TestBase { } "ReencryptedValue authHash is included in toHashBytes" in { - val eov1: EncryptedValue[Fp] = ReencryptedValue(publicKey, plaintext, AuthHash(hex"00ff00ff"), NonEmptyVector(ReencryptionBlock(publicKey, plaintext, publicKey, plaintext), Vector())) + val eov1: EncryptedValue[Fp] = + ReencryptedValue(publicKey, plaintext, AuthHash(hex"00ff00ff"), NonEmptyVector(ReencryptionBlock(publicKey, plaintext, publicKey, plaintext), Vector())) val hash1 = eov1.toHashBytes - val eov2: EncryptedValue[Fp] = ReencryptedValue(publicKey, plaintext, AuthHash(hex"00ff00fe"), NonEmptyVector(ReencryptionBlock(publicKey, plaintext, publicKey, plaintext), Vector())) + val eov2: EncryptedValue[Fp] = + ReencryptedValue(publicKey, plaintext, AuthHash(hex"00ff00fe"), NonEmptyVector(ReencryptionBlock(publicKey, plaintext, publicKey, plaintext), Vector())) val hash2 = eov2.toHashBytes hash1 shouldNot be(hash2) diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/FP12ElemTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/FP12ElemTest.scala index 5c2d99b..be9f985 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/FP12ElemTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/FP12ElemTest.scala @@ -17,11 +17,11 @@ package com.ironcorelabs.recrypt.internal +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp480.implicits._ +import com.ironcorelabs.recrypt.syntax.hashable._ import scodec.bits._ import spire.algebra.Field -import Fp.implicits._ -import Fp480.implicits._ -import com.ironcorelabs.recrypt.syntax.hashable._ class FP12ElemTest extends com.ironcorelabs.recrypt.TestBase { import Arbitraries._ @@ -31,61 +31,59 @@ class FP12ElemTest extends com.ironcorelabs.recrypt.TestBase { "square" should { "be the same as ^2" in { - forAll { (one: FP12Elem[Fp]) => one.square shouldBe one ^ 2 } - forAll { (one: FP12Elem[Fp]) => one.square.square shouldBe one ^ 4 } - forAll { (one: FP12Elem[Fp]) => one.square.square.square shouldBe one ^ 8 } + forAll((one: FP12Elem[Fp]) => one.square shouldBe one ^ 2) + forAll((one: FP12Elem[Fp]) => one.square.square shouldBe one ^ 4) + forAll((one: FP12Elem[Fp]) => one.square.square.square shouldBe one ^ 8) } - "be the same as times self" in { - forAll { (one: FP12Elem[Fp]) => one.square shouldBe one * one } - } + "be the same as times self" in + forAll((one: FP12Elem[Fp]) => one.square shouldBe one * one) } "hashable" should { "always roundtrip with BytesDecoder" in { - forAll { (one: FP12Elem[Fp]) => FP12Elem.byteDecoderFP12Elem[Fp].decode(one.toHashBytes).value shouldBe one } - forAll { (one: FP12Elem[Fp480]) => FP12Elem.byteDecoderFP12Elem[Fp480].decode(one.toHashBytes).value shouldBe one } + forAll((one: FP12Elem[Fp]) => FP12Elem.byteDecoderFP12Elem[Fp].decode(one.toHashBytes).value shouldBe one) + forAll((one: FP12Elem[Fp480]) => FP12Elem.byteDecoderFP12Elem[Fp480].decode(one.toHashBytes).value shouldBe one) } } "inverse" should { - "end up in one when times itself" in { + "end up in one when times itself" in forAll { (one: FP12Elem[Fp]) => whenever(one != fp12Zero) { one.inverse * one shouldBe fp12One } } - } } "x - y" should { - "be the same as x + y * (-1) " in { + "be the same as x + y * (-1) " in forAll { (one: FP12Elem[Fp], two: FP12Elem[Fp]) => - val expected = (one - two) - val result = one + (two * (Field[FP2Elem[Fp]].one * (-1))) + val expected = one - two + val result = one + (two * (Field[FP2Elem[Fp]].one * -1)) result shouldBe expected } - } } "x ^ (z + zz)" should { - "be the same as x ^z * x ^zz for Fp" in { + "be the same as x ^z * x ^zz for Fp" in forAll { (fp2: FP12Elem[Fp], iRaw: BigInt, jRaw: BigInt) => val (i, j) = (iRaw.abs, jRaw.abs) (fp2 ^ i) * (fp2 ^ j) shouldBe fp2 ^ (i + j) } - } - "be the same as x ^z * x ^zz for Fp480" in { + "be the same as x ^z * x ^zz for Fp480" in forAll { (fp2: FP12Elem[Fp480], iRaw: BigInt, jRaw: BigInt) => val (i, j) = (iRaw.abs, jRaw.abs) (fp2 ^ i) * (fp2 ^ j) shouldBe fp2 ^ (i + j) } - } } "hashable" should { "be known value" in { val fp6 = FP6Elem.create(Fp(100), Fp(200), Fp(300), Fp(400), Fp(500), Fp(600)) - FP12Elem[Fp](fp6, fp6).toHashBytes shouldBe hex"0x000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000c8000000000000000000000000000000000000000000000000000000000000012c000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000258000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000c8000000000000000000000000000000000000000000000000000000000000012c000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000258" + FP12Elem[Fp]( + fp6, + fp6 + ).toHashBytes shouldBe hex"0x000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000c8000000000000000000000000000000000000000000000000000000000000012c000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000258000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000c8000000000000000000000000000000000000000000000000000000000000012c000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000258" } } "create" should { diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/FP2ElemTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/FP2ElemTest.scala index 000b41f..aafb8b2 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/FP2ElemTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/FP2ElemTest.scala @@ -16,10 +16,10 @@ */ package com.ironcorelabs.recrypt.internal -import Fp.implicits._ -import Fp480.implicits._ -import spire.algebra.Field +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp480.implicits._ import com.ironcorelabs.recrypt.syntax.hashable._ +import spire.algebra.Field class FP2ElemTest extends com.ironcorelabs.recrypt.TestBase { import Arbitraries._ @@ -29,52 +29,49 @@ class FP2ElemTest extends com.ironcorelabs.recrypt.TestBase { val fp2One = Field[FP2Elem[Fp]].one "square" should { "be the same as ^2" in { - forAll { (one: FP2Elem[Fp]) => one.square shouldBe one ^ 2 } - forAll { (one: FP2Elem[Fp480]) => one.square shouldBe one ^ 2 } - forAll { (one: FP2Elem[Fp]) => one.square.square shouldBe one ^ 4 } - forAll { (one: FP2Elem[Fp]) => one.square.square.square shouldBe one ^ 8 } - forAll { (one: FP2Elem[Fp480]) => one.square.square.square shouldBe one ^ 8 } + forAll((one: FP2Elem[Fp]) => one.square shouldBe one ^ 2) + forAll((one: FP2Elem[Fp480]) => one.square shouldBe one ^ 2) + forAll((one: FP2Elem[Fp]) => one.square.square shouldBe one ^ 4) + forAll((one: FP2Elem[Fp]) => one.square.square.square shouldBe one ^ 8) + forAll((one: FP2Elem[Fp480]) => one.square.square.square shouldBe one ^ 8) } "be the same as times self" in { - forAll { (one: FP2Elem[Fp]) => one.square shouldBe one * one } - forAll { (one: FP2Elem[Fp480]) => one.square shouldBe one * one } + forAll((one: FP2Elem[Fp]) => one.square shouldBe one * one) + forAll((one: FP2Elem[Fp480]) => one.square shouldBe one * one) } } "toByteVector" should { "always roundtrip with fromByteVector" in { - forAll { (one: FP2Elem[Fp]) => FP2Elem.byteDecoderFP2Elem[Fp].decode(one.toHashBytes).value shouldBe one } - forAll { (one: FP12Elem[Fp480]) => FP12Elem.byteDecoderFP12Elem[Fp480].decode(one.toHashBytes).value shouldBe one } + forAll((one: FP2Elem[Fp]) => FP2Elem.byteDecoderFP2Elem[Fp].decode(one.toHashBytes).value shouldBe one) + forAll((one: FP12Elem[Fp480]) => FP12Elem.byteDecoderFP12Elem[Fp480].decode(one.toHashBytes).value shouldBe one) } } "inverse" should { - "end up in one when times itself" in { + "end up in one when times itself" in forAll { (one: FP2Elem[Fp]) => whenever(one != fp2Zero) { one.inverse * one shouldBe fp2One } } - } } "x - y" should { - "be the same as x + y * (-1) " in { + "be the same as x + y * (-1) " in forAll { (one: FP2Elem[Fp], two: FP2Elem[Fp]) => val expected = one - two - val result = one + (two * (-1)) + val result = one + (two * -1) result shouldBe expected } - } } "x ^ (z + zz)" should { - "be the same as x ^z * x ^zz" in { + "be the same as x ^z * x ^zz" in forAll { (fp2: FP2Elem[Fp], iRaw: BigInt, jRaw: BigInt) => val (i, j) = (iRaw.abs, jRaw.abs) (fp2 ^ i) * (fp2 ^ j) shouldBe fp2 ^ (i + j) } - } } } diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/FieldLawTests.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/FieldLawTests.scala index 5d6944b..3348d41 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/FieldLawTests.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/FieldLawTests.scala @@ -17,18 +17,18 @@ package com.ironcorelabs.recrypt.internal -import point.HomogeneousPoint -import org.typelevel.discipline.Predicate +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp480.implicits._ +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint import org.scalacheck.Arbitrary -import spire.laws.RingLaws -import Fp.implicits._ -import Fp480.implicits._ -import org.typelevel.discipline.scalatest.FunSuiteDiscipline import org.scalatest.funsuite.AnyFunSuite +import org.typelevel.discipline.Predicate +import org.typelevel.discipline.scalatest.FunSuiteDiscipline +import spire.laws.RingLaws class FieldLawTests extends AnyFunSuite with org.scalatest.prop.Configuration with FunSuiteDiscipline { import Arbitraries._ - //Additive laws permit all elements. + // Additive laws permit all elements. implicit def pred[A]: Predicate[A] = Predicate.const(true) implicit def fp6Arb: Arbitrary[FP6Elem[Fp]] = Arbitrary(fp6Gen[Fp]) implicit val fp480Arb: Arbitrary[Fp480] = Arbitrary(nonZeroFp480Gen) @@ -40,7 +40,7 @@ class FieldLawTests extends AnyFunSuite with org.scalatest.prop.Configuration wi checkAll("FP6Elem256", RingLaws[FP6Elem[Fp]].field) checkAll("FP12Elem256", RingLaws[FP12Elem[Fp]].field) checkAll("HomogeneousPoint256", RingLaws[HomogeneousPoint[Fp]].additiveGroup) - //Tests on the field instance for Fp480 + // Tests on the field instance for Fp480 checkAll("Fp480", RingLaws[Fp480].field) checkAll("FP2Elem480", RingLaws[FP2Elem[Fp480]].field) checkAll("FP6Elem480", RingLaws[FP6Elem[Fp480]].field) diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/FpTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/FpTest.scala index 290577f..bf63cc4 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/FpTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/FpTest.scala @@ -17,14 +17,14 @@ package com.ironcorelabs.recrypt.internal -import Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ import org.scalacheck.Arbitrary -import spire.implicits._ import scodec.bits.BitVector +import spire.implicits._ class FpTest extends com.ironcorelabs.recrypt.TestBase { import Arbitraries._ - //Things in here are fundemental operations so tehy should work even for 0 + // Things in here are fundemental operations so tehy should work even for 0 implicit val fpArb: Arbitrary[Fp] = Arbitrary(fpGen) "Fp.apply" should { @@ -36,33 +36,30 @@ class FpTest extends com.ironcorelabs.recrypt.TestBase { } "Fp.negate" should { - "Always be in Fp" in { + "Always be in Fp" in forAll { (fp: Fp) => val negateResult = spire.algebra.Field[Fp].negate(fp) negateResult shouldBe Fp(negateResult) } - } } "Fp.fastModPrime" should { - "work for elements greater than 2 * Prime" in { + "work for elements greater than 2 * Prime" in forAll { (fp: Fp) => - val bigIntFp: BigInt = fp //100% sure that it will be widened to the big int before + + val bigIntFp: BigInt = fp // 100% sure that it will be widened to the big int before + val biggerThanPrime = bigIntFp + Fp.Prime * 5 val fastModResult = Fp.fastModPrime(biggerThanPrime) fastModResult shouldBe fp fastModResult shouldBe positiveMod(biggerThanPrime, Fp.Prime) } - } - "work for all numbers" in { + "work for all numbers" in forAll { (b: BigInt) => Fp.fastModPrime(b) shouldBe Fp(b) } - } } "Fp.reciprocal" should { - "Always be 1 in *" in { + "Always be 1 in *" in forAll { (fp: Fp) => if (fp != Fp.Zero) { Fp(fp.reciprocal * fp) shouldBe Fp.One @@ -70,7 +67,6 @@ class FpTest extends com.ironcorelabs.recrypt.TestBase { fp.reciprocal shouldBe Fp.Zero } } - } } "Fp.ModsByPrime.create" should { diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/HashableTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/HashableTest.scala index 46a45e8..a7389fa 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/HashableTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/HashableTest.scala @@ -17,9 +17,9 @@ package com.ironcorelabs.recrypt.internal -import scodec.bits._ import cats.data.NonEmptyVector import com.ironcorelabs.recrypt.syntax.hashable._ +import scodec.bits._ class HashableTest extends com.ironcorelabs.recrypt.TestBase { "NonEmptyVector" should { diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/InternalApiTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/InternalApiTest.scala index a1be9e5..1c1289c 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/InternalApiTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/InternalApiTest.scala @@ -21,13 +21,13 @@ import cats.effect.unsafe.implicits.global import cats.instances.list._ import cats.syntax.traverse._ import com.ironcorelabs.recrypt.internal.Arbitraries._ -import com.ironcorelabs.recrypt.syntax.hashable._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Fp480.implicits._ import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint +import com.ironcorelabs.recrypt.syntax.hashable._ import org.scalacheck.Arbitrary import scodec.bits._ import spire.algebra.Field -import Fp.implicits._ -import Fp480.implicits._ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { import InternalApiTest._ @@ -39,12 +39,12 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { val privateSigningKey = PrivateSigningKey.empty val publicSigningKey = PublicSigningKey.empty val sha256Hash = Sha256Hash(com.ironcorelabs.recrypt.Sha256) - //All Fps in this file should be non-zero. + // All Fps in this file should be non-zero. implicit val fpArb: Arbitrary[Fp] = Arbitrary(nonZeroFpGen) implicit val fp480Arb: Arbitrary[Fp480] = Arbitrary(nonZeroFp480Gen) private val randomBytesIO: IO[ByteVector] = { - //Start with a known value, we'll just add one to it each time + // Start with a known value, we'll just add one to it each time var i = 100L val hashFunc = java.security.MessageDigest.getInstance("SHA-256").digest(_: Array[Byte]) IO { @@ -64,13 +64,22 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { def genReencryptionKey(fromPrivate: PrivateKey[Fp], toPublicKey: PublicKey[Fp]) = for { reencryptionPrivate <- Arbitrary.arbitrary[PrivateKey[Fp]] - salt <- Arbitrary.arbitrary[FP12Elem[Fp]] + salt <- Arbitrary.arbitrary[FP12Elem[Fp]] } yield encryptInstance.generateReencryptionKey(fromPrivate, toPublicKey, reencryptionPrivate, salt, PublicSigningKey.empty, PrivateSigningKey.empty) val goodHomogeneousPoint = HomogeneousPoint[FP2Elem[Fp]]( - FP2Elem(Fp(BigInt("39898887170429929807040143276261848585078991568615066857293752634765338134660")), Fp(BigInt("4145079839513126747718408015399244712098849008922890496895080944648891367549"))), - FP2Elem(Fp(BigInt("54517427188233403272140512636254575372766895942651963572804557077716421872651")), Fp(BigInt("29928198841033477396304275898313889635561368630804063259494165651195801046334"))), - FP2Elem(Fp(BigInt("25757029117904574834370194644693146689936696995375576562303493881177613755324")), Fp(BigInt("20317563273514500379895253969863230147776170908243485486513578790623697384796"))) + FP2Elem( + Fp(BigInt("39898887170429929807040143276261848585078991568615066857293752634765338134660")), + Fp(BigInt("4145079839513126747718408015399244712098849008922890496895080944648891367549")) + ), + FP2Elem( + Fp(BigInt("54517427188233403272140512636254575372766895942651963572804557077716421872651")), + Fp(BigInt("29928198841033477396304275898313889635561368630804063259494165651195801046334")) + ), + FP2Elem( + Fp(BigInt("25757029117904574834370194644693146689936696995375576562303493881177613755324")), + Fp(BigInt("20317563273514500379895253969863230147776170908243485486513578790623697384796")) + ) ) "generateRthRoot" should { @@ -96,13 +105,23 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { ) val result = encryptInstance.generateRthRoot( FP12Elem.create( - Fp(BigInt(1)), Fp(BigInt(2)), Fp(BigInt(3)), Fp(BigInt(4)), Fp(BigInt(5)), Fp(BigInt(6)), - Fp(BigInt(7)), Fp(BigInt(8)), Fp(BigInt(9)), Fp(BigInt(10)), Fp(BigInt(11)), Fp(BigInt(12)) + Fp(BigInt(1)), + Fp(BigInt(2)), + Fp(BigInt(3)), + Fp(BigInt(4)), + Fp(BigInt(5)), + Fp(BigInt(6)), + Fp(BigInt(7)), + Fp(BigInt(8)), + Fp(BigInt(9)), + Fp(BigInt(10)), + Fp(BigInt(11)), + Fp(BigInt(12)) ) ) result shouldBe expectedGoodResult } - "always produce an rth root" in { + "always produce an rth root" in forAll(Arbitrary.arbitrary[FP12Elem[Fp]]) { fp12 => whenever(fp12 != Field[FP12Elem[Fp]].zero) { val rthRoot = encryptInstance.generateRthRoot(fp12) @@ -110,34 +129,48 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { rthPow shouldBe Field[FP12Elem[Fp]].one } } - } } "addLineEval" should { "match known value" in { val expectedGoodResult = FP12Elem.create( - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt("10225613897589023975141864306784331698114333350322193013849355029116866989558")), Fp(BigInt("23874417408544625227955020078213054360178217578435813388951341839988775845640")), - Fp(BigInt("19583696538442210257421816149687930861898894457540838395018829873613832108851")), Fp(BigInt("22526875801371184821181570246816236576448644880717020355432045498197577562711")), - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt("51350284864274176077585216690595295345910970011195603140224124332586682398734")), Fp(BigInt("9195404449948098526566482694993850148148550213325878247570491211174099400997")) - ) -> FP2Elem(Fp(BigInt("25675142432137088038792608345297647672955485005597801570112062166293341199367")), Fp(BigInt("37097977072797351129681460718676877945486954160474440909723818119019141736390"))) + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt("10225613897589023975141864306784331698114333350322193013849355029116866989558")), + Fp(BigInt("23874417408544625227955020078213054360178217578435813388951341839988775845640")), + Fp(BigInt("19583696538442210257421816149687930861898894457540838395018829873613832108851")), + Fp(BigInt("22526875801371184821181570246816236576448644880717020355432045498197577562711")), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt("51350284864274176077585216690595295345910970011195603140224124332586682398734")), + Fp(BigInt("9195404449948098526566482694993850148148550213325878247570491211174099400997")) + ) -> FP2Elem( + Fp(BigInt("25675142432137088038792608345297647672955485005597801570112062166293341199367")), + Fp(BigInt("37097977072797351129681460718676877945486954160474440909723818119019141736390")) + ) val result = encryptInstance.pairing.addLineEval(basePointX, basePointY, goodHomogeneousPoint, goodHomogeneousPoint.double) result shouldBe expectedGoodResult } "match 2nd known value" in { val expectedGoodResult = FP12Elem.create( - Fp(BigInt(0)), Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), Fp(BigInt("55744800738974830414511837562097001444513814113731905690103202632714685000112")), Fp(BigInt("5931115851264405664176255926844469633299602620131317110698302035851504058485")), Fp(BigInt("5922043367691349962919743457016954000050519680657775073386104333409065506275")), Fp(BigInt("20288974314653081232608663556936861878151531295868263204413435854177100288352")), - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt(0)), Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), Fp(BigInt("26356633409924402912277270815241187276017192428798815740104200671052283049228")), Fp(BigInt("15795322029202928214286645072236506167028617449376846994561520041437363044626")) - ) -> FP2Elem(Fp(BigInt("45317051037626942699433282368426742998780524510558790284447501032407331744487")), Fp(BigInt("57314508651404382971317523526158597484748409902108919167661676452517534974217"))) + ) -> FP2Elem( + Fp(BigInt("45317051037626942699433282368426742998780524510558790284447501032407331744487")), + Fp(BigInt("57314508651404382971317523526158597484748409902108919167661676452517534974217")) + ) val (pointX, pointY) = basePoint.double.double.normalize.value val result = encryptInstance.pairing.addLineEval(pointX, pointY, goodHomogeneousPoint.double, goodHomogeneousPoint.double.double) result shouldBe expectedGoodResult @@ -147,15 +180,22 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { "doubleLineEval" should { "match known value" in { val expectedGoodResult = FP12Elem.create( - Fp(BigInt(0)), Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), Fp(BigInt("17712485624843220480183304963635457557059227558921981718335334461785067564761")), Fp(BigInt("60062497247414669535857527984449046910652829387114413501954200738470746113195")), Fp(BigInt("22388663537106305339863882629391283032654826869605943340705330045870326159547")), Fp(BigInt("53713945989969989737781120925512388913929867004299271526634203788037019854146")), - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt(0)), Fp(BigInt(0)), - Fp(BigInt("20917605796411899317217008737010033956820097935526175686366958730322466630407")), Fp(BigInt("56032303778290759243918533214786117372540626820242016384835510414304520082514")) - ) -> FP2Elem(Fp(BigInt("42959077746029251525006723739684969849822728021574589629122051878593325351095")), Fp(BigInt("28016151889145379621959266607393058686270313410121008192417755207152260041257"))) + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt(0)), + Fp(BigInt("20917605796411899317217008737010033956820097935526175686366958730322466630407")), + Fp(BigInt("56032303778290759243918533214786117372540626820242016384835510414304520082514")) + ) -> FP2Elem( + Fp(BigInt("42959077746029251525006723739684969849822728021574589629122051878593325351095")), + Fp(BigInt("28016151889145379621959266607393058686270313410121008192417755207152260041257")) + ) val result = encryptInstance.pairing.doubleLineEval(basePointX, basePointY, goodHomogeneousPoint) result shouldBe expectedGoodResult } @@ -180,22 +220,21 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { encryptInstance.pairing.pair(basePoint, goodHomogeneousPoint) shouldBe expectedGoodResult } - "follow the law pair(a * P, a * Q) == pair(a^2 * P, Q) == pair(P,a^2 * Q)" in { - forAll { a: BigInt => + "follow the law pair(a * P, a * Q) == pair(a^2 * P, Q) == pair(P,a^2 * Q)" in + forAll { (a: BigInt) => whenever(a != 0) { val baseResult = encryptInstance.pairing.pair(basePoint.times(a), goodHomogeneousPoint.times(a)) baseResult shouldBe encryptInstance.pairing.pair(basePoint.times(a.pow(2)), goodHomogeneousPoint) baseResult shouldBe encryptInstance.pairing.pair(basePoint, goodHomogeneousPoint.times(a.pow(2))) } } - } - "follow the law pair(a * P, a * Q) == pair(P, Q) ^ (a^2)" in { - forAll { a: BigInt => + "follow the law pair(a * P, a * Q) == pair(P, Q) ^ (a^2)" in + forAll { (a: BigInt) => whenever(a != 0) { - encryptInstance.pairing.pair(basePoint.times(a), goodHomogeneousPoint.times(a)) shouldBe encryptInstance.pairing.pair(basePoint, goodHomogeneousPoint) ^ (a.pow(2)) + encryptInstance.pairing + .pair(basePoint.times(a), goodHomogeneousPoint.times(a)) shouldBe encryptInstance.pairing.pair(basePoint, goodHomogeneousPoint) ^ (a.pow(2)) } } - } } "PrivateKey +" should { @@ -225,14 +264,13 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { encryptResult.payload.authHash shouldBe AuthHash.create(sha256Hash, encryptResult.payload.ephemeralPublicKey, plaintext) } - "round trip with decrypt using Fp" in { + "round trip with decrypt using Fp" in forAll { (plaintext: FP12Elem[Fp], privateKey: PrivateKey[Fp], ephemeralPrivateKey: PrivateKey[Fp]) => val publicKey = keyGen(privateKey) val encryptResult = encryptInstance.encrypt(publicKey, plaintext, ephemeralPrivateKey, publicSigningKey, privateSigningKey) val decryptResult = encryptInstance.decrypt(privateKey, encryptResult).value decryptResult shouldBe plaintext } - } "round trip with decrypt using Fp480" in { val internalApi480 = createInternalApi480WithoutSigning(com.ironcorelabs.recrypt.Sha256) @@ -254,19 +292,20 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { val publicKey = keyGen(privateKey) val encryptResult = encryptInstance.encrypt(publicKey, plaintext, PrivateKey.fromBigInt(ephemeralSecretKey), publicSigningKey, privateSigningKey) "fail when verify fails" in { - val error = createEncryptWithBadVerify.decrypt(privateKey, encryptResult).leftValue + val error = createEncryptWithBadVerify.decrypt(privateKey, encryptResult).left.value error shouldBe a[SignatureFailed[_]] } "fail when authHash is (magically) wrong" in { - val modifiedPayload = encryptResult.payload.fold[EncryptedValue[Fp]](_.copy(authHash = AuthHash(hex"00ff00ff")), _.copy(authHash = AuthHash(hex"00ff00ff"))) - //This should not be possible as signing should prevent a modified payload, but `encryptInstance` has "always true" signing + val modifiedPayload = + encryptResult.payload.fold[EncryptedValue[Fp]](_.copy(authHash = AuthHash(hex"00ff00ff")), _.copy(authHash = AuthHash(hex"00ff00ff"))) + // This should not be possible as signing should prevent a modified payload, but `encryptInstance` has "always true" signing val modifiedEncryptResult = encryptResult.copy(payload = modifiedPayload) - val decryptErr = encryptInstance.decrypt(privateKey, modifiedEncryptResult).leftValue + val decryptErr = encryptInstance.decrypt(privateKey, modifiedEncryptResult).left.value decryptErr shouldBe a[AuthHashMatchFailed[_]] } "fail when authHash does not match because of wrong private key" in { val differentPrivateKey = PrivateKey(Fp(BigInt("-44"))) - val decryptErr = encryptInstance.decrypt(differentPrivateKey, encryptResult).leftValue + val decryptErr = encryptInstance.decrypt(differentPrivateKey, encryptResult).left.value decryptErr shouldBe a[AuthHashMatchFailed[_]] } @@ -282,7 +321,8 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { val encryptResult = encryptInstance.encrypt(publicKey, plaintext, ephemeralPrivateKey, publicSigningKey, privateSigningKey) val raRePrivateKey = PrivateKey.fromBigInt(BigInt("17561965855055966875289582496525889116201409974621952158489640859240156546764")) val raReK = encryptInstance.generateRthRoot(randomFP12IO.unsafeRunSync()) - val reencryptionKey = encryptInstance.generateReencryptionKey(privateKey, publicKey, reencryptionPrivate, salt, PublicSigningKey.empty, PrivateSigningKey.empty) + val reencryptionKey = + encryptInstance.generateReencryptionKey(privateKey, publicKey, reencryptionPrivate, salt, PublicSigningKey.empty, PrivateSigningKey.empty) "match known value" in { val reencryptedValueOrError = encryptInstance.reencrypt(reencryptionKey, encryptResult, raRePrivateKey, raReK, publicSigningKey, privateSigningKey) val reencryptedValue = reencryptedValueOrError.value @@ -296,25 +336,34 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { val reencryptedValue = reencryptedValueOrError.value val differentPrivateKey = PrivateKey(Fp(BigInt("-44"))) val decryptedValueOrError = encryptInstance.decrypt(differentPrivateKey, reencryptedValue) - val decryptErr = decryptedValueOrError.leftValue + val decryptErr = decryptedValueOrError.left.value decryptErr shouldBe a[AuthHashMatchFailed[_]] } - "roundtrip with decryptN for single level" in { - forAll { (privateKeyFp: Fp, reencryptionPrivate: PrivateKey[Fp], salt: FP12Elem[Fp], plaintext: FP12Elem[Fp], ephemeralPrivateKey: PrivateKey[Fp], fps: (Fp, FP12Elem[Fp])) => - val (_, reencryptionSaltFp) = fps - val privateKey = PrivateKey(privateKeyFp) - val fromPublicKey = keyGen(privateKey) - val toPublicKey = fromPublicKey - val reencryptionKey = encryptInstance.generateReencryptionKey(privateKey, toPublicKey, reencryptionPrivate, salt, PublicSigningKey.empty, PrivateSigningKey.empty) - val encryptResult = encryptInstance.encrypt(toPublicKey, plaintext, ephemeralPrivateKey, publicSigningKey, privateSigningKey) - val reencryptedValueOrError = encryptInstance.reencrypt(reencryptionKey, encryptResult, reencryptionPrivate, reencryptionSaltFp, publicSigningKey, privateSigningKey) - val reencryptedValue = reencryptedValueOrError.value - val decryptedValueOrError = encryptInstance.decrypt(privateKey, reencryptedValue) - val decryptedValue = decryptedValueOrError.value - decryptedValue shouldBe plaintext + "roundtrip with decryptN for single level" in + forAll { + ( + privateKeyFp: Fp, + reencryptionPrivate: PrivateKey[Fp], + salt: FP12Elem[Fp], + plaintext: FP12Elem[Fp], + ephemeralPrivateKey: PrivateKey[Fp], + fps: (Fp, FP12Elem[Fp]) + ) => + val (_, reencryptionSaltFp) = fps + val privateKey = PrivateKey(privateKeyFp) + val fromPublicKey = keyGen(privateKey) + val toPublicKey = fromPublicKey + val reencryptionKey = + encryptInstance.generateReencryptionKey(privateKey, toPublicKey, reencryptionPrivate, salt, PublicSigningKey.empty, PrivateSigningKey.empty) + val encryptResult = encryptInstance.encrypt(toPublicKey, plaintext, ephemeralPrivateKey, publicSigningKey, privateSigningKey) + val reencryptedValueOrError = + encryptInstance.reencrypt(reencryptionKey, encryptResult, reencryptionPrivate, reencryptionSaltFp, publicSigningKey, privateSigningKey) + val reencryptedValue = reencryptedValueOrError.value + val decryptedValueOrError = encryptInstance.decrypt(privateKey, reencryptedValue) + val decryptedValue = decryptedValueOrError.value + decryptedValue shouldBe plaintext } - } "compute good authHash" in { encryptResult.payload.authHash shouldBe AuthHash.create(sha256Hash, encryptResult.payload.ephemeralPublicKey, plaintext) @@ -322,14 +371,16 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { } "fail on bad signature" in { - val reencryptedValueOrError = createEncryptWithBadVerify.reencrypt(reencryptionKey, encryptResult, raRePrivateKey, raReK, publicSigningKey, privateSigningKey) - val error = reencryptedValueOrError.leftValue + val reencryptedValueOrError = + createEncryptWithBadVerify.reencrypt(reencryptionKey, encryptResult, raRePrivateKey, raReK, publicSigningKey, privateSigningKey) + val error = reencryptedValueOrError.left.value error shouldBe a[SignatureFailed[_]] } } "reencryptN" should { - val expectedHashableEncryptedTwice = hex"8538d52016446c7e8f4fa28e333cef771e4c17389682a8515a9e2fbb88caf3f94af54e76c9f0163854b907c19b71a1970877884286173dc8842a80dd46aa9e615ac6a2157793862320033c4024ab86e06417d199811499127bb8b2eb8d69ec833be81a2b786f2fedc61737bb8864d55786547cd09e2f9b640c760355aa86ef685528d7fae7c42389a9a0260b3d20585ff33bf92bc08d2d1a91783a021f169fca1862fb0e038af94b4de96e8eb882437e3a9bd5d8920f2d7feb991efd09f47fb35768b0e0d8d0c3512551ca92bfd0539d7178a3bc6eb0e21d467fc1e2fcf6ad542e1dc66cc03e6b846012bf8f85eaabfc596e3de6044fc0561723431b7f6a5bd8577945d6b3870cecc29b89522b63acea10956d188a5eb74d22686e9248e85c403aca90a727f1f0cefe6e07b9ce6976aa91441a8f52f9acc1df61bf63af6ea5ef1661815f56697f1d5da1028a25917bc0ae8c9d844edc39c955fbe9bb73c5745f288e8f6cef6bf2bc6971bb2f18f227415a6f6fb9112f8a787840da96a5a0a4452fc6dc1ca38196e9ae4420171d71d3a9cdc3bca78047ec363678abcffbc51b743db43e23027edddeba64bcd3074955fce91f00210a910fa6b337afbfbd5f981399a5fe86e2c2dbdfd528730f26e70aadeed4103aab96196911da5900508cf6c571bdc397623d278d8a82224111e7441509d72faba0d8fd8994d74674025c20e34194d9ca607479e476bba584c87e53b33b70bc8b4a200b13eab6f00bcfc4a3ea2ceeee59f1a59c17f8e4934b137e7c2bdaa3a131bf276424a4340e34b57fbc7708ef779ced7c8d3915f4f982d8bd11246b7ed989c19c9826b4ea61ba9cce06320eff550399ee97908b0ba353d5ced125c5edb679a31c1604bd848f77c94d619348cb07a089a743ecbf56cd5e6fb77b719068bcbf4ef57ff8c5f791a4ea807c863f63ff7cbdc105d5b92d666f1fc05a0dad33597da211b5864e9b15969b3bdfd57d5efaad7a15f75d3d4d055c9920d7a2be72d257104ae75721368a645920f43e38b84350522b8d2c589d661ec296d9f9ef6bda55e43760924698d22d16f7cbd51c565ef386e92a600f3414dfe7efd4bdeec09bff1c3bbcf3673b6b0bcd9b74fc183c2079da10c4466af7b39d4cd963611536b67e9b992aec8cc5432f6b38ae20665e8da1bf3474675b4711e91e4ce9d15765ef9b30a67ee68a2dc2cfce6e84415fe38b3acb03a01afb815c232ded3089f258aec45850a672eb18d18e90ea55ee1626528543178f59238b848631640e04b9d55758dc6b32ea92ce00248a7dd5617a0490ffe984617ed44e0748e5fb99f1ada2d26c36b1f9dcf34b2c5247eeefda0c0ed47500da3c806cfcc7035bb1abe6b63dbcd4c1bdbcfe6b369d46117cd6be33b7cc44d2085344dde3ba832a3394ed03d0de5676dac700449765c29f92d3230141e2782d140790878dd447d25faa9da250764e37a5cec2651959dba1a290f3519663b71c8de3618f4b0efbd98dea89b719c3b4513994949acd3bbc3de9c18f8df4a0d1baed760f1bc501d288a58acd18b97bb12746ed5e497366edc75050684a1a7a190a095345a821a1dc167fbbe2a6ba87fe44608c8cbfad83644896bc22477f8e620884815a4eb36a0e2378adcd0c74aa7e941cf166b17554ec66c9265258278bc1b6cf4e2a7ca76f3769bd7a22e10303901abf8c1b19e12c182f7ebc985f68c9376646bce71d39347fd04184ea9bc0eb23dbc11c1f4a2672a6101bc64b549354d40195e682b2ce53f616672170117e23ab1e1eaf141553fd6f759bc8c061c483fb5b287c65a82d6c239b63c73e1f67686acc1d776c72158833e80581f8440fd15ecd376435d8412cc20f965e90e87af8406807b1484d1d8da5c45eb09f3963ebb3de7c120f0542bfb2024adca8956a8da32f03112f91f3bf8c5302a597388f252631820de477856e29e6397c006ee0e28c990ddc3964760eab0d148c5509e606038ef59941322cd535bb6c8e9a8d673213917e6ba1a5119cd7b642303b8c3ad06651f60cc6f8ee75d2a08f561fdec73237471eb0a20f15ac73cf2d7d8476a01bd5fa63b550242fe1bbc1192567a9a80005a974b034f8df8891d926e0dd31c9e575dfce569a7a5d777a67bb9c453d20b62828dc29ed150cff4a9b168c7a8a4989d1b3aa06d8a879a0440f860d4e0b25a8e8c2e30a348d9a151e7a7ceeaf4fa6bc2617e561a83e31cc4bb7a870a413f4d37ead4496eb7e27b07b012b28eb67151af8b26cb2e6c2edfda62d114c67697e53d17911292a398f2087f80744a3030029995e7e7759356374fc431b8cdf4a09544f5699bd429930c6b6152dc2bb07e062c74422e1439293abcc5825fac6ddf3f33d9bf6eb5bd259538aea49758b704cccf440f512680a4bfdb46c90a0b6381d99d390f2c2721970c939b0cce41449fa8eb23f5b941d3aaa6e2cbe94ddb645c16eaf0f3d068d6da459925c9bcfb377cc269bf995d768095d225046792f991edff225ad955f2b6cd5543cac46751c58b7abc78e498b949eec0da842a877f6872c79b96f3220cccc1e3f7adcbf787162dc7841f58943fd97a01945537b294bc285dde3ff6a543875517b0403f1888e0b21d0253b74dbcf8518a89bbeef68d82035a66ac9bc5a2161665295f0fec47f533f124ba35597bf0dded2d67a77688db1e5d8dfd7a38cb8a8efa5ec68fdb6cf04b9254fd2aafa2b0e55089da484507a92d666d0309406cdcc72e0232d9c57138cc52c1ddf36bd51a1078b946496f3559bfc6dd1692ce4a41736dc49c09519f70edff330cd253b7b2797fd89941c330fc07251153f489fa93183c6c7563a792c80c9c52e26f1f63e335776216e534bef47d4771430e9ec2e54fd667385a2619a5f47d42b0f9c025d6df3ee2c81af97e9dcfb17a50b4454d53827ee484296635d30bba9ec1a2537f2084fa4a0fcd4c4a60ba75c8194487c0b95ef8ade74f738fc1f4f97deaca40502105598bc6069e621e297869be84cf6c3b8c3ddb57e27002d10104d20ca31de39336753953faf07e0e0a7124d3fd3b0814e750ac6942b1bdf752440f186a6c0d201dfebf9a97ee62647a817a0dfac3eecc9288d39d567b1d40b11a4265ffdd470565fca9a418d3cb4d62e7964c19e1c3f2984a1d5eb5c0cea2d952b3af8f75014000438f1be0c23e1a151e4eca1018bc7b14bc4df3784f578" + val expectedHashableEncryptedTwice = + hex"8538d52016446c7e8f4fa28e333cef771e4c17389682a8515a9e2fbb88caf3f94af54e76c9f0163854b907c19b71a1970877884286173dc8842a80dd46aa9e615ac6a2157793862320033c4024ab86e06417d199811499127bb8b2eb8d69ec833be81a2b786f2fedc61737bb8864d55786547cd09e2f9b640c760355aa86ef685528d7fae7c42389a9a0260b3d20585ff33bf92bc08d2d1a91783a021f169fca1862fb0e038af94b4de96e8eb882437e3a9bd5d8920f2d7feb991efd09f47fb35768b0e0d8d0c3512551ca92bfd0539d7178a3bc6eb0e21d467fc1e2fcf6ad542e1dc66cc03e6b846012bf8f85eaabfc596e3de6044fc0561723431b7f6a5bd8577945d6b3870cecc29b89522b63acea10956d188a5eb74d22686e9248e85c403aca90a727f1f0cefe6e07b9ce6976aa91441a8f52f9acc1df61bf63af6ea5ef1661815f56697f1d5da1028a25917bc0ae8c9d844edc39c955fbe9bb73c5745f288e8f6cef6bf2bc6971bb2f18f227415a6f6fb9112f8a787840da96a5a0a4452fc6dc1ca38196e9ae4420171d71d3a9cdc3bca78047ec363678abcffbc51b743db43e23027edddeba64bcd3074955fce91f00210a910fa6b337afbfbd5f981399a5fe86e2c2dbdfd528730f26e70aadeed4103aab96196911da5900508cf6c571bdc397623d278d8a82224111e7441509d72faba0d8fd8994d74674025c20e34194d9ca607479e476bba584c87e53b33b70bc8b4a200b13eab6f00bcfc4a3ea2ceeee59f1a59c17f8e4934b137e7c2bdaa3a131bf276424a4340e34b57fbc7708ef779ced7c8d3915f4f982d8bd11246b7ed989c19c9826b4ea61ba9cce06320eff550399ee97908b0ba353d5ced125c5edb679a31c1604bd848f77c94d619348cb07a089a743ecbf56cd5e6fb77b719068bcbf4ef57ff8c5f791a4ea807c863f63ff7cbdc105d5b92d666f1fc05a0dad33597da211b5864e9b15969b3bdfd57d5efaad7a15f75d3d4d055c9920d7a2be72d257104ae75721368a645920f43e38b84350522b8d2c589d661ec296d9f9ef6bda55e43760924698d22d16f7cbd51c565ef386e92a600f3414dfe7efd4bdeec09bff1c3bbcf3673b6b0bcd9b74fc183c2079da10c4466af7b39d4cd963611536b67e9b992aec8cc5432f6b38ae20665e8da1bf3474675b4711e91e4ce9d15765ef9b30a67ee68a2dc2cfce6e84415fe38b3acb03a01afb815c232ded3089f258aec45850a672eb18d18e90ea55ee1626528543178f59238b848631640e04b9d55758dc6b32ea92ce00248a7dd5617a0490ffe984617ed44e0748e5fb99f1ada2d26c36b1f9dcf34b2c5247eeefda0c0ed47500da3c806cfcc7035bb1abe6b63dbcd4c1bdbcfe6b369d46117cd6be33b7cc44d2085344dde3ba832a3394ed03d0de5676dac700449765c29f92d3230141e2782d140790878dd447d25faa9da250764e37a5cec2651959dba1a290f3519663b71c8de3618f4b0efbd98dea89b719c3b4513994949acd3bbc3de9c18f8df4a0d1baed760f1bc501d288a58acd18b97bb12746ed5e497366edc75050684a1a7a190a095345a821a1dc167fbbe2a6ba87fe44608c8cbfad83644896bc22477f8e620884815a4eb36a0e2378adcd0c74aa7e941cf166b17554ec66c9265258278bc1b6cf4e2a7ca76f3769bd7a22e10303901abf8c1b19e12c182f7ebc985f68c9376646bce71d39347fd04184ea9bc0eb23dbc11c1f4a2672a6101bc64b549354d40195e682b2ce53f616672170117e23ab1e1eaf141553fd6f759bc8c061c483fb5b287c65a82d6c239b63c73e1f67686acc1d776c72158833e80581f8440fd15ecd376435d8412cc20f965e90e87af8406807b1484d1d8da5c45eb09f3963ebb3de7c120f0542bfb2024adca8956a8da32f03112f91f3bf8c5302a597388f252631820de477856e29e6397c006ee0e28c990ddc3964760eab0d148c5509e606038ef59941322cd535bb6c8e9a8d673213917e6ba1a5119cd7b642303b8c3ad06651f60cc6f8ee75d2a08f561fdec73237471eb0a20f15ac73cf2d7d8476a01bd5fa63b550242fe1bbc1192567a9a80005a974b034f8df8891d926e0dd31c9e575dfce569a7a5d777a67bb9c453d20b62828dc29ed150cff4a9b168c7a8a4989d1b3aa06d8a879a0440f860d4e0b25a8e8c2e30a348d9a151e7a7ceeaf4fa6bc2617e561a83e31cc4bb7a870a413f4d37ead4496eb7e27b07b012b28eb67151af8b26cb2e6c2edfda62d114c67697e53d17911292a398f2087f80744a3030029995e7e7759356374fc431b8cdf4a09544f5699bd429930c6b6152dc2bb07e062c74422e1439293abcc5825fac6ddf3f33d9bf6eb5bd259538aea49758b704cccf440f512680a4bfdb46c90a0b6381d99d390f2c2721970c939b0cce41449fa8eb23f5b941d3aaa6e2cbe94ddb645c16eaf0f3d068d6da459925c9bcfb377cc269bf995d768095d225046792f991edff225ad955f2b6cd5543cac46751c58b7abc78e498b949eec0da842a877f6872c79b96f3220cccc1e3f7adcbf787162dc7841f58943fd97a01945537b294bc285dde3ff6a543875517b0403f1888e0b21d0253b74dbcf8518a89bbeef68d82035a66ac9bc5a2161665295f0fec47f533f124ba35597bf0dded2d67a77688db1e5d8dfd7a38cb8a8efa5ec68fdb6cf04b9254fd2aafa2b0e55089da484507a92d666d0309406cdcc72e0232d9c57138cc52c1ddf36bd51a1078b946496f3559bfc6dd1692ce4a41736dc49c09519f70edff330cd253b7b2797fd89941c330fc07251153f489fa93183c6c7563a792c80c9c52e26f1f63e335776216e534bef47d4771430e9ec2e54fd667385a2619a5f47d42b0f9c025d6df3ee2c81af97e9dcfb17a50b4454d53827ee484296635d30bba9ec1a2537f2084fa4a0fcd4c4a60ba75c8194487c0b95ef8ade74f738fc1f4f97deaca40502105598bc6069e621e297869be84cf6c3b8c3ddb57e27002d10104d20ca31de39336753953faf07e0e0a7124d3fd3b0814e750ac6942b1bdf752440f186a6c0d201dfebf9a97ee62647a817a0dfac3eecc9288d39d567b1d40b11a4265ffdd470565fca9a418d3cb4d62e7964c19e1c3f2984a1d5eb5c0cea2d952b3af8f75014000438f1be0c23e1a151e4eca1018bc7b14bc4df3784f578" val ptFp12 = FP12Elem.create(Fp(1), Fp(2), Fp(3), Fp(4), Fp(5), Fp(6), Fp(7), Fp(8), Fp(9), Fp(10), Fp(11), Fp(12)) val salt1Fp12 = FP12Elem.create(Fp(11), Fp(12), Fp(13), Fp(14), Fp(15), Fp(16), Fp(17), Fp(18), Fp(19), Fp(110), Fp(111), Fp(112)) val randReK1Fp12 = FP12Elem.create(Fp(21), Fp(22), Fp(23), Fp(24), Fp(25), Fp(26), Fp(27), Fp(28), Fp(29), Fp(210), Fp(211), Fp(212)) @@ -347,16 +398,16 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { val publicKey3 = keyGen(privateKey3) val plaintext = encryptInstance.generateRthRoot(ptFp12) - //First level Encryption + // First level Encryption val encryptResult = encryptInstance.encrypt(publicKey, plaintext, ephemeralPrivateKey, publicSigningKey, privateSigningKey) val raRePrivateKey = PrivateKey.fromBigInt(BigInt("17561965855055966875289582496525889116201409974621952158489640859240156546764")) val raReK = encryptInstance.generateRthRoot(randReK1Fp12) val reencryptionKey = encryptInstance.generateReencryptionKey(privateKey, publicKey2, reencryptionPrivate, salt1, publicSigningKey, privateSigningKey) val reencryptedValueOrError = encryptInstance.reencrypt(reencryptionKey, encryptResult, raRePrivateKey, raReK, publicSigningKey, privateSigningKey) - //Generate first level reencryption + // Generate first level reencryption val reencryptedValue = reencryptedValueOrError.value - //Now let's do a 2nd level of reencryption + // Now let's do a 2nd level of reencryption val raRePrivateKey2 = PrivateKey.fromBigInt(BigInt("1756196585505596687528958249652588911620140997462195215848000000000")) val raReK2 = encryptInstance.generateRthRoot(randReK2Fp12) val salt2 = encryptInstance.generateRthRoot(salt2Fp12) @@ -371,25 +422,25 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { } "generateReencryptionKey" should { - "produce signature that doesn't care about hashedK" in { + "produce signature that doesn't care about hashedK" in forAll { (publicKey: PublicKey[Fp], privKey: PrivateKey[Fp], diffHashedK: HomogeneousPoint[FP2Elem[Fp]]) => forAll(genReencryptionKey(privKey, publicKey)) { key => val changedKey = key.copy(signature = Signature(hex"deadbeef"), payload = key.payload.copy(hashedK = diffHashedK)) key.toHashBytes shouldBe changedKey.toHashBytes } } - } } "verifySignedValue" should { - //An encrypt instance which will fail verify if the messages passed are different. + // An encrypt instance which will fail verify if the messages passed are different. val encryptInstanceWithSign = new InternalApi( Sha256Hash(com.ironcorelabs.recrypt.Sha256), - Ed25519Signing((_, message) => Signature(message), (_, message, signature) => message == signature.bytes), Fp.curvePoints + Ed25519Signing((_, message) => Signature(message), (_, message, signature) => message == signature.bytes), + Fp.curvePoints ) val pubKeyBytes = hex"dead" val origMessage = Fp(hex"beeeeeeeef") - //Signature manually computed. publicKeyBytes + origMessage + // Signature manually computed. publicKeyBytes + origMessage val signedValue = SignedValue(PublicSigningKey(pubKeyBytes), Signature(pubKeyBytes ++ Hashable[Fp].toByteVector(origMessage)), origMessage) "succeed if the payload is the same" in { encryptInstanceWithSign.verifySignedValue(signedValue) shouldBe Some(origMessage) @@ -407,7 +458,10 @@ class InternalApiTest extends com.ironcorelabs.recrypt.TestBase { object InternalApiTest { val defaultSignature = Signature(hex"deaddeefbeef") - def createEncryptWithoutSigning(hashFunc: ByteVector => ByteVector): InternalApi[Fp] = new InternalApi(Sha256Hash(hashFunc), Ed25519Signing((_, _) => defaultSignature, (_, _, _) => true), Fp.curvePoints) - def createInternalApi480WithoutSigning(hashFunc: ByteVector => ByteVector): InternalApi[Fp480] = new InternalApi(Sha256Hash(hashFunc), Ed25519Signing((_, _) => defaultSignature, (_, _, _) => true), Fp480.curvePoints) - def createEncryptWithBadVerify: InternalApi[Fp] = new InternalApi(Sha256Hash { bytes => bytes }, Ed25519Signing((_, _) => defaultSignature, (_, _, _) => false), Fp.curvePoints) + def createEncryptWithoutSigning(hashFunc: ByteVector => ByteVector): InternalApi[Fp] = + new InternalApi(Sha256Hash(hashFunc), Ed25519Signing((_, _) => defaultSignature, (_, _, _) => true), Fp.curvePoints) + def createInternalApi480WithoutSigning(hashFunc: ByteVector => ByteVector): InternalApi[Fp480] = + new InternalApi(Sha256Hash(hashFunc), Ed25519Signing((_, _) => defaultSignature, (_, _, _) => true), Fp480.curvePoints) + def createEncryptWithBadVerify: InternalApi[Fp] = + new InternalApi(Sha256Hash(bytes => bytes), Ed25519Signing((_, _) => defaultSignature, (_, _, _) => false), Fp.curvePoints) } diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/PublicKeyGenTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/PublicKeyGenTest.scala index b6fa226..673555c 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/PublicKeyGenTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/PublicKeyGenTest.scala @@ -17,16 +17,21 @@ package com.ironcorelabs.recrypt.internal -import point.HomogeneousPoint -import Fp.implicits._ import cats.Eq +import com.ironcorelabs.recrypt.internal.Fp.implicits._ +import com.ironcorelabs.recrypt.internal.point.HomogeneousPoint class PublicKeyGenTest extends com.ironcorelabs.recrypt.TestBase { "KeyGen" should { "generate known key" in { val privateKey = PrivateKey.fromBigInt(BigInt("37777967648492203239675772600961898148040325589588086812374811831221462604944")) - val expectedResult = PublicKey(HomogeneousPoint(Fp(BigInt("56377452267431283559088187378398270325210563762492926393848580098576649271541")), Fp(BigInt("46643694276241842996939080253335644316475473619096522181405937227991761798154"))).value) + val expectedResult = PublicKey( + HomogeneousPoint( + Fp(BigInt("56377452267431283559088187378398270325210563762492926393848580098576649271541")), + Fp(BigInt("46643694276241842996939080253335644316475473619096522181405937227991761798154")) + ).value + ) val result = new PublicKeyGen(Fp.curvePoints.generator)(privateKey) val eq = Eq[PublicKey[Fp]] eq.eqv(result, expectedResult) shouldBe true @@ -34,7 +39,12 @@ class PublicKeyGenTest extends com.ironcorelabs.recrypt.TestBase { "generate known key (max 32-byte private key)" in { val privateKey = PrivateKey.fromBigInt(BigInt("50791539541669591690774546266328002110444626558017560467580438981048945568152")) - val expectedResult = PublicKey(HomogeneousPoint(Fp(BigInt("58483620629232886210555514960799664032881966270053836377116209031946678864174")), Fp(BigInt("39604663823550822619127054070927331080305575010367415285113646212320556073913"))).value) + val expectedResult = PublicKey( + HomogeneousPoint( + Fp(BigInt("58483620629232886210555514960799664032881966270053836377116209031946678864174")), + Fp(BigInt("39604663823550822619127054070927331080305575010367415285113646212320556073913")) + ).value + ) val result = PublicKeyGen(Fp.curvePoints.generator)(privateKey) val eq = Eq[PublicKey[Fp]] eq.eqv(result, expectedResult) shouldBe true diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/SchnorrSignatureTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/SchnorrSignatureTest.scala index 5f7f80c..3378f27 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/SchnorrSignatureTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/SchnorrSignatureTest.scala @@ -21,7 +21,7 @@ import scodec.bits._ class SchnorrSignatureTest extends com.ironcorelabs.recrypt.TestBase { - //We don't support this in general because we lose type safety. For tests we'll just allow it. + // We don't support this in general because we lose type safety. For tests we'll just allow it. implicit val hashableByteVector: Hashable[ByteVector] = Hashable.by[ByteVector](identity) "SchnorrSignature for Fp" should { import Fp.implicits._ @@ -72,9 +72,19 @@ class SchnorrSignatureTest extends com.ironcorelabs.recrypt.TestBase { "verify known good with augmentation" in { val augmenting = PrivateKey(Fp(hex"0x85d403b4e6f4b1e19b9572fcbc4751508bffc5ca209fc0bcf3149d54c721be20")) - val message = hex"0x3135353138313631333539353469e4601ac60b63e2aabd957c2dd293da29420e7e9a315b896c7a00144dc63a2543faa774934f040a33443ddb8cfce3324879e092181ce74e2c759b2dabaac15c2e2b3fb51761429f4ae0b4643dec667acd96787083384077d60c22b65ae9644e479b552c1da72741b83aa454f87bb1df7d81b1109cfb09d943e52cc10a6ec770606158ee851c4e660014637077733523d04d041a780692dabcdf0c0ce170e8a54cf6d1131319609c932992b9441bf5bfcca73d54cfa06406715d1fe76023be1b6cc13270b35d16c013d84a7fc7101e9abb768953b40ddfcb3a4dcd7986502c465021f6284861dbf3fe62ae80c2df0d0b896f976d0ab793588d344e343f41440e446758d9743cbabaf787ea243c312209d238ba89bbe707f7d60ffa253d0e65176a57b3e47769e90feb4f6ceb90a89d7ce71991aae7449d2f8aa3c90f4a25abfa5145f910a82c7852532b7fae9799bdf9b5ef24428c224e468f6d4d10a53c7e454d1521d2d31ee1e479ece79deec2f292b42b70ca37ce4e5b0d88811813b39e617476b56409881635e09dc8c7d5994188a2ba46b5f5540616cb0c9f2b556e5a1150061c2e1733cdc10306d366b70187d9d70e86c22cd3f87e6c98befa460b15d4529d0dace7273da7bdc1413e398f3d70e419e6ebbb8f9cc6545a31334f1a9b937753174c7856cd0460ed3c0361c3d8851784d5298df7ced7e28e470251db113c7151185fdfd0c43455fb7efb5ff321619070eaa0d2450504a8d240eabdc0de7f0bef8d2e99e7a0306505a9a84170fc5b441bdd276384fd2b082901ab251d072343c0d7d34a41b9ff5d50c90610f4c002c24f84c48ef0f11b709f1082a3b8562537a821727fa4b71fff3bde107e93533e33b96638fde110fa93497d4ba4274f006f1e2204e7de41aff8c7c80e26bb7100f5010a3995a3a84827768b344225044565794a68624763694f694a46557a49314e694973496e523563434936496b705856434a392e65794a77615751694f6a51774f53776963326c6b496a6f696247396a595777746332566e6257567564434973496d74705a4349364e5449314c434a70595851694f6a45314e5445344d5459784d7a5573496d5634634349364d5455314d5467784e6a49314e53776963335669496a6f6959574a6a4d54497a496e302e36565331706f6e48725a493245474a6d47366748574f793258456970626335615a355751306f5a583779776f4835755a595a6c7378663448797152656947494671653536694e396438375978665159737772616c73773e00fc622bb17a1cffc0f101e894da65ace242684e402d03242509a60900869d87ff251f613b28457bba230f351fa5b4bb465c94dd67338dcfcfbe893fb52125" - val publicKey = PublicKey.fromByteVectors(hex"0x3e00fc622bb17a1cffc0f101e894da65ace242684e402d03242509a60900869d", hex"0x87ff251f613b28457bba230f351fa5b4bb465c94dd67338dcfcfbe893fb52125").value - val (r, s) = com.ironcorelabs.recrypt.SchnorrSignature.unsafeFromBytes(hex"0x8151a7bd378dbb25f4aff9c52d44b8c8576dfffe79901e340f5c8999ab41a18c2cdadd8707882adc17ad605d5ec6809241f4b062909e0ac68cf3e9ae7b9f7854").toBigInts + val message = + hex"0x3135353138313631333539353469e4601ac60b63e2aabd957c2dd293da29420e7e9a315b896c7a00144dc63a2543faa774934f040a33443ddb8cfce3324879e092181ce74e2c759b2dabaac15c2e2b3fb51761429f4ae0b4643dec667acd96787083384077d60c22b65ae9644e479b552c1da72741b83aa454f87bb1df7d81b1109cfb09d943e52cc10a6ec770606158ee851c4e660014637077733523d04d041a780692dabcdf0c0ce170e8a54cf6d1131319609c932992b9441bf5bfcca73d54cfa06406715d1fe76023be1b6cc13270b35d16c013d84a7fc7101e9abb768953b40ddfcb3a4dcd7986502c465021f6284861dbf3fe62ae80c2df0d0b896f976d0ab793588d344e343f41440e446758d9743cbabaf787ea243c312209d238ba89bbe707f7d60ffa253d0e65176a57b3e47769e90feb4f6ceb90a89d7ce71991aae7449d2f8aa3c90f4a25abfa5145f910a82c7852532b7fae9799bdf9b5ef24428c224e468f6d4d10a53c7e454d1521d2d31ee1e479ece79deec2f292b42b70ca37ce4e5b0d88811813b39e617476b56409881635e09dc8c7d5994188a2ba46b5f5540616cb0c9f2b556e5a1150061c2e1733cdc10306d366b70187d9d70e86c22cd3f87e6c98befa460b15d4529d0dace7273da7bdc1413e398f3d70e419e6ebbb8f9cc6545a31334f1a9b937753174c7856cd0460ed3c0361c3d8851784d5298df7ced7e28e470251db113c7151185fdfd0c43455fb7efb5ff321619070eaa0d2450504a8d240eabdc0de7f0bef8d2e99e7a0306505a9a84170fc5b441bdd276384fd2b082901ab251d072343c0d7d34a41b9ff5d50c90610f4c002c24f84c48ef0f11b709f1082a3b8562537a821727fa4b71fff3bde107e93533e33b96638fde110fa93497d4ba4274f006f1e2204e7de41aff8c7c80e26bb7100f5010a3995a3a84827768b344225044565794a68624763694f694a46557a49314e694973496e523563434936496b705856434a392e65794a77615751694f6a51774f53776963326c6b496a6f696247396a595777746332566e6257567564434973496d74705a4349364e5449314c434a70595851694f6a45314e5445344d5459784d7a5573496d5634634349364d5455314d5467784e6a49314e53776963335669496a6f6959574a6a4d54497a496e302e36565331706f6e48725a493245474a6d47366748574f793258456970626335615a355751306f5a583779776f4835755a595a6c7378663448797152656947494671653536694e396438375978665159737772616c73773e00fc622bb17a1cffc0f101e894da65ace242684e402d03242509a60900869d87ff251f613b28457bba230f351fa5b4bb465c94dd67338dcfcfbe893fb52125" + val publicKey = PublicKey + .fromByteVectors( + hex"0x3e00fc622bb17a1cffc0f101e894da65ace242684e402d03242509a60900869d", + hex"0x87ff251f613b28457bba230f351fa5b4bb465c94dd67338dcfcfbe893fb52125" + ) + .value + val (r, s) = com.ironcorelabs.recrypt.SchnorrSignature + .unsafeFromBytes( + hex"0x8151a7bd378dbb25f4aff9c52d44b8c8576dfffe79901e340f5c8999ab41a18c2cdadd8707882adc17ad605d5ec6809241f4b062909e0ac68cf3e9ae7b9f7854" + ) + .toBigInts schnorrSigning.verify(publicKey, augmenting, message, SchnorrSignature(r, s), sha256) shouldBe true } } diff --git a/src/test/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPointTest.scala b/src/test/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPointTest.scala index 81fb174..ba39d1c 100644 --- a/src/test/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPointTest.scala +++ b/src/test/scala/com/ironcorelabs/recrypt/internal/point/HomogeneousPointTest.scala @@ -18,16 +18,28 @@ package com.ironcorelabs.recrypt.internal package point import cats.kernel.Eq -import Arbitraries._ -import Fp.implicits._ +import com.ironcorelabs.recrypt.internal.Arbitraries._ +import com.ironcorelabs.recrypt.internal.Fp.implicits._ import org.scalacheck.Arbitrary import spire.algebra.Field class HomogeneousPointTest extends com.ironcorelabs.recrypt.TestBase { val generator = HomogeneousPoint[Fp](Fp(1), Fp(2), Fp(1)) - val g2 = HomogeneousPoint[Fp](Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026864184071691")), Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026864184071772")), Fp(BigInt("64"))) - val g3 = HomogeneousPoint[Fp](Fp(BigInt("65000549695646603732796438742357289393463195703644999101259116053171121198695")), Fp(BigInt("4687415513658244809525991071247988106440212480")), Fp(BigInt("65000549695646603732796438742357781093930617575615238062101372432637196015207"))) - val g4 = HomogeneousPoint[Fp](Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145025948345898599")), Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145010275033523815")), Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026861392762471"))) + val g2 = HomogeneousPoint[Fp]( + Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026864184071691")), + Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026864184071772")), + Fp(BigInt("64")) + ) + val g3 = HomogeneousPoint[Fp]( + Fp(BigInt("65000549695646603732796438742357289393463195703644999101259116053171121198695")), + Fp(BigInt("4687415513658244809525991071247988106440212480")), + Fp(BigInt("65000549695646603732796438742357781093930617575615238062101372432637196015207")) + ) + val g4 = HomogeneousPoint[Fp]( + Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145025948345898599")), + Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145010275033523815")), + Fp(BigInt("65000549695646603732796438742359905742825358107623003571877145026861392762471")) + ) val homogeneousPointEq = Eq[HomogeneousPoint[Fp]] implicit val fpArb: Arbitrary[Fp] = Arbitrary(fpGen) @@ -51,7 +63,7 @@ class HomogeneousPointTest extends com.ironcorelabs.recrypt.TestBase { val fp2ElemZero = Field[FP2Elem[Fp]].zero "always roundtrip with fromXYByteVector" in { val zeroPoint = HomogeneousPoint[FP2Elem[Fp]](fp2ElemZero, fp2ElemZero, fp2ElemZero) - //fromXYByteVector results in a normalized version + // fromXYByteVector results in a normalized version forAll { (one: HomogeneousPoint[FP2Elem[Fp]]) => Eq[HomogeneousPoint[FP2Elem[Fp]]].eqv(HomogeneousPoint.fromXYByteVectorOnTwistedCurve(one.toByteVector).getOrElse(zeroPoint), one) shouldBe true } @@ -67,7 +79,7 @@ class HomogeneousPointTest extends com.ironcorelabs.recrypt.TestBase { } "be known computed points" in { generator.times(3) shouldBe g3 - //because they're generated different ways they z value is different. + // because they're generated different ways they z value is different. homogeneousPointEq.eqv(generator.add(generator).add(generator), g3) shouldBe true generator.double.double shouldBe g4 @@ -77,25 +89,56 @@ class HomogeneousPointTest extends com.ironcorelabs.recrypt.TestBase { "negate" should { "be inverse" in { - val p = HomogeneousPoint[Fp](Fp(BigInt("51868263261043312406854161881216729836664278127733745592824683284523123334836")), Fp(BigInt("33177037179116331804302795932430957042199370361710027222382691374266461254686")), Fp(1)) + val p = HomogeneousPoint[Fp]( + Fp(BigInt("51868263261043312406854161881216729836664278127733745592824683284523123334836")), + Fp(BigInt("33177037179116331804302795932430957042199370361710027222382691374266461254686")), + Fp(1) + ) p.add(p.negate).isZero shouldBe true } } "FP2Elem" should { val generator = HomogeneousPoint[FP2Elem[Fp]]( - FP2Elem(Fp(BigInt("39898887170429929807040143276261848585078991568615066857293752634765338134660")), Fp(BigInt("4145079839513126747718408015399244712098849008922890496895080944648891367549"))), - FP2Elem(Fp(BigInt("54517427188233403272140512636254575372766895942651963572804557077716421872651")), Fp(BigInt("29928198841033477396304275898313889635561368630804063259494165651195801046334"))), - FP2Elem(Fp(BigInt("25757029117904574834370194644693146689936696995375576562303493881177613755324")), Fp(BigInt("20317563273514500379895253969863230147776170908243485486513578790623697384796"))) + FP2Elem( + Fp(BigInt("39898887170429929807040143276261848585078991568615066857293752634765338134660")), + Fp(BigInt("4145079839513126747718408015399244712098849008922890496895080944648891367549")) + ), + FP2Elem( + Fp(BigInt("54517427188233403272140512636254575372766895942651963572804557077716421872651")), + Fp(BigInt("29928198841033477396304275898313889635561368630804063259494165651195801046334")) + ), + FP2Elem( + Fp(BigInt("25757029117904574834370194644693146689936696995375576562303493881177613755324")), + Fp(BigInt("20317563273514500379895253969863230147776170908243485486513578790623697384796")) + ) ) val g2 = HomogeneousPoint[FP2Elem[Fp]]( - FP2Elem(Fp(BigInt("32311960366087947012076758362581520145717417890234046373304260108936423529098")), Fp(BigInt("35269620335705756074126918480452007394637574429548402586405603689111865012277"))), - FP2Elem(Fp(BigInt("2671623292902381891983929407252968557708719845514875421467184727609122988155")), Fp(BigInt("43411962343069999753626042779984151944324217242944227801565084354101193342512"))), - FP2Elem(Fp(BigInt("49224387566402035134179552391576133560012154182767147936960003073581543401731")), Fp(BigInt("25130345353334486611452031924738614968497575666203626401540449736117460133315"))) + FP2Elem( + Fp(BigInt("32311960366087947012076758362581520145717417890234046373304260108936423529098")), + Fp(BigInt("35269620335705756074126918480452007394637574429548402586405603689111865012277")) + ), + FP2Elem( + Fp(BigInt("2671623292902381891983929407252968557708719845514875421467184727609122988155")), + Fp(BigInt("43411962343069999753626042779984151944324217242944227801565084354101193342512")) + ), + FP2Elem( + Fp(BigInt("49224387566402035134179552391576133560012154182767147936960003073581543401731")), + Fp(BigInt("25130345353334486611452031924738614968497575666203626401540449736117460133315")) + ) ) val g3 = HomogeneousPoint[FP2Elem[Fp]]( - FP2Elem(Fp(BigInt("51086982105523813823110808607809625268338972497063497406133847490229508299200")), Fp(BigInt("52234782886912211912712112378454173535403665704601063483058173875683915331983"))), - FP2Elem(Fp(BigInt("59006560018688086896657059684288540317025716993375680687355515288698643930005")), Fp(BigInt("32303626048328539612706779190102637076875855563268472072440283570203880314879"))), - FP2Elem(Fp(BigInt("9132775622516916950536114990103670069586282707156393447180163663038647337412")), Fp(BigInt("11493687929025082100322220798309089712792846582945108156599613143240527668028"))) + FP2Elem( + Fp(BigInt("51086982105523813823110808607809625268338972497063497406133847490229508299200")), + Fp(BigInt("52234782886912211912712112378454173535403665704601063483058173875683915331983")) + ), + FP2Elem( + Fp(BigInt("59006560018688086896657059684288540317025716993375680687355515288698643930005")), + Fp(BigInt("32303626048328539612706779190102637076875855563268472072440283570203880314879")) + ), + FP2Elem( + Fp(BigInt("9132775622516916950536114990103670069586282707156393447180163663038647337412")), + Fp(BigInt("11493687929025082100322220798309089712792846582945108156599613143240527668028")) + ) ) val eq = Eq[HomogeneousPoint[FP2Elem[Fp]]] "have g + g == g*2 " in {