├── .gitignore
├── project
├── build.properties
├── plugins.sbt
└── FluenceCrossType.scala
├── .travis.yml
├── cipher
├── js
│ └── src
│ │ ├── main
│ │ └── scala
│ │ │ └── fluence
│ │ │ └── crypto
│ │ │ ├── facade
│ │ │ └── cryptojs
│ │ │ │ ├── Key.scala
│ │ │ │ ├── Enc.scala
│ │ │ │ ├── Lib.scala
│ │ │ │ ├── Mode.scala
│ │ │ │ ├── Algos.scala
│ │ │ │ ├── Hex.scala
│ │ │ │ ├── Pad.scala
│ │ │ │ ├── WordArrayFactory.scala
│ │ │ │ ├── KeyOptions.scala
│ │ │ │ ├── CryptoJS.scala
│ │ │ │ ├── AES.scala
│ │ │ │ └── CryptOptions.scala
│ │ │ └── aes
│ │ │ └── AesCrypt.scala
│ │ └── test
│ │ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ └── AesJSSpec.scala
├── src
│ └── main
│ │ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ └── aes
│ │ └── AesConfig.scala
└── jvm
│ └── src
│ ├── test
│ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ └── AesSpec.scala
│ └── main
│ └── scala
│ └── fluence
│ └── crypto
│ └── aes
│ └── AesCrypt.scala
├── hashsign
├── js
│ └── src
│ │ └── main
│ │ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ ├── facade
│ │ ├── Buffer.scala
│ │ ├── ed25519
│ │ │ └── Supercop.scala
│ │ └── ecdsa
│ │ │ ├── Hash.scala
│ │ │ └── Elliptic.scala
│ │ ├── hash
│ │ ├── CryptoHashers.scala
│ │ └── JsCryptoHasher.scala
│ │ ├── CryptoJsHelpers.scala
│ │ ├── eddsa
│ │ └── Ed25519.scala
│ │ └── ecdsa
│ │ └── Ecdsa.scala
├── jvm
│ └── src
│ │ ├── main
│ │ └── scala
│ │ │ └── fluence
│ │ │ └── crypto
│ │ │ ├── hash
│ │ │ ├── CryptoHashers.scala
│ │ │ └── JdkCryptoHasher.scala
│ │ │ ├── JavaAlgorithm.scala
│ │ │ ├── eddsa
│ │ │ └── Ed25519.scala
│ │ │ └── ecdsa
│ │ │ └── Ecdsa.scala
│ │ └── test
│ │ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ └── JvmEcdsaSpec.scala
└── src
│ └── test
│ └── scala
│ └── fluence
│ └── crypto
│ ├── HashSpec.scala
│ ├── EcdsaSpec.scala
│ └── Ed25519Spec.scala
├── core
└── src
│ ├── main
│ └── scala
│ │ └── fluence
│ │ └── crypto
│ │ ├── signature
│ │ ├── SignatureChecker.scala
│ │ ├── PubKeyAndSignature.scala
│ │ ├── Signer.scala
│ │ ├── Signature.scala
│ │ └── SignAlgo.scala
│ │ ├── CryptoError.scala
│ │ ├── KeyPair.scala
│ │ ├── Crypto.scala
│ │ ├── DumbCrypto.scala
│ │ └── cipher
│ │ └── CipherSearch.scala
│ └── test
│ └── scala
│ └── fluence
│ └── crypto
│ ├── NoOpCryptSpec.scala
│ └── CryptoSearchingSpec.scala
├── .scalafmt.conf
├── CONTRIBUTING.md
├── README.md
├── FluenceCLA.md
└── LICENSE.md
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | target
3 | log
--------------------------------------------------------------------------------
/project/build.properties:
--------------------------------------------------------------------------------
1 | sbt.version = 1.2.8
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: required
2 |
3 | language: scala
4 | scala:
5 | - 2.12.9
6 |
7 | # These directories are cached to S3 at the end of the build
8 | cache:
9 | directories:
10 | - $HOME/.ivy2/cache
11 | - $HOME/.sbt/boot
12 | - $HOME/.sbt/launchers
13 |
14 | before_cache:
15 | # Tricks to avoid unnecessary cache updates
16 | - find $HOME/.sbt -name "*.lock" | xargs rm
17 | - find $HOME/.ivy2 -name "ivydata-*.properties" | xargs rm
--------------------------------------------------------------------------------
/project/plugins.sbt:
--------------------------------------------------------------------------------
1 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.0.1")
2 |
3 | addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.3.20")
4 |
5 | addSbtPlugin("de.heikoseeberger" % "sbt-header" % "5.2.0")
6 |
7 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.28")
8 | addSbtPlugin("org.portable-scala" % "sbt-crossproject" % "0.6.0")
9 | addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.6.0")
10 |
11 | addSbtPlugin("ch.epfl.scala" % "sbt-scalajs-bundler" % "0.14.0")
12 |
13 | addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.9.2")
14 |
15 | addSbtPlugin("org.foundweekends" % "sbt-bintray" % "0.5.4")
16 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Key.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Key extends js.Object
24 |
--------------------------------------------------------------------------------
/project/FluenceCrossType.scala:
--------------------------------------------------------------------------------
1 | import sbt._
2 | import sbtcrossproject.CrossPlugin.autoImport._
3 |
4 | import scalajscrossproject.ScalaJSCrossPlugin.autoImport._
5 |
6 | /**
7 | * cross types https://github.com/portable-scala/sbt-crossproject
8 | * http://xuwei-k.github.io/slides/scala-js-matsuri/#21
9 | * avoid move files
10 | */
11 | object FluenceCrossType extends sbtcrossproject.CrossType {
12 | override def projectDir(crossBase: File, projectType: String) =
13 | crossBase / projectType
14 |
15 | override def projectDir(crossBase: File, projectType: sbtcrossproject.Platform) = {
16 | val dir = projectType match {
17 | case JVMPlatform ⇒ "jvm"
18 | case JSPlatform ⇒ "js"
19 | }
20 | crossBase / dir
21 | }
22 |
23 | def shared(projectBase: File, conf: String) =
24 | projectBase.getParentFile / "src" / conf / "scala"
25 |
26 | override def sharedSrcDir(projectBase: File, conf: String) =
27 | Some(shared(projectBase, conf))
28 | }
29 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Enc.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Enc extends js.Object {
24 | def Hex: Hex = js.native
25 | }
26 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Lib.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Lib extends js.Object {
24 | def WordArray: WordArrayFactory = js.native
25 | }
26 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Mode.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Modes extends js.Object {
24 | val CBC: Mode = js.native
25 | }
26 |
27 | @js.native
28 | trait Mode extends js.Object
29 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Algos.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Algos extends js.Object {
24 | def SHA256: Algo = js.native
25 | }
26 |
27 | @js.native
28 | trait Algo extends js.Object
29 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/facade/Buffer.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation.JSGlobal
22 |
23 | @js.native
24 | @JSGlobal("Buffer")
25 | class Buffer(arr: js.Array[Byte]) extends js.Object {
26 | def toString(enc: String): String = js.native
27 | }
28 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/signature/SignatureChecker.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.signature
19 |
20 | import cats.data.Kleisli
21 | import fluence.crypto.Crypto
22 | import scodec.bits.ByteVector
23 |
24 | import scala.language.higherKinds
25 |
26 | case class SignatureChecker(check: Kleisli[Crypto.Result, (Signature, ByteVector), Unit])
27 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/hash/CryptoHashers.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.hash
19 |
20 | import fluence.crypto.Crypto
21 |
22 | object CryptoHashers {
23 | lazy val Sha1: Crypto.Hasher[Array[Byte], Array[Byte]] = JsCryptoHasher.Sha1
24 |
25 | lazy val Sha256: Crypto.Hasher[Array[Byte], Array[Byte]] = JsCryptoHasher.Sha256
26 | }
27 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Hex.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait Hex extends js.Object {
24 |
25 | /**
26 | * Parse from HEX to JS byte representation
27 | * @param str Hex
28 | */
29 | def parse(str: String): WordArray = js.native
30 | }
31 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/main/scala/fluence/crypto/hash/CryptoHashers.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.hash
19 |
20 | import fluence.crypto.Crypto
21 |
22 | object CryptoHashers {
23 | lazy val Sha1: Crypto.Hasher[Array[Byte], Array[Byte]] = JdkCryptoHasher.Sha1
24 |
25 | lazy val Sha256: Crypto.Hasher[Array[Byte], Array[Byte]] = JdkCryptoHasher.Sha256
26 | }
27 |
--------------------------------------------------------------------------------
/.scalafmt.conf:
--------------------------------------------------------------------------------
1 | version = 2.0.1
2 |
3 | docstrings = JavaDoc
4 |
5 | maxColumn = 120
6 |
7 | align = some
8 | align.tokens = [{code = "=>", owner = "Case"}, ":=", "%", "%%", "%%%"]
9 |
10 | assumeStandardLibraryStripMargin = true
11 | includeCurlyBraceInSelectChains = false
12 |
13 | continuationIndent {
14 | callSite = 2
15 | defnSite = 2
16 | extendSite = 4
17 | }
18 |
19 | danglingParentheses = true
20 |
21 | newlines {
22 | alwaysBeforeTopLevelStatements = true
23 | sometimesBeforeColonInMethodReturnType = true
24 | penalizeSingleSelectMultiArgList = false
25 | alwaysBeforeElseAfterCurlyIf = false
26 | neverInResultType = false
27 | }
28 |
29 | spaces {
30 | afterKeywordBeforeParen = true
31 | }
32 |
33 | binPack {
34 | parentConstructors = true
35 | literalArgumentLists = true
36 | }
37 |
38 | optIn {
39 | breaksInsideChains = false
40 | breakChainOnFirstMethodDot = true
41 | configStyleArguments = true
42 | }
43 |
44 | runner {
45 | optimizer {
46 | forceConfigStyleOnOffset = 150
47 | forceConfigStyleMinArgCount = 2
48 | }
49 | }
50 |
51 | rewrite {
52 | rules = [
53 | SortImports
54 | ]
55 | }
56 |
57 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/Pad.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation.JSGlobal
22 |
23 | @js.native
24 | @JSGlobal
25 | class Paddings extends js.Object {
26 |
27 | val Pkcs7: Pad = js.native
28 | }
29 |
30 | @js.native
31 | @JSGlobal
32 | class Pad extends js.Object
33 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/WordArrayFactory.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait WordArrayFactory extends js.Object {
24 |
25 | def random(size: Int): WordArray = js.native
26 | def create(array: js.Any): WordArray = js.native
27 | }
28 |
29 | @js.native
30 | trait WordArray extends js.Object
31 |
--------------------------------------------------------------------------------
/cipher/src/main/scala/fluence/crypto/aes/AesConfig.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.aes
19 |
20 | /**
21 | * Config for AES-256 password based encryption
22 | * @param iterationCount The number of iterations of hashing the password
23 | * @param salt Salt, which will be mixed with the password
24 | */
25 | case class AesConfig(
26 | iterationCount: Int = 50,
27 | salt: String = "fluence"
28 | )
29 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/CryptoJsHelpers.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import io.scalajs.nodejs.buffer.Buffer
21 | import scodec.bits.ByteVector
22 |
23 | import scala.language.higherKinds
24 |
25 | object CryptoJsHelpers {
26 | implicit class ByteVectorOp(bv: ByteVector) {
27 | def toJsBuffer: Buffer = Buffer.from(ByteVector(bv.toArray).toHex, "hex")
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/CryptoError.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import scala.language.higherKinds
21 | import scala.util.control.NoStackTrace
22 |
23 | case class CryptoError(message: String, causedBy: Option[Throwable] = None) extends NoStackTrace {
24 | override def getMessage: String = message
25 |
26 | override def getCause: Throwable = causedBy getOrElse super.getCause
27 | }
28 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/signature/PubKeyAndSignature.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.signature
19 |
20 | import fluence.crypto.KeyPair
21 |
22 | /**
23 | * Container for public key of signer and a signature.
24 | *
25 | * @param publicKey Public key of signature maker
26 | * @param signature Some signature
27 | */
28 | case class PubKeyAndSignature(publicKey: KeyPair.Public, signature: Signature)
29 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/signature/Signer.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.signature
19 |
20 | import cats.instances.either._
21 | import fluence.crypto.{Crypto, KeyPair}
22 | import scodec.bits.ByteVector
23 |
24 | case class Signer(publicKey: KeyPair.Public, sign: Crypto.Func[ByteVector, Signature]) {
25 | lazy val signWithPK: Crypto.Func[ByteVector, PubKeyAndSignature] = sign.map(PubKeyAndSignature(publicKey, _))
26 | }
27 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/signature/Signature.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.signature
19 |
20 | import scodec.bits.ByteVector
21 |
22 | /** Container for a signature. */
23 | case class Signature private (sign: ByteVector) extends AnyVal {
24 | def bytes: Array[Byte] = sign.toArray
25 | }
26 |
27 | object Signature {
28 |
29 | def apply(sign: ByteVector): Signature = new Signature(sign)
30 |
31 | def apply(sign: Array[Byte]): Signature = new Signature(ByteVector(sign))
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/KeyOptions.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait KeyOptions extends js.Object {
24 | val keySize: Int
25 | val iterations: Int
26 | val hasher: Algo
27 | }
28 |
29 | object KeyOptions {
30 |
31 | def apply(keySizeBits: Int, iterations: Int, hasher: Algo): KeyOptions = {
32 | js.Dynamic.literal(keySize = keySizeBits / 32, iterations = iterations, hasher = hasher).asInstanceOf[KeyOptions]
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/KeyPair.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import scodec.bits.ByteVector
21 |
22 | case class KeyPair(publicKey: KeyPair.Public, secretKey: KeyPair.Secret)
23 |
24 | object KeyPair {
25 |
26 | case class Public(value: ByteVector) extends AnyVal {
27 | def bytes: Array[Byte] = value.toArray
28 | }
29 |
30 | case class Secret(value: ByteVector) extends AnyVal {
31 | def bytes: Array[Byte] = value.toArray
32 | }
33 |
34 | def fromBytes(pk: Array[Byte], sk: Array[Byte]): KeyPair = fromByteVectors(ByteVector(pk), ByteVector(sk))
35 | def fromByteVectors(pk: ByteVector, sk: ByteVector): KeyPair = KeyPair(Public(pk), Secret(sk))
36 | }
37 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/CryptoJS.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation.JSImport
22 |
23 | @js.native
24 | @JSImport("crypto-js", JSImport.Namespace)
25 | object CryptoJS extends js.Object {
26 |
27 | def pad: Paddings = js.native
28 | def mode: Modes = js.native
29 | def AES: AES = js.native
30 |
31 | /**
32 | * https://en.wikipedia.org/wiki/PBKDF2
33 | * @return Salted and hashed key
34 | */
35 | def PBKDF2(pass: String, salt: String, options: KeyOptions): Key = js.native
36 |
37 | def lib: Lib = js.native
38 |
39 | def enc: Enc = js.native
40 |
41 | def algo: Algos = js.native
42 | }
43 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/facade/ed25519/Supercop.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.ed25519
19 |
20 | import io.scalajs.nodejs.buffer.Buffer
21 |
22 | import scala.scalajs.js
23 | import scala.scalajs.js.annotation.JSImport
24 |
25 | @js.native
26 | trait KeyPair extends js.Object {
27 | val publicKey: Buffer
28 | val secretKey: Buffer
29 | }
30 |
31 | @js.native
32 | @JSImport("supercop.js", JSImport.Namespace)
33 | object Supercop extends js.Object {
34 | def verify(sig: Buffer, msg: Buffer, pubKey: Buffer): Boolean = js.native
35 | def sign(msg: Buffer, pubKey: Buffer, privKey: Buffer): Buffer = js.native
36 | def createKeyPair(seed: Buffer): KeyPair = js.native
37 | def createSeed(): Buffer = js.native
38 | }
39 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contribute Code
2 |
3 | You are welcome to contribute to Fluence.
4 |
5 | Things you need to know:
6 |
7 | 1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
8 | 2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
9 |
10 | ### Contributor License Agreement
11 |
12 | When you contribute, you have to be aware that your contribution is covered by **GNU Affero General Public License**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
13 | In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.
14 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/AES.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation.JSGlobal
22 |
23 | @js.native
24 | @JSGlobal
25 | class AES extends js.Object {
26 |
27 | /**
28 | * @param msg Message to encrypt in JS WordArray.
29 | * Could be created with CryptoJS.lib.WordArray.create(new Int8Array(arrayByte.toJSArray))
30 | * @param options { iv: iv, padding: CryptoJS.pad.Pkcs7, mode: CryptoJS.mode.CBC }
31 | * @return Encrypted message
32 | */
33 | def encrypt(msg: WordArray, key: Key, options: CryptOptions): js.Any = js.native
34 |
35 | def decrypt(encrypted: String, key: Key, options: CryptOptions): js.Any = js.native
36 | }
37 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/facade/ecdsa/Hash.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.ecdsa
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation.JSImport
22 | import scala.scalajs.js.typedarray.Uint8Array
23 |
24 | //TODO hide enc argument in methods, make it `hex` by default
25 | /**
26 | * https://github.com/indutny/hash.js - part of elliptic library
27 | */
28 | @js.native
29 | @JSImport("hash.js", "sha256")
30 | class SHA256() extends js.Object {
31 | def update(msg: Uint8Array): Unit = js.native
32 | def digest(enc: String): String = js.native
33 | }
34 |
35 | @js.native
36 | @JSImport("hash.js", "sha1")
37 | class SHA1() extends js.Object {
38 | def update(msg: Uint8Array): Unit = js.native
39 | def digest(enc: String): String = js.native
40 | }
41 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/facade/cryptojs/CryptOptions.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.cryptojs
19 |
20 | import scala.scalajs.js
21 |
22 | @js.native
23 | trait CryptOptions extends js.Object {
24 | val iv: Option[js.Any]
25 | val padding: Pad
26 | val mode: Mode
27 | }
28 |
29 | object CryptOptions {
30 |
31 | def apply(iv: Option[WordArray], padding: Pad, mode: Mode): CryptOptions = {
32 | iv match {
33 | case Some(i) ⇒
34 | js.Dynamic.literal(iv = i, padding = padding, mode = mode).asInstanceOf[CryptOptions]
35 | case None ⇒
36 | //if IV is empty, there will be an error in JS lib
37 | js.Dynamic
38 | .literal(iv = CryptoJS.lib.WordArray.random(0), padding = padding, mode = mode)
39 | .asInstanceOf[CryptOptions]
40 | }
41 |
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/main/scala/fluence/crypto/JavaAlgorithm.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import java.security.Security
21 |
22 | import org.bouncycastle.jce.provider.BouncyCastleProvider
23 |
24 | import scala.language.{higherKinds, implicitConversions}
25 |
26 | /**
27 | * trait that initializes a JVM-specific provider to work with cryptography
28 | */
29 | private[crypto] trait JavaAlgorithm {
30 | JavaAlgorithm.addProvider
31 | }
32 |
33 | object JavaAlgorithm {
34 |
35 | /**
36 | * add JVM-specific security provider in class loader
37 | */
38 | private lazy val addProvider = {
39 | Option(Security.getProvider(BouncyCastleProvider.PROVIDER_NAME))
40 | .foreach(_ ⇒ Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME))
41 | Security.addProvider(new BouncyCastleProvider())
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/core/src/test/scala/fluence/crypto/NoOpCryptSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import org.scalatest.{Matchers, WordSpec}
21 |
22 | class NoOpCryptSpec extends WordSpec with Matchers {
23 |
24 | "NoOpCrypt" should {
25 | "convert a string to bytes back and forth without any cryptography" in {
26 |
27 | val noOpCrypt = DumbCrypto.cipherString
28 |
29 | val emptyString = ""
30 | noOpCrypt.decrypt(noOpCrypt.encrypt(emptyString).right.get).right.get shouldBe emptyString
31 | val nonEmptyString = "some text here"
32 | noOpCrypt.decrypt(noOpCrypt.encrypt(nonEmptyString).right.get).right.get shouldBe nonEmptyString
33 | val byteArray = Array(1.toByte, 23.toByte, 45.toByte)
34 | noOpCrypt.encrypt(noOpCrypt.decrypt(byteArray).right.get).right.get shouldBe byteArray
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/test/scala/fluence/crypto/JvmEcdsaSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.ecdsa.Ecdsa
21 | import org.scalatest.{Matchers, WordSpec}
22 | import scodec.bits.ByteVector
23 |
24 | import scala.util.Random
25 |
26 | class JvmEcdsaSpec extends WordSpec with Matchers {
27 |
28 | def rndBytes(size: Int): Array[Byte] = Random.nextString(10).getBytes
29 |
30 | def rndByteVector(size: Int) = ByteVector(rndBytes(size))
31 |
32 | "jvm ecdsa algorithm" should {
33 |
34 | "restore key pair from secret key" in {
35 | val algo = Ecdsa.signAlgo
36 | val testKeys = algo.generateKeyPair(None).right.get
37 |
38 | val ecdsa = Ecdsa.ecdsa_secp256k1_sha256
39 |
40 | val newKeys = ecdsa.restorePairFromSecret(testKeys.secretKey).right.get
41 |
42 | testKeys shouldBe newKeys
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/Crypto.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import cats.data.Kleisli
21 |
22 | import scala.util.Try
23 |
24 | object Crypto {
25 | type Result[T] = Either[CryptoError, T]
26 |
27 | type Hasher[A, B] = Kleisli[Result, A, B]
28 |
29 | type Func[A, B] = Kleisli[Result, A, B]
30 |
31 | case class Cipher[A](
32 | encrypt: Kleisli[Result, A, Array[Byte]],
33 | decrypt: Kleisli[Result, Array[Byte], A]
34 | )
35 |
36 | type KeyPairGenerator = Kleisli[Result, Option[Array[Byte]], KeyPair]
37 |
38 | def apply[A, B](fn: A ⇒ Result[B]): Func[A, B] = Kleisli[Result, A, B](fn)
39 |
40 | def tryFn[A, B](fn: A ⇒ B)(errorText: String): Crypto.Func[A, B] =
41 | Crypto(a ⇒ tryUnit(fn(a))(errorText))
42 |
43 | def tryUnit[B](fn: ⇒ B)(errorText: String): Result[B] =
44 | Try(fn).toEither.left.map(t ⇒ CryptoError(errorText, Some(t)))
45 |
46 | def cond[B](ifTrue: ⇒ B, errorText: ⇒ String): Crypto.Func[Boolean, B] =
47 | Crypto(Either.cond(_, ifTrue, CryptoError(errorText)))
48 | }
49 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/main/scala/fluence/crypto/hash/JdkCryptoHasher.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.hash
19 |
20 | import java.security.MessageDigest
21 |
22 | import fluence.crypto.{Crypto, CryptoError}
23 |
24 | import scala.util.Try
25 |
26 | object JdkCryptoHasher {
27 |
28 | lazy val Sha256: Crypto.Hasher[Array[Byte], Array[Byte]] = apply("SHA-256")
29 | lazy val Sha1: Crypto.Hasher[Array[Byte], Array[Byte]] = apply("SHA-1")
30 |
31 | /**
32 | * Thread-safe implementation of [[Crypto.Hasher]] with standard jdk [[java.security.MessageDigest]]
33 | *
34 | * @param algorithm one of allowed hashing algorithms
35 | * [[https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest]]
36 | */
37 | def apply(algorithm: String): Crypto.Hasher[Array[Byte], Array[Byte]] =
38 | Crypto(
39 | bytes ⇒
40 | Try(MessageDigest.getInstance(algorithm).digest(bytes)).toEither.left
41 | .map(err ⇒ CryptoError(s"Cannot get $algorithm hash", Some(err)))
42 | )
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/core/src/test/scala/fluence/crypto/CryptoSearchingSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.cipher.CipherSearch
21 | import org.scalatest.{Matchers, WordSpec}
22 |
23 | import scala.collection.Searching.{Found, InsertionPoint}
24 |
25 | class CryptoSearchingSpec extends WordSpec with Matchers {
26 |
27 | "search" should {
28 | "correct search plainText key in encrypted data" in {
29 |
30 | val crypt: Crypto.Cipher[String] = DumbCrypto.cipherString
31 |
32 | val plainTextElements = Array("A", "B", "C", "D", "E")
33 | val encryptedElements = plainTextElements.map(t ⇒ crypt.encrypt.run(t).right.get)
34 |
35 | val search = CipherSearch.binarySearch(encryptedElements, crypt.decrypt)
36 |
37 | search("B").right.get shouldBe Found(1)
38 | search("D").right.get shouldBe Found(3)
39 | search("E").right.get shouldBe Found(4)
40 |
41 | search("0").right.get shouldBe InsertionPoint(0)
42 | search("BB").right.get shouldBe InsertionPoint(2)
43 | search("ZZ").right.get shouldBe InsertionPoint(5)
44 |
45 | }
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/signature/SignAlgo.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.signature
19 |
20 | import cats.data.Kleisli
21 | import fluence.crypto.{Crypto, KeyPair}
22 | import scodec.bits.ByteVector
23 |
24 | import scala.language.higherKinds
25 |
26 | /**
27 | * Signature algorithm -- cryptographically coupled keypair, signer and signature checker.
28 | *
29 | * @param name Algorithm name
30 | * @param generateKeyPair Keypair generator; note that you must ensure the seed entropy is secure
31 | * @param signer Signer for a given keypair
32 | * @param checker Checker for a given public key
33 | */
34 | case class SignAlgo(
35 | name: String,
36 | generateKeyPair: Crypto.KeyPairGenerator,
37 | signer: SignAlgo.SignerFn,
38 | implicit val checker: SignAlgo.CheckerFn
39 | )
40 |
41 | object SignAlgo {
42 | type SignerFn = KeyPair ⇒ Signer
43 |
44 | type CheckerFn = KeyPair.Public ⇒ SignatureChecker
45 |
46 | /**
47 | * For CheckerFn, builds a function that takes PubKeyAndSignature along with plain data, and checks the signature.
48 | */
49 | def checkerFunc(fn: CheckerFn): Crypto.Func[(PubKeyAndSignature, ByteVector), Unit] =
50 | Kleisli {
51 | case (pks, msg) ⇒
52 | fn(pks.publicKey).check.run(pks.signature -> msg)
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/hashsign/src/test/scala/fluence/crypto/HashSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.hash.CryptoHashers
21 | import org.scalatest.{Matchers, WordSpec}
22 | import scodec.bits.ByteVector
23 |
24 | class HashSpec extends WordSpec with Matchers {
25 | "jvm hasher" should {
26 | //test values get from third-party hash services
27 | "work with sha256" in {
28 | val str = "sha256Tester"
29 | val sha256TesterHex = "513c17f8cf6ba96ce412cc2ae82f68821e9a2c6ae7a2fb1f5e46d08c387c8e65"
30 |
31 | val hasher = CryptoHashers.Sha256
32 | ByteVector(hasher(str.getBytes()).right.get).toHex shouldBe sha256TesterHex
33 | }
34 |
35 | "work with sha1" in {
36 | val str = "sha1Tester"
37 | val sha1TesterHex = "879db20eabcecea7d4736a8bae5bc64564b76b2f"
38 |
39 | val hasher = CryptoHashers.Sha1
40 | ByteVector(hasher(str.getBytes()).right.get).toHex shouldBe sha1TesterHex
41 | }
42 |
43 | "check unsigned array with sha1" in {
44 |
45 | val arr = Array[Byte](3, -9, -31, 48, 10, 125, 51, -39, -20, -125, 123, 61, -36, 49, 76, 90, -16, 54, -61, 62, 50,
46 | -116, -37, -88, -125, -32, -105, 120, 118, 13, -37, 33, -36)
47 |
48 | val base64Check = "9keNwsj08vKTlwIpHAEYvsfpdP4="
49 |
50 | val hasher = CryptoHashers.Sha1
51 |
52 | ByteVector(hasher(arr).right.get).toBase64 shouldBe base64Check
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/facade/ecdsa/Elliptic.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.facade.ecdsa
19 |
20 | import scala.scalajs.js
21 | import scala.scalajs.js.annotation._
22 | import scala.scalajs.js.typedarray.Uint8Array
23 |
24 | //TODO hide enc argument in methods, make it `hex` by default
25 | /**
26 | * https://github.com/indutny/elliptic - fast elliptic-curve cryptography in a plain javascript implementation
27 | */
28 | @js.native
29 | @JSImport("elliptic", "ec")
30 | class EC(curve: String) extends js.Object {
31 | def genKeyPair(options: Option[js.Dynamic] = None): KeyPair = js.native
32 | def keyPair(options: js.Dynamic): KeyPair = js.native
33 | def keyFromPublic(pub: String, enc: String): KeyPair = js.native
34 | def keyFromPrivate(priv: String, enc: String): KeyPair = js.native
35 | }
36 |
37 | @js.native
38 | @JSImport("elliptic", "ec")
39 | class KeyPair(ec: EC, options: js.Dynamic) extends js.Object {
40 | def verify(msg: Uint8Array, signature: String): Boolean = js.native
41 | def sign(msg: Uint8Array): Signature = js.native
42 |
43 | def getPublic(compact: Boolean, enc: String): String = js.native
44 | def getPrivate(enc: String): String = js.native
45 | val priv: js.Any = js.native
46 | val pub: js.Any = js.native
47 | }
48 |
49 | @js.native
50 | @JSImport("elliptic", "ec")
51 | class Signature(der: String, enc: String = "hex") extends js.Object {
52 | def toDER(enc: String): String = js.native
53 | }
54 |
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/DumbCrypto.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import java.security.SecureRandom
21 |
22 | import cats.data.Kleisli
23 | import fluence.crypto.signature.{SignAlgo, Signature, SignatureChecker, Signer}
24 | import cats.syntax.either._
25 | import scodec.bits.ByteVector
26 |
27 | import scala.language.higherKinds
28 |
29 | object DumbCrypto {
30 |
31 | lazy val signAlgo: SignAlgo =
32 | SignAlgo(
33 | "dumb",
34 | Kleisli[Crypto.Result, Option[Array[Byte]], KeyPair] { seedOpt ⇒
35 | val seed = seedOpt.getOrElse {
36 | new SecureRandom().generateSeed(32)
37 | }
38 | KeyPair.fromBytes(seed, seed).asRight
39 | },
40 | keyPair ⇒
41 | Signer(
42 | keyPair.publicKey,
43 | Kleisli[Crypto.Result, ByteVector, Signature](plain ⇒ Signature(plain.reverse).asRight)
44 | ),
45 | publicKey ⇒
46 | SignatureChecker(
47 | Kleisli {
48 | case (sgn, msg) ⇒ Either.cond(sgn.sign == msg.reverse, (), CryptoError("Signatures mismatch"))
49 | }
50 | )
51 | )
52 |
53 | lazy val cipherString: Crypto.Cipher[String] =
54 | Crypto.Cipher(
55 | Kleisli[Crypto.Result, String, Array[Byte]](_.getBytes.asRight[CryptoError]),
56 | Kleisli[Crypto.Result, Array[Byte], String](bytes ⇒ new String(bytes).asRight[CryptoError])
57 | )
58 |
59 | lazy val noOpHasher: Crypto.Hasher[Array[Byte], Array[Byte]] =
60 | Kleisli[Crypto.Result, Array[Byte], Array[Byte]](_.asRight)
61 |
62 | lazy val testHasher: Crypto.Hasher[Array[Byte], Array[Byte]] =
63 | Kleisli[Crypto.Result, Array[Byte], Array[Byte]](bytes ⇒ ("H<" + new String(bytes) + ">").getBytes().asRight)
64 | }
65 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/hash/JsCryptoHasher.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.hash
19 |
20 | import cats.instances.either._
21 | import cats.syntax.either._
22 | import fluence.crypto.{Crypto, CryptoError}
23 | import fluence.crypto.facade.ecdsa.{SHA1, SHA256}
24 | import scodec.bits.ByteVector
25 |
26 | import scala.language.higherKinds
27 | import scala.scalajs.js
28 | import scala.scalajs.js.JSConverters._
29 | import scala.scalajs.js.typedarray.Uint8Array
30 |
31 | object JsCryptoHasher {
32 |
33 | lazy val Sha256: Crypto.Hasher[Array[Byte], Array[Byte]] =
34 | Crypto.tryFn[Array[Byte], Array[Byte]] { msg ⇒
35 | val sha256 = new SHA256()
36 | sha256.update(new Uint8Array(msg.toJSArray))
37 | ByteVector.fromValidHex(sha256.digest("hex")).toArray
38 | }("Cannot calculate Sha256 hash")
39 |
40 | lazy val Sha1: Crypto.Hasher[Array[Byte], Array[Byte]] =
41 | Crypto.tryFn[Array[Byte], Array[Byte]] { msg ⇒
42 | val sha1 = new SHA1()
43 | sha1.update(new Uint8Array(msg.toJSArray))
44 | ByteVector.fromValidHex(sha1.digest("hex")).toArray
45 | }("Cannot calculate Sha256 hash")
46 |
47 | /**
48 | * Calculates hash of message.
49 | *
50 | * @return hash in Scala array
51 | */
52 | val hash: Crypto.Func[(ByteVector, Option[Crypto.Hasher[Array[Byte], Array[Byte]]]), Array[Byte]] =
53 | Crypto {
54 | case (message, hasher) ⇒
55 | val arr = message.toArray
56 | hasher
57 | .fold(arr.asRight[CryptoError]) { h ⇒
58 | h(arr)
59 | }
60 | }
61 |
62 | /**
63 | * Calculates hash of message.
64 | *
65 | * @return hash in JS array
66 | */
67 | val hashJs: Crypto.Func[(ByteVector, Option[Crypto.Hasher[Array[Byte], Array[Byte]]]), js.Array[Byte]] =
68 | hash
69 | .map(_.toJSArray)
70 | }
71 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://travis-ci.org/fluencelabs/crypto)
2 |
3 | # Сrypto
4 |
5 | Cryptography for Scala and Scala.js, FP-flavoured.
6 |
7 | APIs are mostly based on [codec](https://github.com/fluencelabs/codec) approach with partial bijections, using `CryptoError` case class for errors.
8 |
9 | ## Submodules
10 |
11 | ### crypto-core
12 |
13 | Provides APIs and data types for various cryptographical operations, but without implementations.
14 |
15 | This library should be added as dependency to both implementations of crypto algorithms and on the user side, if particular app doesn't require a particular algorithm.
16 |
17 | ### crypto-hashsign
18 |
19 | Cross-platform hashing and signing algos.
20 |
21 | Use a `fluence.crypto.hash.CryptoHashers` to access a hashing algorithm. Currently `Sha1` and `Sha256` are provided.
22 |
23 | `fluence.crypto.ecdsa.Ecdsa.signAlgo` is an instance of `SignAlgo` with `ecdsa_secp256k1_sha256` under the hood.
24 |
25 | ### crypto-cipher
26 |
27 | Encryption and decryption algorithms, coded as arrows and bijections. Currently contains `AES` ciphering.
28 |
29 | ### crypto-keystore
30 |
31 | Provides a JSON format for serializing a keypair, using `codec-circe` for JSON processing.
32 |
33 | For Scala on JVM, storing on the disc is implemented with use of `cats-effect`.
34 |
35 | ### crypto-jwt
36 |
37 | Simplified JWT implementation, meaning a JSON-serialized header and claim with signature checking.
38 |
39 | `codec-circe` is used for JSON encoding/decoding, and `codec-bits` for binary data manipulations.
40 |
41 | ## Installation
42 |
43 | ```scala
44 | // Bintray repo is used so far. Migration to Maven Central is planned
45 | resolvers += Resolver.bintrayRepo("fluencelabs", "releases")
46 |
47 | val cryptoV = "0.0.3"
48 |
49 | libraryDependencies ++= Seq(
50 | "one.fluence" %%% "crypto-core" % cryptoV, // basic types and APIs
51 | "one.fluence" %%% "crypto-hashsign" % cryptoV, // hashers and signatures
52 | "one.fluence" %%% "crypto-cipher" % cryptoV, // encoding and decoding
53 | "one.fluence" %%% "crypto-keystore" % cryptoV, // serialize and store a keypair
54 | "one.fluence" %%% "crypto-jwt" % cryptoV // simple JWT implementation
55 | )
56 | ```
57 |
58 | ## License
59 |
60 | Fluence is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License v3 (AGPLv3) as published by the Free Software Foundation.
61 |
62 | Fluence includes some [external modules](https://github.com/fluencelabs/crypto/blob/master/build.sbt) that carry their own licensing.
--------------------------------------------------------------------------------
/core/src/main/scala/fluence/crypto/cipher/CipherSearch.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.cipher
19 |
20 | import cats.Monad
21 | import cats.data.Kleisli
22 | import fluence.crypto.Crypto
23 | import cats.instances.either._
24 | import cats.syntax.either._
25 |
26 | import scala.collection.Searching.{Found, InsertionPoint, SearchResult}
27 | import scala.language.higherKinds
28 |
29 | object CipherSearch {
30 |
31 | /**
32 | * Searches the specified indexedSeq for the search element using the binary search algorithm.
33 | * The sequence should be sorted with the same `Ordering` before calling, otherwise, the results are undefined.
34 | *
35 | * @param coll Ordered collection of encrypted elements to search in.
36 | * @param decrypt Decryption function for sequence elements.
37 | * @param ordering The ordering to be used to compare elements.
38 | *
39 | * @return A `Found` value containing the index corresponding to the search element in the
40 | * sequence. A `InsertionPoint` value containing the index where the element would be inserted if
41 | * the search element is not found in the sequence.
42 | */
43 | def binarySearch[A, B](coll: IndexedSeq[A], decrypt: Crypto.Func[A, B])(
44 | implicit ordering: Ordering[B]
45 | ): Crypto.Func[B, SearchResult] =
46 | Kleisli { input ⇒
47 | {
48 | implicitly[Monad[Crypto.Result]].tailRecM((0, coll.length)) {
49 | case (from, to) if from == to ⇒ Right(InsertionPoint(from)).asRight
50 | case (from, to) ⇒
51 | val idx = from + (to - from - 1) / 2
52 | decrypt(coll(idx)).map { d ⇒
53 | math.signum(ordering.compare(input, d)) match {
54 | case -1 ⇒ Left((from, idx))
55 | case 1 ⇒ Left((idx + 1, to))
56 | case _ ⇒ Right(Found(idx))
57 | }
58 | }
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/cipher/jvm/src/test/scala/fluence/crypto/AesSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.aes.{AesConfig, AesCrypt}
21 | import org.scalactic.source.Position
22 | import org.scalatest.{Assertion, Matchers, WordSpec}
23 | import scodec.bits.ByteVector
24 |
25 | import scala.util.{Random, Try}
26 |
27 | class AesSpec extends WordSpec with Matchers with slogging.LazyLogging {
28 |
29 | def rndString(size: Int): String = Random.nextString(10)
30 | val conf = AesConfig()
31 |
32 | "aes crypto" should {
33 | "work with IV" in {
34 |
35 | val pass = ByteVector("pass".getBytes())
36 | val crypt = AesCrypt.build(pass, withIV = true, config = conf)
37 |
38 | val str = rndString(200).getBytes
39 | val crypted = crypt.encrypt(str).right.get
40 | crypt.decrypt(crypted).right.get shouldBe str
41 | val fakeAes = AesCrypt.build(ByteVector("wrong".getBytes()), withIV = true, config = conf)
42 | checkCryptoError(fakeAes.decrypt(crypted))
43 |
44 | //we cannot check if first bytes is iv or already data, but encryption goes wrong
45 | val aesWithoutIV = AesCrypt.build(pass, withIV = false, config = conf)
46 | aesWithoutIV.decrypt(crypted).right.get shouldNot be(str)
47 |
48 | val aesWrongSalt = AesCrypt.build(pass, withIV = true, config = conf.copy(salt = rndString(10)))
49 | checkCryptoError(aesWrongSalt.decrypt(crypted))
50 | }
51 |
52 | "work without IV" in {
53 | val pass = ByteVector("pass".getBytes())
54 | val crypt = AesCrypt.build(pass, withIV = false, config = conf)
55 |
56 | val str = rndString(200).getBytes()
57 | val crypted = crypt.encrypt(str).right.get
58 | crypt.decrypt(crypted).right.get shouldBe str
59 |
60 | val fakeAes = AesCrypt.build(ByteVector("wrong".getBytes()), withIV = false, config = conf)
61 | checkCryptoError(fakeAes.decrypt(crypted))
62 |
63 | //we cannot check if first bytes is iv or already data, but encryption goes wrong
64 | val aesWithIV = AesCrypt.build(pass, withIV = true, config = conf)
65 | aesWithIV.decrypt(crypted).right.get shouldNot be(str)
66 |
67 | val aesWrongSalt = AesCrypt.build(pass, withIV = true, config = conf.copy(salt = rndString(10)))
68 | checkCryptoError(aesWrongSalt.decrypt(crypted))
69 | }
70 | }
71 |
72 | def checkCryptoError(tr: Crypto.Result[Array[Byte]])(implicit pos: Position): Assertion = {
73 | tr.isLeft shouldBe true
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/hashsign/src/test/scala/fluence/crypto/EcdsaSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.ecdsa.Ecdsa
21 | import fluence.crypto.signature.{SignAlgo, Signature}
22 | import org.scalatest.{Matchers, WordSpec}
23 | import scodec.bits.ByteVector
24 |
25 | import scala.util.{Random, Try}
26 |
27 | class EcdsaSpec extends WordSpec with Matchers {
28 |
29 | def rndBytes(size: Int): Array[Byte] = Random.nextString(10).getBytes
30 |
31 | def rndByteVector(size: Int) = ByteVector(rndBytes(size))
32 |
33 | "ecdsa algorithm" should {
34 | "correct sign and verify data" in {
35 | val algorithm: SignAlgo = Ecdsa.signAlgo
36 |
37 | val keys = algorithm.generateKeyPair(None).right.get
38 | val pubKey = keys.publicKey
39 | val data = rndByteVector(10)
40 | val sign = algorithm.signer(keys).sign(data).right.get
41 |
42 | algorithm.checker(pubKey).check((sign, data)).isRight shouldBe true
43 |
44 | val randomData = rndByteVector(10)
45 | val randomSign = algorithm.signer(keys).sign(randomData).right.get
46 |
47 | algorithm.checker(pubKey).check(randomSign -> data).isRight shouldBe false
48 |
49 | algorithm.checker(pubKey).check(sign -> randomData).isRight shouldBe false
50 | }
51 |
52 | "correctly work with signer and checker" in {
53 | val algo: SignAlgo = Ecdsa.signAlgo
54 | val keys = algo.generateKeyPair(None).right.get
55 | val signer = algo.signer(keys)
56 | val checker = algo.checker(keys.publicKey)
57 |
58 | val data = rndByteVector(10)
59 | val sign = signer.sign(data).right.get
60 |
61 | checker.check(sign -> data).isRight shouldBe true
62 |
63 | val randomSign = signer.sign(rndByteVector(10)).right.get
64 | checker.check(randomSign -> data).isRight shouldBe false
65 | }
66 |
67 | "throw an errors on invalid data" in {
68 | val algo: SignAlgo = Ecdsa.signAlgo
69 | val keys = algo.generateKeyPair(None).right.get
70 | val signer = algo.signer(keys)
71 | val checker = algo.checker(keys.publicKey)
72 | val data = rndByteVector(10)
73 |
74 | val sign = signer.sign(data).right.get
75 |
76 | the[CryptoError] thrownBy {
77 | checker.check(Signature(rndByteVector(10)) -> data).toTry.get
78 | }
79 | val invalidChecker = algo.checker(KeyPair.fromByteVectors(rndByteVector(10), rndByteVector(10)).publicKey)
80 | the[CryptoError] thrownBy {
81 | invalidChecker
82 | .check(sign -> data)
83 | .toTry
84 | .get
85 | }
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/hashsign/src/test/scala/fluence/crypto/Ed25519Spec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.eddsa.Ed25519
21 | import fluence.crypto.signature.{SignAlgo, Signature}
22 | import org.scalatest.{Matchers, WordSpec}
23 | import scodec.bits.ByteVector
24 |
25 | import scala.util.{Random, Try}
26 |
27 | class Ed25519Spec extends WordSpec with Matchers {
28 |
29 | def rndBytes(size: Int): Array[Byte] = Random.nextString(10).getBytes
30 |
31 | def rndByteVector(size: Int) = ByteVector(rndBytes(size))
32 |
33 | "ed25519 algorithm" should {
34 | "correct sign and verify data" in {
35 | val algorithm: SignAlgo = Ed25519.signAlgo
36 |
37 | val keys = algorithm.generateKeyPair(None).right.get
38 | val pubKey = keys.publicKey
39 | val data = rndByteVector(10)
40 | val sign = algorithm.signer(keys).sign(data).right.get
41 |
42 | algorithm.checker(pubKey).check(sign -> data).isRight shouldBe true
43 |
44 | val randomData = rndByteVector(10)
45 | val randomSign = algorithm.signer(keys).sign(randomData).right.get
46 |
47 | algorithm.checker(pubKey).check(randomSign -> data).contains(true) shouldBe false
48 |
49 | algorithm.checker(pubKey).check(sign -> randomData).contains(true) shouldBe false
50 | }
51 |
52 | "correctly work with signer and checker" in {
53 | val algo: SignAlgo = Ed25519.signAlgo
54 | val keys = algo.generateKeyPair(None).right.get
55 | val signer = algo.signer(keys)
56 | val checker = algo.checker(keys.publicKey)
57 |
58 | val data = rndByteVector(10)
59 | val sign = signer.sign(data).right.get
60 |
61 | checker.check(sign -> data).isRight shouldBe true
62 |
63 | val randomSign = signer.sign(rndByteVector(10)).right.get
64 | checker.check(randomSign, data).contains(true) shouldBe false
65 | }
66 |
67 | "throw an errors on invalid data" in {
68 | val algo: SignAlgo = Ed25519.signAlgo
69 | val keys = algo.generateKeyPair(None).right.get
70 | val signer = algo.signer(keys)
71 | val checker = algo.checker(keys.publicKey)
72 | val data = rndByteVector(10)
73 |
74 | val sign = signer.sign(data).right.get
75 |
76 | the[CryptoError] thrownBy {
77 | checker.check(Signature(rndByteVector(10)), data).toTry.get
78 | }
79 | val invalidChecker = algo.checker(KeyPair.fromByteVectors(rndByteVector(10), rndByteVector(10)).publicKey)
80 | the[CryptoError] thrownBy {
81 | invalidChecker
82 | .check(sign, data)
83 | .toTry
84 | .get
85 | }
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/cipher/js/src/test/scala/fluence/crypto/AesJSSpec.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto
19 |
20 | import fluence.crypto.aes.{AesConfig, AesCrypt}
21 | import org.scalactic.source.Position
22 | import org.scalatest.{Assertion, Matchers, WordSpec}
23 | import scodec.bits.ByteVector
24 |
25 | import scala.util.{Random, Try}
26 |
27 | class AesJSSpec extends WordSpec with Matchers with slogging.LazyLogging {
28 |
29 | def rndString(size: Int): String = Random.nextString(10)
30 |
31 | val conf = AesConfig()
32 |
33 | // TODO: use properties testing
34 | "aes crypto" should {
35 | "work with IV" in {
36 | val pass = ByteVector("pass".getBytes())
37 | val crypt = AesCrypt.build(pass, withIV = true, config = conf)
38 |
39 | val str = rndString(200).getBytes()
40 | val crypted = crypt.encrypt(str).right.get
41 | crypt.decrypt(crypted).right.get shouldBe str
42 |
43 | val fakeAes = AesCrypt.build(ByteVector("wrong".getBytes()), withIV = true, config = conf)
44 | checkCryptoError(fakeAes.decrypt(crypted), str)
45 |
46 | //we cannot check if first bytes is iv or already data, but encryption goes wrong
47 | val aesWithoutIV = AesCrypt.build(pass, withIV = false, config = conf)
48 | aesWithoutIV.decrypt(crypted).right.get shouldNot be(str)
49 |
50 | val aesWrongSalt = AesCrypt.build(pass, withIV = true, config = conf.copy(salt = rndString(10)))
51 | checkCryptoError(aesWrongSalt.decrypt(crypted), str)
52 | }
53 |
54 | "work without IV" in {
55 | val pass = ByteVector("pass".getBytes())
56 | val crypt = AesCrypt.build(pass, withIV = false, config = conf)
57 |
58 | val str = rndString(200).getBytes()
59 | val crypted = crypt.encrypt(str).right.get
60 | crypt.decrypt(crypted).right.get shouldBe str
61 |
62 | val fakeAes = AesCrypt.build(ByteVector("wrong".getBytes()), withIV = false, config = conf)
63 | checkCryptoError(fakeAes.decrypt(crypted), str)
64 |
65 | //we cannot check if first bytes is iv or already data, but encryption goes wrong
66 | val aesWithIV = AesCrypt.build(pass, withIV = true, config = conf)
67 | aesWithIV.decrypt(crypted).right.get shouldNot be(str)
68 |
69 | val aesWrongSalt = AesCrypt.build(pass, withIV = false, config = conf.copy(salt = rndString(10)))
70 | checkCryptoError(aesWrongSalt.decrypt(crypted), str)
71 | }
72 |
73 | /**
74 | * Checks if there is a crypto error or result is not equal with source result.
75 | */
76 | def checkCryptoError(tr: Crypto.Result[Array[Byte]], msg: Array[Byte])(implicit pos: Position): Assertion = {
77 | tr.map { r ⇒
78 | !(r sameElements msg)
79 | }.fold(
80 | _ ⇒ true,
81 | res => res
82 | ) shouldBe true
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/eddsa/Ed25519.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.eddsa
19 |
20 | import fluence.crypto.facade.ed25519.Supercop
21 | import fluence.crypto.hash.JsCryptoHasher
22 | import fluence.crypto.{Crypto, CryptoError, CryptoJsHelpers, KeyPair}
23 | import fluence.crypto.signature.{SignAlgo, Signature, SignatureChecker, Signer}
24 | import scodec.bits.ByteVector
25 |
26 | import scala.language.higherKinds
27 |
28 | class Ed25519(hasher: Option[Crypto.Hasher[Array[Byte], Array[Byte]]]) {
29 |
30 | import CryptoJsHelpers._
31 |
32 | val sign: Crypto.Func[(KeyPair, ByteVector), Signature] =
33 | Crypto {
34 | case (keyPair, message) ⇒
35 | for {
36 | hash ← JsCryptoHasher.hash(message, hasher)
37 | sign ← Crypto.tryUnit {
38 | Supercop.sign(
39 | ByteVector(hash).toJsBuffer,
40 | keyPair.publicKey.value.toJsBuffer,
41 | keyPair.secretKey.value.toJsBuffer
42 | )
43 | }("Error on signing message by js/ed25519 signature")
44 | } yield Signature(ByteVector.fromValidHex(sign.toString("hex")))
45 | }
46 |
47 | val verify: Crypto.Func[(KeyPair.Public, Signature, ByteVector), Unit] =
48 | Crypto {
49 | case (
50 | pubKey,
51 | signature,
52 | message
53 | ) ⇒
54 | for {
55 | hash ← JsCryptoHasher.hash(message, hasher)
56 | verify ← Crypto.tryUnit(
57 | Supercop.verify(signature.sign.toJsBuffer, ByteVector(hash).toJsBuffer, pubKey.value.toJsBuffer)
58 | )("Cannot verify message")
59 | _ ← Either.cond(verify, (), CryptoError("Signature is not verified"))
60 | } yield ()
61 | }
62 |
63 | val generateKeyPair: Crypto.KeyPairGenerator =
64 | Crypto[Option[Array[Byte]], KeyPair] { input ⇒
65 | for {
66 | seed ← Crypto.tryUnit(input.map(ByteVector(_).toJsBuffer).getOrElse(Supercop.createSeed()))(
67 | "Error on seed creation"
68 | )
69 | jsKeyPair ← Crypto.tryUnit(Supercop.createKeyPair(seed))("Error on key pair generation.")
70 | keyPair ← Crypto.tryUnit(
71 | KeyPair.fromByteVectors(
72 | ByteVector.fromValidHex(jsKeyPair.publicKey.toString("hex")),
73 | ByteVector.fromValidHex(jsKeyPair.secretKey.toString("hex"))
74 | )
75 | )("Error on decoding public and secret keys")
76 | } yield keyPair
77 | }
78 | }
79 |
80 | object Ed25519 {
81 |
82 | val ed25519: Ed25519 = new Ed25519(None)
83 |
84 | val signAlgo: SignAlgo =
85 | SignAlgo(
86 | name = "ed25519",
87 | generateKeyPair = ed25519.generateKeyPair,
88 | signer = kp ⇒
89 | Signer(
90 | kp.publicKey,
91 | ed25519.sign.local(kp -> _)
92 | ),
93 | checker = pk ⇒
94 | SignatureChecker(
95 | ed25519.verify.local {
96 | case (signature, plain) ⇒ (pk, signature, plain)
97 | }
98 | )
99 | )
100 |
101 | }
102 |
--------------------------------------------------------------------------------
/hashsign/js/src/main/scala/fluence/crypto/ecdsa/Ecdsa.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.ecdsa
19 |
20 | import fluence.crypto._
21 | import fluence.crypto.facade.ecdsa.EC
22 | import fluence.crypto.hash.JsCryptoHasher
23 | import fluence.crypto.signature.{SignAlgo, Signature, SignatureChecker, Signer}
24 | import scodec.bits.ByteVector
25 |
26 | import scala.language.higherKinds
27 | import scala.scalajs.js
28 | import scala.scalajs.js.JSConverters._
29 | import scala.scalajs.js.typedarray.Uint8Array
30 |
31 | /**
32 | * Return in all js methods hex, because in the other case we will receive javascript objects
33 | * @param ec implementation of ecdsa logic for different curves
34 | */
35 | class Ecdsa(ec: EC, hasher: Option[Crypto.Hasher[Array[Byte], Array[Byte]]]) {
36 |
37 | /**
38 | * Restores key pair by secret key.
39 | *
40 | */
41 | val restoreKeyPair: Crypto.Func[KeyPair.Secret, KeyPair] =
42 | Crypto.tryFn[KeyPair.Secret, KeyPair] { secretKey ⇒
43 | val key = ec.keyFromPrivate(secretKey.value.toHex, "hex")
44 | val publicHex = key.getPublic(compact = true, "hex")
45 | val secretHex = key.getPrivate("hex")
46 | val public = ByteVector.fromValidHex(publicHex)
47 | val secret = ByteVector.fromValidHex(secretHex)
48 | KeyPair.fromByteVectors(public, secret)
49 | }("Incorrect secret key format")
50 |
51 | val generateKeyPair: Crypto.KeyPairGenerator =
52 | Crypto.tryFn[Option[Array[Byte]], KeyPair] { input ⇒
53 | val seedJs = input.map(bs ⇒ js.Dynamic.literal(entropy = bs.toJSArray))
54 | val key = ec.genKeyPair(seedJs)
55 | val publicHex = key.getPublic(compact = true, "hex")
56 | val secretHex = key.getPrivate("hex")
57 | val public = ByteVector.fromValidHex(publicHex)
58 | val secret = ByteVector.fromValidHex(secretHex)
59 | KeyPair.fromByteVectors(public, secret)
60 | }("Failed to generate key pair")
61 |
62 | val sign: Crypto.Func[(KeyPair, ByteVector), Signature] =
63 | Crypto {
64 | case (keyPair: KeyPair, message: ByteVector) ⇒
65 | for {
66 | secret ← Crypto.tryUnit {
67 | ec.keyFromPrivate(keyPair.secretKey.value.toHex, "hex")
68 | }("Cannot get private key from key pair")
69 | hash ← JsCryptoHasher.hashJs(message, hasher)
70 | signHex ← Crypto.tryUnit(secret.sign(new Uint8Array(hash)).toDER("hex"))("Cannot sign message")
71 | } yield Signature(ByteVector.fromValidHex(signHex))
72 | }
73 |
74 | val verify: Crypto.Func[(KeyPair.Public, Signature, ByteVector), Unit] =
75 | Crypto {
76 | case (
77 | pubKey,
78 | signature,
79 | message
80 | ) ⇒
81 | for {
82 | public ← Crypto.tryUnit {
83 | val hex = pubKey.value.toHex
84 | ec.keyFromPublic(hex, "hex")
85 | }("Incorrect public key format.")
86 | hash ← JsCryptoHasher.hashJs(message, hasher)
87 | verify ← Crypto.tryUnit(public.verify(new Uint8Array(hash), signature.sign.toHex))("Cannot verify message")
88 | _ ← Either.cond(verify, (), CryptoError("Signature is not verified"))
89 | } yield ()
90 | }
91 |
92 | }
93 |
94 | object Ecdsa {
95 | val ecdsa_secp256k1_sha256 = new Ecdsa(new EC("secp256k1"), Some(JsCryptoHasher.Sha256))
96 |
97 | val signAlgo: SignAlgo = SignAlgo(
98 | "ecdsa/secp256k1/sha256/js",
99 | generateKeyPair = ecdsa_secp256k1_sha256.generateKeyPair,
100 | signer = kp ⇒
101 | Signer(
102 | kp.publicKey,
103 | ecdsa_secp256k1_sha256.sign.local(kp -> _)
104 | ),
105 | checker = pk ⇒
106 | SignatureChecker(
107 | ecdsa_secp256k1_sha256.verify.local {
108 | case (signature, plain) ⇒ (pk, signature, plain)
109 | }
110 | )
111 | )
112 | }
113 |
--------------------------------------------------------------------------------
/cipher/js/src/main/scala/fluence/crypto/aes/AesCrypt.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.aes
19 |
20 | import fluence.crypto.facade.cryptojs.{CryptOptions, CryptoJS, Key, KeyOptions}
21 | import fluence.crypto.{Crypto, CryptoError}
22 | import scodec.bits.ByteVector
23 |
24 | import scala.language.higherKinds
25 | import scala.scalajs.js.JSConverters._
26 | import scala.scalajs.js.typedarray.Int8Array
27 |
28 | class AesCrypt(password: Array[Char], withIV: Boolean, config: AesConfig) {
29 |
30 | private val salt = config.salt
31 |
32 | private val rndStr = CryptoJS.lib.WordArray
33 |
34 | //number of password hashing iterations
35 | private val iterationCount = config.iterationCount
36 | //initialisation vector must be the same length as block size
37 | private val IV_SIZE = 16
38 | private val BITS = 256
39 | //generate IV in hex
40 | private def generateIV = rndStr.random(IV_SIZE)
41 |
42 | private val pad = CryptoJS.pad.Pkcs7
43 | private val mode = CryptoJS.mode.CBC
44 | private val aes = CryptoJS.AES
45 |
46 | /**
47 | * Encrypt data.
48 | * data Data to encrypt
49 | * key Salted and hashed password
50 | * @return Encrypted data with IV
51 | */
52 | private val encryptData =
53 | Crypto.tryFn[(Array[Byte], Key), Array[Byte]] {
54 | case (data: Array[Byte], key: Key) ⇒
55 | //transform data to JS type
56 | val wordArray = CryptoJS.lib.WordArray.create(new Int8Array(data.toJSArray))
57 | val iv = if (withIV) Some(generateIV) else None
58 | val cryptOptions = CryptOptions(iv = iv, padding = pad, mode = mode)
59 | //encryption return base64 string, transform it to byte array
60 | val crypted = ByteVector.fromValidBase64(aes.encrypt(wordArray, key, cryptOptions).toString)
61 | //IV also needs to be transformed in byte array
62 | val byteIv = iv.map(i ⇒ ByteVector.fromValidHex(i.toString))
63 | byteIv.map(_.toArray ++ crypted.toArray).getOrElse(crypted.toArray)
64 | }("Cannot encrypt data")
65 |
66 | private val decryptData: Crypto.Func[(Key, String, Option[String]), ByteVector] =
67 | Crypto.tryFn[(Key, String, Option[String]), ByteVector] {
68 | case (key: Key, base64Data: String, iv: Option[String]) ⇒
69 | //parse IV to WordArray JS format
70 | val cryptOptions = CryptOptions(iv = iv.map(i ⇒ CryptoJS.enc.Hex.parse(i)), padding = pad, mode = mode)
71 | val dec = aes.decrypt(base64Data, key, cryptOptions)
72 | ByteVector.fromValidHex(dec.toString)
73 | }("Cannot decrypt data")
74 |
75 | /**
76 | * cipherText Encrypted data with IV
77 | * @return IV in hex and data in base64
78 | */
79 | private val detachData: Crypto.Func[Array[Byte], (Option[String], String)] =
80 | Crypto.tryFn { cipherText: Array[Byte] ⇒
81 | val dataWithParams = if (withIV) {
82 | val ivDec = ByteVector(cipherText.slice(0, IV_SIZE)).toHex
83 | val encMessage = cipherText.slice(IV_SIZE, cipherText.length)
84 | (Some(ivDec), encMessage)
85 | } else (None, cipherText)
86 | val (ivOp, data) = dataWithParams
87 | val base64 = ByteVector(data).toBase64
88 | (ivOp, base64)
89 | }("Cannot detach data and IV")
90 |
91 | /**
92 | * Hash password with salt `iterationCount` times
93 | */
94 | private val initSecretKey: Crypto.Func[Unit, Key] =
95 | Crypto.tryFn { _: Unit ⇒
96 | // get raw key from password and salt
97 | val keyOption = KeyOptions(BITS, iterations = iterationCount, hasher = CryptoJS.algo.SHA256)
98 | CryptoJS.PBKDF2(new String(password), salt, keyOption)
99 | }("Cannot init secret key")
100 |
101 | val decrypt: Crypto.Func[Array[Byte], Array[Byte]] =
102 | Crypto { input ⇒
103 | for {
104 | detachedData ← detachData(input)
105 | (iv, base64) = detachedData
106 | key ← initSecretKey(())
107 | decData ← decryptData((key, base64, iv))
108 | _ ← Crypto[Boolean, Unit](Either.cond(_, (), CryptoError("Cannot decrypt message with this password.")))(
109 | decData.nonEmpty
110 | )
111 | } yield decData.toArray
112 | }
113 |
114 | val encrypt: Crypto.Func[Array[Byte], Array[Byte]] =
115 | Crypto[Array[Byte], Array[Byte]] { input ⇒
116 | for {
117 | key ← initSecretKey(())
118 | encrypted ← encryptData(input -> key)
119 | } yield encrypted
120 | }
121 | }
122 |
123 | object AesCrypt {
124 |
125 | def build(password: ByteVector, withIV: Boolean, config: AesConfig): Crypto.Cipher[Array[Byte]] = {
126 | val aes = new AesCrypt(password.toHex.toCharArray, withIV, config)
127 | Crypto.Cipher(aes.encrypt, aes.decrypt)
128 | }
129 |
130 | }
131 |
--------------------------------------------------------------------------------
/FluenceCLA.md:
--------------------------------------------------------------------------------
1 | Thank you for your interest in Fluence Labs projects.
2 |
3 | In order to clarify the intellectual property license
4 | granted with Contributions from any person or entity, Fluence Labs
5 | must have a Contributor License Agreement ("CLA") on file that has
6 | been signed by each Contributor, indicating agreement to the license
7 | terms below. This license is for your protection as a Contributor as
8 | well as the protection of Fluence Labs and its users; it does not
9 | change your rights to use your own Contributions for any other purpose.
10 | This contribution license is based on the Apache Contribution License
11 | for individuals.
12 |
13 | Please read this document carefully before signing and keep a copy
14 | for your records.
15 |
16 | You accept and agree to the following terms and conditions for Your
17 | present and future Contributions submitted to Fluence Labs. Except
18 | for the license granted herein to Fluence Labs and recipients of
19 | software distributed by Fluence Labs, You reserve all right, title,
20 | and interest in and to Your Contributions.
21 |
22 | 1. Definitions.
23 | "You" (or "Your") shall mean the copyright owner or legal entity
24 | authorized by the copyright owner that is making this Agreement
25 | with Fluence Labs. For legal entities, the entity making a
26 | Contribution and all other entities that control, are controlled
27 | by, or are under common control with that entity are considered to
28 | be a single Contributor. For the purposes of this definition,
29 | "control" means (i) the power, direct or indirect, to cause the
30 | direction or management of such entity, whether by contract or
31 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
32 | outstanding shares, or (iii) beneficial ownership of such entity.
33 | "Contribution" shall mean any original work of authorship,
34 | including any modifications or additions to an existing work, that
35 | is intentionally submitted by You to Fluence Labs for inclusion
36 | in, or documentation of, any of the products owned or managed by
37 | Fluence Labs (the "Work"). For the purposes of this definition,
38 | "submitted" means any form of electronic, verbal, or written
39 | communication sent to Fluence Labs or its representatives,
40 | including but not limited to communication on electronic mailing
41 | lists, source code control systems, and issue tracking systems that
42 | are managed by, or on behalf of, Fluence Labs for the purpose of
43 | discussing and improving the Work, but excluding communication that
44 | is conspicuously marked or otherwise designated in writing by You
45 | as "Not a Contribution."
46 |
47 | 2. Grant of Copyright License. Subject to the terms and conditions of
48 | this Agreement, You hereby grant to Fluence Labs and to
49 | recipients of software distributed by Fluence Labs a perpetual,
50 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
51 | copyright license to reproduce, prepare derivative works of,
52 | publicly display, publicly perform, sublicense, and distribute Your
53 | Contributions and such derivative works.
54 |
55 | 3. Grant of Patent License. Subject to the terms and conditions of
56 | this Agreement, You hereby grant to Fluence Labs and to
57 | recipients of software distributed by Fluence Labs a perpetual,
58 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
59 | (except as stated in this section) patent license to make, have
60 | made, use, offer to sell, sell, import, and otherwise transfer the
61 | Work, where such license applies only to those patent claims
62 | licensable by You that are necessarily infringed by Your
63 | Contribution(s) alone or by combination of Your Contribution(s)
64 | with the Work to which such Contribution(s) was submitted. If any
65 | entity institutes patent litigation against You or any other entity
66 | (including a cross-claim or counterclaim in a lawsuit) alleging
67 | that your Contribution, or the Work to which you have contributed,
68 | constitutes direct or contributory patent infringement, then any
69 | patent licenses granted to that entity under this Agreement for
70 | that Contribution or Work shall terminate as of the date such
71 | litigation is filed.
72 |
73 | 4. You represent that you are legally entitled to grant the above
74 | license. If your employer(s) has rights to intellectual property
75 | that you create that includes your Contributions, you represent
76 | that you have received permission to make Contributions on behalf
77 | of that employer, that your employer has waived such rights for
78 | your Contributions to Fluence Labs, or that your employer has
79 | executed a separate Corporate CLA with Fluence Labs.
80 |
81 | 5. You represent that each of Your Contributions is Your original
82 | creation (see section 7 for submissions on behalf of others). You
83 | represent that Your Contribution submissions include complete
84 | details of any third-party license or other restriction (including,
85 | but not limited to, related patents and trademarks) of which you
86 | are personally aware and which are associated with any part of Your
87 | Contributions.
88 |
89 | 6. You are not expected to provide support for Your Contributions,
90 | except to the extent You desire to provide support. You may provide
91 | support for free, for a fee, or not at all. Unless required by
92 | applicable law or agreed to in writing, You provide Your
93 | Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
94 | OF ANY KIND, either express or implied, including, without
95 | limitation, any warranties or conditions of TITLE, NON
96 | INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
97 |
98 | 7. Should You wish to submit work that is not Your original creation,
99 | You may submit it to Fluence Labs separately from any
100 | Contribution, identifying the complete details of its source and of
101 | any license or other restriction (including, but not limited to,
102 | related patents, trademarks, and license agreements) of which you
103 | are personally aware, and conspicuously marking the work as
104 | "Submitted on behalf of a third-party: [named here]".
105 |
106 | 8. You agree to notify Fluence Labs of any facts or circumstances of
107 | which you become aware that would make these representations
108 | inaccurate in any respect.
109 |
110 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/main/scala/fluence/crypto/eddsa/Ed25519.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.eddsa
19 |
20 | import java.security._
21 |
22 | import cats.syntax.either._
23 | import cats.instances.either._
24 | import cats.syntax.functor._
25 | import fluence.crypto.KeyPair.Secret
26 | import fluence.crypto.signature.{SignAlgo, SignatureChecker, Signer}
27 | import fluence.crypto.{KeyPair, _}
28 | import org.bouncycastle.crypto.{AsymmetricCipherKeyPair, KeyGenerationParameters}
29 | import org.bouncycastle.crypto.generators.Ed25519KeyPairGenerator
30 | import org.bouncycastle.crypto.params.{Ed25519PrivateKeyParameters, Ed25519PublicKeyParameters}
31 | import org.bouncycastle.crypto.signers.Ed25519Signer
32 | import scodec.bits.ByteVector
33 |
34 | import scala.language.higherKinds
35 |
36 | /**
37 | * Edwards-curve Digital Signature Algorithm (EdDSA)
38 | */
39 | class Ed25519(strength: Int) extends JavaAlgorithm {
40 |
41 | /**
42 | * Restores pair of keys from the known secret key.
43 | * The public key will be the same each method call with the same secret key.
44 | * sk secret key
45 | * @return key pair
46 | */
47 | val restorePairFromSecret: Crypto.Func[Secret, KeyPair] =
48 | Crypto.tryFn[Secret, KeyPair] { sk ⇒
49 | val secret = new Ed25519PrivateKeyParameters(sk.bytes, 0)
50 | KeyPair.fromBytes(secret.generatePublicKey().getEncoded, sk.bytes)
51 | }("Could not generate KeyPair from private key")
52 |
53 | private val signMessage: Crypto.Func[(Array[Byte], Array[Byte]), Array[Byte]] =
54 | Crypto.tryFn[(Array[Byte], Array[Byte]), Array[Byte]] {
55 | case (
56 | privateKey,
57 | message
58 | ) ⇒
59 | val privKey = new Ed25519PrivateKeyParameters(privateKey, 0)
60 | val signer = new Ed25519Signer
61 | signer.init(true, privKey)
62 | signer.update(message, 0, message.length)
63 | signer.generateSignature()
64 | }("Cannot sign message")
65 |
66 | val sign: Crypto.Func[(KeyPair, ByteVector), signature.Signature] =
67 | signMessage
68 | .map(bb ⇒ fluence.crypto.signature.Signature(ByteVector(bb)))
69 | .local {
70 | case (keyPair, message) ⇒
71 | keyPair.secretKey.bytes -> message.toArray
72 | }
73 |
74 | private val verifySign: Crypto.Func[(Array[Byte], Array[Byte], Array[Byte]), Unit] =
75 | Crypto.tryFn[(Array[Byte], Array[Byte], Array[Byte]), Boolean] {
76 | case (
77 | publicKey,
78 | signature,
79 | message
80 | ) ⇒
81 | val pubKey = new Ed25519PublicKeyParameters(publicKey, 0)
82 | val signer = new Ed25519Signer
83 | signer.init(false, pubKey)
84 | signer.update(message, 0, message.length)
85 | signer.verifySignature(signature)
86 | }("Cannot verify message") andThen Crypto.cond((), "Signature is not verified")
87 |
88 | val verify: Crypto.Func[(KeyPair.Public, signature.Signature, ByteVector), Unit] =
89 | verifySign.local {
90 | case (
91 | publicKey,
92 | signature,
93 | message
94 | ) ⇒
95 | (publicKey.bytes, signature.bytes, message.toArray)
96 | }
97 |
98 | private def getKeyPairGenerator =
99 | Crypto.tryUnit(
100 | new Ed25519KeyPairGenerator()
101 | )(
102 | "Cannot get key pair generator"
103 | )
104 |
105 | val generateKeyPair: Crypto.KeyPairGenerator =
106 | Crypto[Option[Array[Byte]], KeyPair] { input ⇒
107 | getKeyPairGenerator.flatMap { g ⇒
108 | val random = input.map(new SecureRandom(_)).getOrElse(new SecureRandom())
109 | val keyParameters = new KeyGenerationParameters(random, strength)
110 | g.init(keyParameters)
111 | Either.fromOption(Option(g.generateKeyPair()), CryptoError("Generated keypair is null"))
112 | }.flatMap(
113 | (p: AsymmetricCipherKeyPair) ⇒
114 | Crypto.tryUnit {
115 | val pk = p.getPublic match {
116 | case pk: Ed25519PublicKeyParameters => pk.getEncoded
117 | case p =>
118 | throw new ClassCastException(s"Cannot cast public key (${p.getClass}) to Ed25519PublicKeyParameters")
119 | }
120 | val sk = p.getPrivate match {
121 | case sk: Ed25519PrivateKeyParameters => sk.getEncoded
122 | case s =>
123 | throw new ClassCastException(s"Cannot cast private key (${p.getClass}) to Ed25519PrivateKeyParameters")
124 | }
125 | KeyPair.fromBytes(pk, sk)
126 | }("Could not generate KeyPair")
127 | )
128 | }
129 | }
130 |
131 | object Ed25519 {
132 |
133 | /**
134 | * Keys in tendermint are generating with a random seed of 32 bytes
135 | */
136 | val ed25519 = new Ed25519(256)
137 | val signAlgo: SignAlgo = signAlgoInit(256)
138 |
139 | /**
140 | *
141 | * @param strength the size, in bits, of the keys we want to produce
142 | */
143 | def ed25519Init(strength: Int) = new Ed25519(strength)
144 |
145 | /**
146 | *
147 | * @param strength the size, in bits, of the keys we want to produce
148 | */
149 | def signAlgoInit(strength: Int): SignAlgo = {
150 | val algo = ed25519Init(strength)
151 | SignAlgo(
152 | name = "ed25519",
153 | generateKeyPair = algo.generateKeyPair,
154 | signer = kp ⇒
155 | Signer(
156 | kp.publicKey,
157 | Crypto[ByteVector, signature.Signature] { input ⇒
158 | algo.sign(kp -> input)
159 | }
160 | ),
161 | checker = pk ⇒
162 | SignatureChecker(
163 | Crypto {
164 | case (signature, plain) ⇒
165 | algo.verify(pk, signature, plain)
166 | }
167 | )
168 | )
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/cipher/jvm/src/main/scala/fluence/crypto/aes/AesCrypt.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.aes
19 |
20 | import cats.instances.either._
21 | import fluence.crypto.{Crypto, JavaAlgorithm}
22 | import org.bouncycastle.crypto.digests.SHA256Digest
23 | import org.bouncycastle.crypto.engines.AESEngine
24 | import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator
25 | import org.bouncycastle.crypto.modes.CBCBlockCipher
26 | import org.bouncycastle.crypto.paddings.{PKCS7Padding, PaddedBufferedBlockCipher}
27 | import org.bouncycastle.crypto.params.{KeyParameter, ParametersWithIV}
28 | import org.bouncycastle.crypto.{CipherParameters, PBEParametersGenerator}
29 | import scodec.bits.ByteVector
30 |
31 | import scala.language.higherKinds
32 | import scala.util.Random
33 |
34 | case class DetachedData(ivData: Array[Byte], encData: Array[Byte])
35 | case class DataWithParams(data: Array[Byte], params: CipherParameters)
36 |
37 | /**
38 | * PBEWithSHA256And256BitAES-CBC-BC cryptography
39 | * PBE - Password-based encryption
40 | * SHA256 - hash for password
41 | * AES with CBC BC - Advanced Encryption Standard with Cipher Block Chaining
42 | * https://ru.wikipedia.org/wiki/Advanced_Encryption_Standard
43 | * https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_(CBC)
44 | * @param password User entered password
45 | * @param withIV Initialization vector to achieve semantic security, a property whereby repeated usage of the scheme
46 | * under the same key does not allow an attacker to infer relationships between segments of the encrypted
47 | * message
48 | */
49 | class AesCrypt(password: Array[Char], withIV: Boolean, config: AesConfig) extends JavaAlgorithm {
50 |
51 | private val rnd = Random
52 | private val salt = config.salt.getBytes()
53 |
54 | //number of password hashing iterations
55 | private val iterationCount = config.iterationCount
56 | //initialisation vector must be the same length as block size
57 | private val IV_SIZE = 16
58 | private val BITS = 256
59 | private def generateIV: Array[Byte] = {
60 | val iv = new Array[Byte](IV_SIZE)
61 | rnd.nextBytes(iv)
62 | iv
63 | }
64 |
65 | /**
66 | * Key spec initialization
67 | */
68 | private val initSecretKey: Crypto.Func[( /*password*/ Array[Char], /*salt*/ Array[Byte]), Array[Byte]] =
69 | Crypto.tryFn[(Array[Char], Array[Byte]), Array[Byte]] {
70 | case (password, salt) ⇒
71 | PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password)
72 | }("Cannot init secret key")
73 |
74 | /**
75 | * Setup AES CBC cipher
76 | * encrypt: True for encryption and false for decryption
77 | *
78 | * @return cipher
79 | */
80 | private val setupAesCipher: Crypto.Func[(CipherParameters, Boolean), PaddedBufferedBlockCipher] =
81 | Crypto.tryFn[(CipherParameters, Boolean), PaddedBufferedBlockCipher] {
82 | case (params, encrypt) ⇒
83 | // setup AES cipher in CBC mode with PKCS7 padding
84 | val padding = new PKCS7Padding
85 | val cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine), padding)
86 | cipher.reset()
87 | cipher.init(encrypt, params)
88 |
89 | cipher
90 | }("Cannot setup aes cipher")
91 |
92 | private val cipherBytes: Crypto.Func[(Array[Byte], PaddedBufferedBlockCipher), Array[Byte]] =
93 | Crypto.tryFn[(Array[Byte], PaddedBufferedBlockCipher), Array[Byte]] {
94 | case (data, cipher) ⇒
95 | // create a temporary buffer to decode into (it'll include padding)
96 | val buf = new Array[Byte](cipher.getOutputSize(data.length))
97 | val outputLength = cipher.processBytes(data, 0, data.length, buf, 0)
98 | val lastBlockLength = cipher.doFinal(buf, outputLength)
99 | //remove padding
100 | buf.slice(0, outputLength + lastBlockLength)
101 | }("Error in cipher processing")
102 |
103 | /**
104 | *
105 | * dataWithParams Cata with cipher parameters
106 | * addData Additional data (nonce)
107 | * encrypt True for encryption and false for decryption
108 | * @return Crypted bytes
109 | */
110 | private val processData: Crypto.Func[(DataWithParams, Option[Array[Byte]], Boolean), Array[Byte]] =
111 | Crypto {
112 | case (dataWithParams, addData, encrypt) ⇒
113 | for {
114 | cipher ← setupAesCipher(dataWithParams.params -> encrypt)
115 | buf ← cipherBytes(dataWithParams.data, cipher)
116 | } yield addData.map(_ ++ buf).getOrElse(buf)
117 | }
118 |
119 | /**
120 | * encrypted data = initialization vector + data
121 | */
122 | private val detachIV: Crypto.Func[(Array[Byte], Int), DetachedData] =
123 | Crypto.tryFn[(Array[Byte], Int), DetachedData] {
124 | case (data, ivSize) ⇒
125 | val ivData = data.slice(0, ivSize)
126 | val encData = data.slice(ivSize, data.length)
127 | DetachedData(ivData, encData)
128 | }("Cannot detach data and IV")
129 |
130 | private val params: Crypto.Func[Array[Byte], KeyParameter] =
131 | Crypto.tryFn { key: Array[Byte] ⇒
132 | val pGen = new PKCS5S2ParametersGenerator(new SHA256Digest)
133 | pGen.init(key, salt, iterationCount)
134 |
135 | pGen.generateDerivedParameters(BITS).asInstanceOf[KeyParameter]
136 | }("Cannot generate key parameters")
137 |
138 | private val paramsWithIV: Crypto.Func[(Array[Byte], Array[Byte]), ParametersWithIV] =
139 | Crypto {
140 | case (key: Array[Byte], iv: Array[Byte]) ⇒
141 | params
142 | .andThen(
143 | Crypto.tryFn((kp: KeyParameter) ⇒ new ParametersWithIV(kp, iv))("Cannot generate key parameters with IV")
144 | )
145 | .run(key)
146 | }
147 |
148 | /**
149 | * Generate key parameters with IV if it is necessary
150 | * key Password
151 | * @return Optional IV and cipher parameters
152 | */
153 | val extDataWithParams: Crypto.Func[Array[Byte], (Option[Array[Byte]], CipherParameters)] =
154 | Crypto(
155 | key ⇒
156 | if (withIV) {
157 | val ivData = generateIV
158 |
159 | // setup cipher parameters with key and IV
160 | paramsWithIV(key, ivData).map(k ⇒ (Some(ivData), k))
161 | } else {
162 | params(key).map(k ⇒ (None, k))
163 | }
164 | )
165 |
166 | private val detachDataAndGetParams: Crypto.Func[(Array[Byte], Array[Char], Array[Byte], Boolean), DataWithParams] =
167 | Crypto {
168 | case (data, password, salt, withIV) ⇒
169 | if (withIV) {
170 | for {
171 | ivDataWithEncData ← detachIV(data -> IV_SIZE)
172 | key ← initSecretKey(password -> salt)
173 | // setup cipher parameters with key and IV
174 | paramsWithIV ← paramsWithIV(key, ivDataWithEncData.ivData)
175 | } yield DataWithParams(ivDataWithEncData.encData, paramsWithIV)
176 | } else {
177 | for {
178 | key ← initSecretKey(password -> salt)
179 | // setup cipher parameters with key
180 | params ← params(key)
181 | } yield DataWithParams(data, params)
182 | }
183 | }
184 |
185 | val decrypt: Crypto.Func[Array[Byte], Array[Byte]] =
186 | Crypto[Array[Byte], Array[Byte]] { input: Array[Byte] ⇒
187 | for {
188 | dataWithParams ← detachDataAndGetParams((input, password, salt, withIV))
189 | decData ← processData((dataWithParams, None, /*encrypt =*/ false))
190 | } yield decData
191 | }
192 |
193 | val encrypt: Crypto.Func[Array[Byte], Array[Byte]] =
194 | Crypto { input: Array[Byte] ⇒
195 | for {
196 | key ← initSecretKey(password -> salt)
197 | extDataWithParams ← extDataWithParams(key)
198 | encData ← processData((DataWithParams(input, extDataWithParams._2), extDataWithParams._1, /*encrypt =*/ true))
199 | } yield encData
200 |
201 | }
202 | }
203 |
204 | object AesCrypt {
205 |
206 | def build(password: ByteVector, withIV: Boolean, config: AesConfig): Crypto.Cipher[Array[Byte]] = {
207 | val aes = new AesCrypt(password.toHex.toCharArray, withIV, config)
208 | Crypto.Cipher(aes.encrypt, aes.decrypt)
209 | }
210 |
211 | }
212 |
--------------------------------------------------------------------------------
/hashsign/jvm/src/main/scala/fluence/crypto/ecdsa/Ecdsa.scala:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2017 Fluence Labs Limited
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU Affero General Public License as
6 | * published by the Free Software Foundation, either version 3 of the
7 | * License, or (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU Affero General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU Affero General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package fluence.crypto.ecdsa
19 |
20 | import java.math.BigInteger
21 | import java.security._
22 | import java.security.interfaces.ECPrivateKey
23 |
24 | import cats.instances.either._
25 | import cats.syntax.either._
26 | import fluence.crypto.KeyPair.Secret
27 | import fluence.crypto.{KeyPair, _}
28 | import fluence.crypto.hash.JdkCryptoHasher
29 | import fluence.crypto.signature.{SignAlgo, SignatureChecker, Signer}
30 | import org.bouncycastle.jce.ECNamedCurveTable
31 | import org.bouncycastle.jce.interfaces.ECPublicKey
32 | import org.bouncycastle.jce.provider.BouncyCastleProvider
33 | import org.bouncycastle.jce.spec.{ECParameterSpec, ECPrivateKeySpec, ECPublicKeySpec}
34 | import scodec.bits.ByteVector
35 |
36 | import scala.language.higherKinds
37 |
38 | /**
39 | * Elliptic Curve Digital Signature Algorithm
40 | * @param curveType http://www.bouncycastle.org/wiki/display/JA1/Supported+Curves+%28ECDSA+and+ECGOST%29
41 | * @param scheme https://bouncycastle.org/specifications.html
42 | */
43 | class Ecdsa(curveType: String, scheme: String, hasher: Option[Crypto.Hasher[Array[Byte], Array[Byte]]])
44 | extends JavaAlgorithm {
45 |
46 | import Ecdsa._
47 |
48 | val HEXradix = 16
49 |
50 | /**
51 | * Restores pair of keys from the known secret key.
52 | * The public key will be the same each method call with the same secret key.
53 | * sk secret key
54 | * @return key pair
55 | */
56 | val restorePairFromSecret: Crypto.Func[Secret, KeyPair] =
57 | Crypto(
58 | sk ⇒
59 | for {
60 | ecSpec ← Either.fromOption(
61 | Option(ECNamedCurveTable.getParameterSpec(curveType)),
62 | CryptoError("Parameter spec for the curve is not available.")
63 | )
64 | keyPair ← Crypto.tryUnit {
65 | val hex = sk.value.toHex
66 | val d = new BigInteger(hex, HEXradix)
67 | // to re-create public key from private we need to multiply known from curve point G with D (private key)
68 | // result will be point Q (public key)
69 | // https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
70 | val g = ecSpec.getG
71 | val q = g.multiply(d)
72 | val pk = ByteVector(q.getEncoded(true))
73 | KeyPair.fromByteVectors(pk, sk.value)
74 | }("Could not generate KeyPair from private key. Unexpected.")
75 | } yield keyPair
76 | )
77 |
78 | private def curveSpec: Crypto.Result[ECParameterSpec] =
79 | Crypto.tryUnit(ECNamedCurveTable.getParameterSpec(curveType).asInstanceOf[ECParameterSpec])(
80 | "Cannot get curve parameters"
81 | )
82 |
83 | private def getKeyPairGenerator =
84 | Crypto.tryUnit(KeyPairGenerator.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME))(
85 | "Cannot get key pair generator"
86 | )
87 |
88 | val generateKeyPair: Crypto.KeyPairGenerator =
89 | Crypto[Option[Array[Byte]], KeyPair] { input ⇒
90 | for {
91 | ecSpec ← Either.fromOption(
92 | Option(ECNamedCurveTable.getParameterSpec(curveType)),
93 | CryptoError("Parameter spec for the curve is not available.")
94 | )
95 | g ← getKeyPairGenerator
96 | _ ← Crypto.tryUnit {
97 | g.initialize(ecSpec, input.map(new SecureRandom(_)).getOrElse(new SecureRandom()))
98 | }(s"Could not initialize KeyPairGenerator")
99 | p ← Either.fromOption(Option(g.generateKeyPair()), CryptoError("Generated key pair is null"))
100 | keyPair ← Crypto.tryUnit {
101 | val pk = p.getPublic match {
102 | case pk: ECPublicKey => ByteVector(p.getPublic.asInstanceOf[ECPublicKey].getQ.getEncoded(true))
103 | case p =>
104 | throw new ClassCastException(s"Cannot cast public key (${p.getClass}) to Ed25519PublicKeyParameters")
105 | }
106 | val sk = p.getPrivate match {
107 | case sk: ECPrivateKey =>
108 | val bg = p.getPrivate.asInstanceOf[ECPrivateKey].getS
109 | ByteVector.fromValidHex(bg.toString(HEXradix))
110 | case s =>
111 | throw new ClassCastException(s"Cannot cast private key (${p.getClass}) to Ed25519PrivateKeyParameters")
112 | }
113 | KeyPair.fromByteVectors(pk, sk)
114 | }("Could not generate KeyPair")
115 | } yield keyPair
116 | }
117 |
118 | private def getKeyFactory =
119 | Crypto.tryUnit(KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME))(
120 | "Cannot get key factory instance"
121 | )
122 |
123 | private def getSignatureProvider =
124 | Crypto.tryUnit(Signature.getInstance(scheme, BouncyCastleProvider.PROVIDER_NAME))(
125 | "Cannot get signature instance"
126 | )
127 |
128 | private val signMessage: Crypto.Func[(BigInteger, Array[Byte]), Array[Byte]] =
129 | Crypto {
130 | case (
131 | privateKey,
132 | message
133 | ) ⇒
134 | for {
135 | ec ← curveSpec
136 | keySpec ← Crypto.tryUnit(new ECPrivateKeySpec(privateKey, ec))("Cannot read private key.")
137 | keyFactory ← getKeyFactory
138 | signProvider ← getSignatureProvider
139 | _ ← Crypto.tryUnit(signProvider.initSign(keyFactory.generatePrivate(keySpec)))("Cannot initSign")
140 | hash ← hasher.fold(
141 | message.asRight[CryptoError]
142 | )(_.apply(message))
143 |
144 | sign ← Crypto.tryUnit {
145 | signProvider.update(hash)
146 | signProvider.sign()
147 | }("Cannot sign message.")
148 |
149 | } yield sign
150 | }
151 |
152 | val sign: Crypto.Func[(KeyPair, ByteVector), signature.Signature] =
153 | signMessage
154 | .map(bb ⇒ fluence.crypto.signature.Signature(ByteVector(bb)))
155 | .local {
156 | case (keyPair, message) ⇒ (new BigInteger(keyPair.secretKey.value.toHex, HEXradix), message.toArray)
157 | }
158 |
159 | private val verifySign: Crypto.Func[(Array[Byte], Array[Byte], Array[Byte]), Unit] =
160 | Crypto {
161 | case (
162 | publicKey,
163 | signature,
164 | message
165 | ) ⇒
166 | for {
167 | ec ← curveSpec
168 | keySpec ← Crypto.tryUnit(new ECPublicKeySpec(ec.getCurve.decodePoint(publicKey), ec))(
169 | "Cannot read public key"
170 | )
171 | keyFactory ← getKeyFactory
172 | signProvider ← getSignatureProvider
173 | _ ← Crypto.tryUnit(
174 | signProvider.initVerify(keyFactory.generatePublic(keySpec))
175 | )("Cannot initVerify message")
176 |
177 | hash ← hasher.fold(
178 | message.asRight[CryptoError]
179 | )(_.apply(message))
180 |
181 | _ ← Crypto.tryUnit(signProvider.update(hash))("Cannot update message")
182 |
183 | verify ← Crypto.tryUnit(signProvider.verify(signature))("Cannot verify message")
184 |
185 | _ ← Either.cond(verify, (), CryptoError("Signature is not verified"))
186 | } yield ()
187 | }
188 |
189 | val verify: Crypto.Func[(KeyPair.Public, signature.Signature, ByteVector), Unit] =
190 | verifySign.local {
191 | case (
192 | publicKey,
193 | signature,
194 | message
195 | ) ⇒
196 | (publicKey.bytes, signature.bytes, message.toArray)
197 | }
198 | }
199 |
200 | object Ecdsa {
201 | //algorithm name in security provider
202 | val ECDSA = "ECDSA"
203 |
204 | /**
205 | * size of key is 256 bit
206 | * `secp256k1` refers to the parameters of the ECDSA curve
207 | * `NONEwithECDSA with sha-256 hasher` Preferably the size of the key is greater than or equal to the digest algorithm
208 | * don't use `SHA256WithECDSA` because of non-compatibility with javascript libraries
209 | */
210 | val ecdsa_secp256k1_sha256 = new Ecdsa("secp256k1", "NONEwithECDSA", Some(JdkCryptoHasher.Sha256))
211 |
212 | val signAlgo: SignAlgo = SignAlgo(
213 | name = "ecdsa_secp256k1_sha256",
214 | generateKeyPair = ecdsa_secp256k1_sha256.generateKeyPair,
215 | signer = kp ⇒
216 | Signer(
217 | kp.publicKey,
218 | Crypto { input ⇒
219 | ecdsa_secp256k1_sha256.sign(kp -> input)
220 | }
221 | ),
222 | checker = pk ⇒
223 | SignatureChecker(
224 | Crypto {
225 | case (
226 | signature: fluence.crypto.signature.Signature,
227 | plain: ByteVector
228 | ) ⇒
229 | ecdsa_secp256k1_sha256.verify(pk, signature, plain)
230 | }
231 | )
232 | )
233 | }
234 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU Affero General Public License
2 | =================================
3 |
4 | _Version 3, 19 November 2007_
5 | _Copyright © 2007 Free Software Foundation, Inc. <>_
6 |
7 | Everyone is permitted to copy and distribute verbatim copies
8 | of this license document, but changing it is not allowed.
9 |
10 | ## Preamble
11 |
12 | The GNU Affero General Public License is a free, copyleft license for
13 | software and other kinds of works, specifically designed to ensure
14 | cooperation with the community in the case of network server software.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | our General Public Licenses are intended to guarantee your freedom to
19 | share and change all versions of a program--to make sure it remains free
20 | software for all its users.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | Developers that use our General Public Licenses protect your rights
30 | with two steps: **(1)** assert copyright on the software, and **(2)** offer
31 | you this License which gives you legal permission to copy, distribute
32 | and/or modify the software.
33 |
34 | A secondary benefit of defending all users' freedom is that
35 | improvements made in alternate versions of the program, if they
36 | receive widespread use, become available for other developers to
37 | incorporate. Many developers of free software are heartened and
38 | encouraged by the resulting cooperation. However, in the case of
39 | software used on network servers, this result may fail to come about.
40 | The GNU General Public License permits making a modified version and
41 | letting the public access it on a server without ever releasing its
42 | source code to the public.
43 |
44 | The GNU Affero General Public License is designed specifically to
45 | ensure that, in such cases, the modified source code becomes available
46 | to the community. It requires the operator of a network server to
47 | provide the source code of the modified version running there to the
48 | users of that server. Therefore, public use of a modified version, on
49 | a publicly accessible server, gives the public access to the source
50 | code of the modified version.
51 |
52 | An older license, called the Affero General Public License and
53 | published by Affero, was designed to accomplish similar goals. This is
54 | a different license, not a version of the Affero GPL, but Affero has
55 | released a new version of the Affero GPL which permits relicensing under
56 | this license.
57 |
58 | The precise terms and conditions for copying, distribution and
59 | modification follow.
60 |
61 | ## TERMS AND CONDITIONS
62 |
63 | ### 0. Definitions
64 |
65 | “This License” refers to version 3 of the GNU Affero General Public License.
66 |
67 | “Copyright” also means copyright-like laws that apply to other kinds of
68 | works, such as semiconductor masks.
69 |
70 | “The Program” refers to any copyrightable work licensed under this
71 | License. Each licensee is addressed as “you”. “Licensees” and
72 | “recipients” may be individuals or organizations.
73 |
74 | To “modify” a work means to copy from or adapt all or part of the work
75 | in a fashion requiring copyright permission, other than the making of an
76 | exact copy. The resulting work is called a “modified version” of the
77 | earlier work or a work “based on” the earlier work.
78 |
79 | A “covered work” means either the unmodified Program or a work based
80 | on the Program.
81 |
82 | To “propagate” a work means to do anything with it that, without
83 | permission, would make you directly or secondarily liable for
84 | infringement under applicable copyright law, except executing it on a
85 | computer or modifying a private copy. Propagation includes copying,
86 | distribution (with or without modification), making available to the
87 | public, and in some countries other activities as well.
88 |
89 | To “convey” a work means any kind of propagation that enables other
90 | parties to make or receive copies. Mere interaction with a user through
91 | a computer network, with no transfer of a copy, is not conveying.
92 |
93 | An interactive user interface displays “Appropriate Legal Notices”
94 | to the extent that it includes a convenient and prominently visible
95 | feature that **(1)** displays an appropriate copyright notice, and **(2)**
96 | tells the user that there is no warranty for the work (except to the
97 | extent that warranties are provided), that licensees may convey the
98 | work under this License, and how to view a copy of this License. If
99 | the interface presents a list of user commands or options, such as a
100 | menu, a prominent item in the list meets this criterion.
101 |
102 | ### 1. Source Code
103 |
104 | The “source code” for a work means the preferred form of the work
105 | for making modifications to it. “Object code” means any non-source
106 | form of a work.
107 |
108 | A “Standard Interface” means an interface that either is an official
109 | standard defined by a recognized standards body, or, in the case of
110 | interfaces specified for a particular programming language, one that
111 | is widely used among developers working in that language.
112 |
113 | The “System Libraries” of an executable work include anything, other
114 | than the work as a whole, that **(a)** is included in the normal form of
115 | packaging a Major Component, but which is not part of that Major
116 | Component, and **(b)** serves only to enable use of the work with that
117 | Major Component, or to implement a Standard Interface for which an
118 | implementation is available to the public in source code form. A
119 | “Major Component”, in this context, means a major essential component
120 | (kernel, window system, and so on) of the specific operating system
121 | (if any) on which the executable work runs, or a compiler used to
122 | produce the work, or an object code interpreter used to run it.
123 |
124 | The “Corresponding Source” for a work in object code form means all
125 | the source code needed to generate, install, and (for an executable
126 | work) run the object code and to modify the work, including scripts to
127 | control those activities. However, it does not include the work's
128 | System Libraries, or general-purpose tools or generally available free
129 | programs which are used unmodified in performing those activities but
130 | which are not part of the work. For example, Corresponding Source
131 | includes interface definition files associated with source files for
132 | the work, and the source code for shared libraries and dynamically
133 | linked subprograms that the work is specifically designed to require,
134 | such as by intimate data communication or control flow between those
135 | subprograms and other parts of the work.
136 |
137 | The Corresponding Source need not include anything that users
138 | can regenerate automatically from other parts of the Corresponding
139 | Source.
140 |
141 | The Corresponding Source for a work in source code form is that
142 | same work.
143 |
144 | ### 2. Basic Permissions
145 |
146 | All rights granted under this License are granted for the term of
147 | copyright on the Program, and are irrevocable provided the stated
148 | conditions are met. This License explicitly affirms your unlimited
149 | permission to run the unmodified Program. The output from running a
150 | covered work is covered by this License only if the output, given its
151 | content, constitutes a covered work. This License acknowledges your
152 | rights of fair use or other equivalent, as provided by copyright law.
153 |
154 | You may make, run and propagate covered works that you do not
155 | convey, without conditions so long as your license otherwise remains
156 | in force. You may convey covered works to others for the sole purpose
157 | of having them make modifications exclusively for you, or provide you
158 | with facilities for running those works, provided that you comply with
159 | the terms of this License in conveying all material for which you do
160 | not control copyright. Those thus making or running the covered works
161 | for you must do so exclusively on your behalf, under your direction
162 | and control, on terms that prohibit them from making any copies of
163 | your copyrighted material outside their relationship with you.
164 |
165 | Conveying under any other circumstances is permitted solely under
166 | the conditions stated below. Sublicensing is not allowed; section 10
167 | makes it unnecessary.
168 |
169 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
170 |
171 | No covered work shall be deemed part of an effective technological
172 | measure under any applicable law fulfilling obligations under article
173 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
174 | similar laws prohibiting or restricting circumvention of such
175 | measures.
176 |
177 | When you convey a covered work, you waive any legal power to forbid
178 | circumvention of technological measures to the extent such circumvention
179 | is effected by exercising rights under this License with respect to
180 | the covered work, and you disclaim any intention to limit operation or
181 | modification of the work as a means of enforcing, against the work's
182 | users, your or third parties' legal rights to forbid circumvention of
183 | technological measures.
184 |
185 | ### 4. Conveying Verbatim Copies
186 |
187 | You may convey verbatim copies of the Program's source code as you
188 | receive it, in any medium, provided that you conspicuously and
189 | appropriately publish on each copy an appropriate copyright notice;
190 | keep intact all notices stating that this License and any
191 | non-permissive terms added in accord with section 7 apply to the code;
192 | keep intact all notices of the absence of any warranty; and give all
193 | recipients a copy of this License along with the Program.
194 |
195 | You may charge any price or no price for each copy that you convey,
196 | and you may offer support or warranty protection for a fee.
197 |
198 | ### 5. Conveying Modified Source Versions
199 |
200 | You may convey a work based on the Program, or the modifications to
201 | produce it from the Program, in the form of source code under the
202 | terms of section 4, provided that you also meet all of these conditions:
203 |
204 | * **a)** The work must carry prominent notices stating that you modified
205 | it, and giving a relevant date.
206 | * **b)** The work must carry prominent notices stating that it is
207 | released under this License and any conditions added under section 7.
208 | This requirement modifies the requirement in section 4 to
209 | “keep intact all notices”.
210 | * **c)** You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 | * **d)** If the work has interactive user interfaces, each must display
218 | Appropriate Legal Notices; however, if the Program has interactive
219 | interfaces that do not display Appropriate Legal Notices, your
220 | work need not make them do so.
221 |
222 | A compilation of a covered work with other separate and independent
223 | works, which are not by their nature extensions of the covered work,
224 | and which are not combined with it such as to form a larger program,
225 | in or on a volume of a storage or distribution medium, is called an
226 | “aggregate” if the compilation and its resulting copyright are not
227 | used to limit the access or legal rights of the compilation's users
228 | beyond what the individual works permit. Inclusion of a covered work
229 | in an aggregate does not cause this License to apply to the other
230 | parts of the aggregate.
231 |
232 | ### 6. Conveying Non-Source Forms
233 |
234 | You may convey a covered work in object code form under the terms
235 | of sections 4 and 5, provided that you also convey the
236 | machine-readable Corresponding Source under the terms of this License,
237 | in one of these ways:
238 |
239 | * **a)** Convey the object code in, or embodied in, a physical product
240 | (including a physical distribution medium), accompanied by the
241 | Corresponding Source fixed on a durable physical medium
242 | customarily used for software interchange.
243 | * **b)** Convey the object code in, or embodied in, a physical product
244 | (including a physical distribution medium), accompanied by a
245 | written offer, valid for at least three years and valid for as
246 | long as you offer spare parts or customer support for that product
247 | model, to give anyone who possesses the object code either **(1)** a
248 | copy of the Corresponding Source for all the software in the
249 | product that is covered by this License, on a durable physical
250 | medium customarily used for software interchange, for a price no
251 | more than your reasonable cost of physically performing this
252 | conveying of source, or **(2)** access to copy the
253 | Corresponding Source from a network server at no charge.
254 | * **c)** Convey individual copies of the object code with a copy of the
255 | written offer to provide the Corresponding Source. This
256 | alternative is allowed only occasionally and noncommercially, and
257 | only if you received the object code with such an offer, in accord
258 | with subsection 6b.
259 | * **d)** Convey the object code by offering access from a designated
260 | place (gratis or for a charge), and offer equivalent access to the
261 | Corresponding Source in the same way through the same place at no
262 | further charge. You need not require recipients to copy the
263 | Corresponding Source along with the object code. If the place to
264 | copy the object code is a network server, the Corresponding Source
265 | may be on a different server (operated by you or a third party)
266 | that supports equivalent copying facilities, provided you maintain
267 | clear directions next to the object code saying where to find the
268 | Corresponding Source. Regardless of what server hosts the
269 | Corresponding Source, you remain obligated to ensure that it is
270 | available for as long as needed to satisfy these requirements.
271 | * **e)** Convey the object code using peer-to-peer transmission, provided
272 | you inform other peers where the object code and Corresponding
273 | Source of the work are being offered to the general public at no
274 | charge under subsection 6d.
275 |
276 | A separable portion of the object code, whose source code is excluded
277 | from the Corresponding Source as a System Library, need not be
278 | included in conveying the object code work.
279 |
280 | A “User Product” is either **(1)** a “consumer product”, which means any
281 | tangible personal property which is normally used for personal, family,
282 | or household purposes, or **(2)** anything designed or sold for incorporation
283 | into a dwelling. In determining whether a product is a consumer product,
284 | doubtful cases shall be resolved in favor of coverage. For a particular
285 | product received by a particular user, “normally used” refers to a
286 | typical or common use of that class of product, regardless of the status
287 | of the particular user or of the way in which the particular user
288 | actually uses, or expects or is expected to use, the product. A product
289 | is a consumer product regardless of whether the product has substantial
290 | commercial, industrial or non-consumer uses, unless such uses represent
291 | the only significant mode of use of the product.
292 |
293 | “Installation Information” for a User Product means any methods,
294 | procedures, authorization keys, or other information required to install
295 | and execute modified versions of a covered work in that User Product from
296 | a modified version of its Corresponding Source. The information must
297 | suffice to ensure that the continued functioning of the modified object
298 | code is in no case prevented or interfered with solely because
299 | modification has been made.
300 |
301 | If you convey an object code work under this section in, or with, or
302 | specifically for use in, a User Product, and the conveying occurs as
303 | part of a transaction in which the right of possession and use of the
304 | User Product is transferred to the recipient in perpetuity or for a
305 | fixed term (regardless of how the transaction is characterized), the
306 | Corresponding Source conveyed under this section must be accompanied
307 | by the Installation Information. But this requirement does not apply
308 | if neither you nor any third party retains the ability to install
309 | modified object code on the User Product (for example, the work has
310 | been installed in ROM).
311 |
312 | The requirement to provide Installation Information does not include a
313 | requirement to continue to provide support service, warranty, or updates
314 | for a work that has been modified or installed by the recipient, or for
315 | the User Product in which it has been modified or installed. Access to a
316 | network may be denied when the modification itself materially and
317 | adversely affects the operation of the network or violates the rules and
318 | protocols for communication across the network.
319 |
320 | Corresponding Source conveyed, and Installation Information provided,
321 | in accord with this section must be in a format that is publicly
322 | documented (and with an implementation available to the public in
323 | source code form), and must require no special password or key for
324 | unpacking, reading or copying.
325 |
326 | ### 7. Additional Terms
327 |
328 | “Additional permissions” are terms that supplement the terms of this
329 | License by making exceptions from one or more of its conditions.
330 | Additional permissions that are applicable to the entire Program shall
331 | be treated as though they were included in this License, to the extent
332 | that they are valid under applicable law. If additional permissions
333 | apply only to part of the Program, that part may be used separately
334 | under those permissions, but the entire Program remains governed by
335 | this License without regard to the additional permissions.
336 |
337 | When you convey a copy of a covered work, you may at your option
338 | remove any additional permissions from that copy, or from any part of
339 | it. (Additional permissions may be written to require their own
340 | removal in certain cases when you modify the work.) You may place
341 | additional permissions on material, added by you to a covered work,
342 | for which you have or can give appropriate copyright permission.
343 |
344 | Notwithstanding any other provision of this License, for material you
345 | add to a covered work, you may (if authorized by the copyright holders of
346 | that material) supplement the terms of this License with terms:
347 |
348 | * **a)** Disclaiming warranty or limiting liability differently from the
349 | terms of sections 15 and 16 of this License; or
350 | * **b)** Requiring preservation of specified reasonable legal notices or
351 | author attributions in that material or in the Appropriate Legal
352 | Notices displayed by works containing it; or
353 | * **c)** Prohibiting misrepresentation of the origin of that material, or
354 | requiring that modified versions of such material be marked in
355 | reasonable ways as different from the original version; or
356 | * **d)** Limiting the use for publicity purposes of names of licensors or
357 | authors of the material; or
358 | * **e)** Declining to grant rights under trademark law for use of some
359 | trade names, trademarks, or service marks; or
360 | * **f)** Requiring indemnification of licensors and authors of that
361 | material by anyone who conveys the material (or modified versions of
362 | it) with contractual assumptions of liability to the recipient, for
363 | any liability that these contractual assumptions directly impose on
364 | those licensors and authors.
365 |
366 | All other non-permissive additional terms are considered “further
367 | restrictions” within the meaning of section 10. If the Program as you
368 | received it, or any part of it, contains a notice stating that it is
369 | governed by this License along with a term that is a further
370 | restriction, you may remove that term. If a license document contains
371 | a further restriction but permits relicensing or conveying under this
372 | License, you may add to a covered work material governed by the terms
373 | of that license document, provided that the further restriction does
374 | not survive such relicensing or conveying.
375 |
376 | If you add terms to a covered work in accord with this section, you
377 | must place, in the relevant source files, a statement of the
378 | additional terms that apply to those files, or a notice indicating
379 | where to find the applicable terms.
380 |
381 | Additional terms, permissive or non-permissive, may be stated in the
382 | form of a separately written license, or stated as exceptions;
383 | the above requirements apply either way.
384 |
385 | ### 8. Termination
386 |
387 | You may not propagate or modify a covered work except as expressly
388 | provided under this License. Any attempt otherwise to propagate or
389 | modify it is void, and will automatically terminate your rights under
390 | this License (including any patent licenses granted under the third
391 | paragraph of section 11).
392 |
393 | However, if you cease all violation of this License, then your
394 | license from a particular copyright holder is reinstated **(a)**
395 | provisionally, unless and until the copyright holder explicitly and
396 | finally terminates your license, and **(b)** permanently, if the copyright
397 | holder fails to notify you of the violation by some reasonable means
398 | prior to 60 days after the cessation.
399 |
400 | Moreover, your license from a particular copyright holder is
401 | reinstated permanently if the copyright holder notifies you of the
402 | violation by some reasonable means, this is the first time you have
403 | received notice of violation of this License (for any work) from that
404 | copyright holder, and you cure the violation prior to 30 days after
405 | your receipt of the notice.
406 |
407 | Termination of your rights under this section does not terminate the
408 | licenses of parties who have received copies or rights from you under
409 | this License. If your rights have been terminated and not permanently
410 | reinstated, you do not qualify to receive new licenses for the same
411 | material under section 10.
412 |
413 | ### 9. Acceptance Not Required for Having Copies
414 |
415 | You are not required to accept this License in order to receive or
416 | run a copy of the Program. Ancillary propagation of a covered work
417 | occurring solely as a consequence of using peer-to-peer transmission
418 | to receive a copy likewise does not require acceptance. However,
419 | nothing other than this License grants you permission to propagate or
420 | modify any covered work. These actions infringe copyright if you do
421 | not accept this License. Therefore, by modifying or propagating a
422 | covered work, you indicate your acceptance of this License to do so.
423 |
424 | ### 10. Automatic Licensing of Downstream Recipients
425 |
426 | Each time you convey a covered work, the recipient automatically
427 | receives a license from the original licensors, to run, modify and
428 | propagate that work, subject to this License. You are not responsible
429 | for enforcing compliance by third parties with this License.
430 |
431 | An “entity transaction” is a transaction transferring control of an
432 | organization, or substantially all assets of one, or subdividing an
433 | organization, or merging organizations. If propagation of a covered
434 | work results from an entity transaction, each party to that
435 | transaction who receives a copy of the work also receives whatever
436 | licenses to the work the party's predecessor in interest had or could
437 | give under the previous paragraph, plus a right to possession of the
438 | Corresponding Source of the work from the predecessor in interest, if
439 | the predecessor has it or can get it with reasonable efforts.
440 |
441 | You may not impose any further restrictions on the exercise of the
442 | rights granted or affirmed under this License. For example, you may
443 | not impose a license fee, royalty, or other charge for exercise of
444 | rights granted under this License, and you may not initiate litigation
445 | (including a cross-claim or counterclaim in a lawsuit) alleging that
446 | any patent claim is infringed by making, using, selling, offering for
447 | sale, or importing the Program or any portion of it.
448 |
449 | ### 11. Patents
450 |
451 | A “contributor” is a copyright holder who authorizes use under this
452 | License of the Program or a work on which the Program is based. The
453 | work thus licensed is called the contributor's “contributor version”.
454 |
455 | A contributor's “essential patent claims” are all patent claims
456 | owned or controlled by the contributor, whether already acquired or
457 | hereafter acquired, that would be infringed by some manner, permitted
458 | by this License, of making, using, or selling its contributor version,
459 | but do not include claims that would be infringed only as a
460 | consequence of further modification of the contributor version. For
461 | purposes of this definition, “control” includes the right to grant
462 | patent sublicenses in a manner consistent with the requirements of
463 | this License.
464 |
465 | Each contributor grants you a non-exclusive, worldwide, royalty-free
466 | patent license under the contributor's essential patent claims, to
467 | make, use, sell, offer for sale, import and otherwise run, modify and
468 | propagate the contents of its contributor version.
469 |
470 | In the following three paragraphs, a “patent license” is any express
471 | agreement or commitment, however denominated, not to enforce a patent
472 | (such as an express permission to practice a patent or covenant not to
473 | sue for patent infringement). To “grant” such a patent license to a
474 | party means to make such an agreement or commitment not to enforce a
475 | patent against the party.
476 |
477 | If you convey a covered work, knowingly relying on a patent license,
478 | and the Corresponding Source of the work is not available for anyone
479 | to copy, free of charge and under the terms of this License, through a
480 | publicly available network server or other readily accessible means,
481 | then you must either **(1)** cause the Corresponding Source to be so
482 | available, or **(2)** arrange to deprive yourself of the benefit of the
483 | patent license for this particular work, or **(3)** arrange, in a manner
484 | consistent with the requirements of this License, to extend the patent
485 | license to downstream recipients. “Knowingly relying” means you have
486 | actual knowledge that, but for the patent license, your conveying the
487 | covered work in a country, or your recipient's use of the covered work
488 | in a country, would infringe one or more identifiable patents in that
489 | country that you have reason to believe are valid.
490 |
491 | If, pursuant to or in connection with a single transaction or
492 | arrangement, you convey, or propagate by procuring conveyance of, a
493 | covered work, and grant a patent license to some of the parties
494 | receiving the covered work authorizing them to use, propagate, modify
495 | or convey a specific copy of the covered work, then the patent license
496 | you grant is automatically extended to all recipients of the covered
497 | work and works based on it.
498 |
499 | A patent license is “discriminatory” if it does not include within
500 | the scope of its coverage, prohibits the exercise of, or is
501 | conditioned on the non-exercise of one or more of the rights that are
502 | specifically granted under this License. You may not convey a covered
503 | work if you are a party to an arrangement with a third party that is
504 | in the business of distributing software, under which you make payment
505 | to the third party based on the extent of your activity of conveying
506 | the work, and under which the third party grants, to any of the
507 | parties who would receive the covered work from you, a discriminatory
508 | patent license **(a)** in connection with copies of the covered work
509 | conveyed by you (or copies made from those copies), or **(b)** primarily
510 | for and in connection with specific products or compilations that
511 | contain the covered work, unless you entered into that arrangement,
512 | or that patent license was granted, prior to 28 March 2007.
513 |
514 | Nothing in this License shall be construed as excluding or limiting
515 | any implied license or other defenses to infringement that may
516 | otherwise be available to you under applicable patent law.
517 |
518 | ### 12. No Surrender of Others' Freedom
519 |
520 | If conditions are imposed on you (whether by court order, agreement or
521 | otherwise) that contradict the conditions of this License, they do not
522 | excuse you from the conditions of this License. If you cannot convey a
523 | covered work so as to satisfy simultaneously your obligations under this
524 | License and any other pertinent obligations, then as a consequence you may
525 | not convey it at all. For example, if you agree to terms that obligate you
526 | to collect a royalty for further conveying from those to whom you convey
527 | the Program, the only way you could satisfy both those terms and this
528 | License would be to refrain entirely from conveying the Program.
529 |
530 | ### 13. Remote Network Interaction; Use with the GNU General Public License
531 |
532 | Notwithstanding any other provision of this License, if you modify the
533 | Program, your modified version must prominently offer all users
534 | interacting with it remotely through a computer network (if your version
535 | supports such interaction) an opportunity to receive the Corresponding
536 | Source of your version by providing access to the Corresponding Source
537 | from a network server at no charge, through some standard or customary
538 | means of facilitating copying of software. This Corresponding Source
539 | shall include the Corresponding Source for any work covered by version 3
540 | of the GNU General Public License that is incorporated pursuant to the
541 | following paragraph.
542 |
543 | Notwithstanding any other provision of this License, you have
544 | permission to link or combine any covered work with a work licensed
545 | under version 3 of the GNU General Public License into a single
546 | combined work, and to convey the resulting work. The terms of this
547 | License will continue to apply to the part which is the covered work,
548 | but the work with which it is combined will remain governed by version
549 | 3 of the GNU General Public License.
550 |
551 | ### 14. Revised Versions of this License
552 |
553 | The Free Software Foundation may publish revised and/or new versions of
554 | the GNU Affero General Public License from time to time. Such new versions
555 | will be similar in spirit to the present version, but may differ in detail to
556 | address new problems or concerns.
557 |
558 | Each version is given a distinguishing version number. If the
559 | Program specifies that a certain numbered version of the GNU Affero General
560 | Public License “or any later version” applies to it, you have the
561 | option of following the terms and conditions either of that numbered
562 | version or of any later version published by the Free Software
563 | Foundation. If the Program does not specify a version number of the
564 | GNU Affero General Public License, you may choose any version ever published
565 | by the Free Software Foundation.
566 |
567 | If the Program specifies that a proxy can decide which future
568 | versions of the GNU Affero General Public License can be used, that proxy's
569 | public statement of acceptance of a version permanently authorizes you
570 | to choose that version for the Program.
571 |
572 | Later license versions may give you additional or different
573 | permissions. However, no additional obligations are imposed on any
574 | author or copyright holder as a result of your choosing to follow a
575 | later version.
576 |
577 | ### 15. Disclaimer of Warranty
578 |
579 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
580 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
581 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
582 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
583 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
584 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
585 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
586 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
587 |
588 | ### 16. Limitation of Liability
589 |
590 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
591 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
592 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
593 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
594 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
595 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
596 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
597 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
598 | SUCH DAMAGES.
599 |
600 | ### 17. Interpretation of Sections 15 and 16
601 |
602 | If the disclaimer of warranty and limitation of liability provided
603 | above cannot be given local legal effect according to their terms,
604 | reviewing courts shall apply local law that most closely approximates
605 | an absolute waiver of all civil liability in connection with the
606 | Program, unless a warranty or assumption of liability accompanies a
607 | copy of the Program in return for a fee.
608 |
609 | _END OF TERMS AND CONDITIONS_
610 |
611 | ## How to Apply These Terms to Your New Programs
612 |
613 | If you develop a new program, and you want it to be of the greatest
614 | possible use to the public, the best way to achieve this is to make it
615 | free software which everyone can redistribute and change under these terms.
616 |
617 | To do so, attach the following notices to the program. It is safest
618 | to attach them to the start of each source file to most effectively
619 | state the exclusion of warranty; and each file should have at least
620 | the “copyright” line and a pointer to where the full notice is found.
621 |
622 |
623 | Copyright (C)
624 |
625 | This program is free software: you can redistribute it and/or modify
626 | it under the terms of the GNU Affero General Public License as published by
627 | the Free Software Foundation, either version 3 of the License, or
628 | (at your option) any later version.
629 |
630 | This program is distributed in the hope that it will be useful,
631 | but WITHOUT ANY WARRANTY; without even the implied warranty of
632 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
633 | GNU Affero General Public License for more details.
634 |
635 | You should have received a copy of the GNU Affero General Public License
636 | along with this program. If not, see .
637 |
638 | Also add information on how to contact you by electronic and paper mail.
639 |
640 | If your software can interact with users remotely through a computer
641 | network, you should also make sure that it provides a way for users to
642 | get its source. For example, if your program is a web application, its
643 | interface could display a “Source” link that leads users to an archive
644 | of the code. There are many ways you could offer source, and different
645 | solutions will be better for different programs; see section 13 for the
646 | specific requirements.
647 |
648 | You should also get your employer (if you work as a programmer) or school,
649 | if any, to sign a “copyright disclaimer” for the program, if necessary.
650 | For more information on this, and how to apply and follow the GNU AGPL, see
651 | <>.
--------------------------------------------------------------------------------