Using a scalaz stream to calculate digest

So, I was wondering how can I use stream-stream to generate a file digest using java.security.MessageDigest?

I would like to do this using the size of the constant memory buffer (e.g. 4 KB). I think I understand how to start by reading the file, but I'm afraid to understand how:

1) call digest.update(buf)for every 4KB, which is effectively a side effect for the Java MessageDigest instance, which I suppose should happen inside the scalaz-stream framework.

2) finally, call digest.digest()to get back the computed digest from inside the scalaz-stream frame somehow?

I think I understand how to get started:

import scalaz.stream._
import java.security.MessageDigest

val f = "/a/b/myfile.bin"
val bufSize = 4096

val digest = MessageDigest.getInstance("SHA-256")

Process.constant(bufSize).toSource
  .through(io.fileChunkR(f, bufSize))

! , ? , , , ( ) - - - , .to(), ? , , scalaz. , .

+4
2

0.4 scalaz-stream . hash java.security.MessageDigest . , :

import scalaz.concurrent.Task
import scalaz.stream._

object Sha1Sum extends App {
  val fileName = "testdata/celsius.txt"
  val bufferSize = 4096

  val sha1sum: Task[Option[String]] =
    Process.constant(bufferSize)
      .toSource
      .through(io.fileChunkR(fileName, bufferSize))
      .pipe(hash.sha1)
      .map(sum => s"${sum.toHex}  $fileName")
      .runLast

  sha1sum.run.foreach(println)
}

update() digest() hash.sha1 Process1.

+3

, - , , , :

import java.io._
import java.security.MessageDigest
import resource._
import scodec.bits.ByteVector
import scalaz._, Scalaz._
import scalaz.concurrent.Task
import scalaz.stream._
import scalaz.stream.io._

val f = "/a/b/myfile.bin"
val bufSize = 4096

val md = MessageDigest.getInstance("SHA-256")

def _digestResource(md: => MessageDigest): Sink[Task,ByteVector] =
      resource(Task.delay(md))(md => Task.delay(()))(
        md => Task.now((bytes: ByteVector) => Task.delay(md.update(bytes.toArray))))

Process.constant(4096).toSource
    .through(fileChunkR(f.getAbsolutePath, 4096))
    .to(_digestResource(md))
    .run
    .run

md.digest()

, , MessageDigest scalaz- .run md.digest().

...

0

All Articles