Crypto

Crypto module is a basic crypto toolbox for cryptographic hash and digital signature.

CryptoJVM also add a simple helper for SSL on JVM.

hash

import scodec.bits.ByteVector
import jbok.crypto._

val bytes = ByteVector("jbok".getBytes())
// bytes: ByteVector = Chunk(
//   View(scodec.bits.ByteVector$AtArray@22fb60f3, 0L, 4L)
// )
bytes.kec256.toHex
// res0: String = "ec2efe5a15b243d8e1de351847914f166c4ac52c1ecbebe6743503360511f728"
bytes.kec512.toHex
// res1: String = "5cc1aba4bd66bfdc928229ac41957ab8255afaf8ae1cf074eb5d4d0d2080092981e91049051c97e11683bb6aa84abfb2e1caf95938af41b102a96f391390756f"
bytes.sha256.toHex
// res2: String = "b6d2a9f078b043dd79ab2f19a591b3e3a62de67aa80da004ac2a6ddfb0bb0964"
bytes.ripemd160.toHex
// res3: String = "8f463e54903130beacfccc0a3c9d3754d42978b6"

signature

import scodec.bits.ByteVector
import jbok.crypto._
import jbok.crypto.signature._
import cats.effect.IO

val keyPair = Signature[ECDSA].generateKeyPair[IO]().unsafeRunSync()
// keyPair: KeyPair = KeyPair(
//   Public(Chunk(View(scodec.bits.ByteVector$AtArray@dd3d0a6, 0L, 64L))),
//   Secret(Chunk(View(scodec.bits.ByteVector$AtArray@3c964873, 1L, 32L)))
// )
val message = ByteVector("jbok".getBytes)
// message: ByteVector = Chunk(
//   View(scodec.bits.ByteVector$AtArray@7db72209, 0L, 4L)
// )
val chainId = BigInt(1)
// chainId: BigInt = 1
val signature = Signature[ECDSA].sign[IO](message.kec256.toArray, keyPair, chainId).unsafeRunSync()
// signature: CryptoSignature = CryptoSignature(
//   98641613839774298854436043207444874419672363612670819841564376685868853073403,
//   25367043290981739089092716016150212653042144050633816654991797974214572066888,
//   30
// )

Signature[ECDSA].recoverPublic(message.kec256.toArray, signature, chainId)
// res4: Option[KeyPair.Public] = Some(
//   Public(Chunk(View(scodec.bits.ByteVector$AtArray@2c7e2c5, 0L, 64L)))
// )

// change chainId
Signature[ECDSA].recoverPublic(message.kec256.toArray, signature, chainId + 1)
// res5: Option[KeyPair.Public] = None