Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA256 of data stream

I am having a use case where i am downloading the file from URL using GET request. Is it possible to calculate SHA256 of file stream without saving to disk or holding an entire object in memory?

like image 479
Rajeev Avatar asked Jul 24 '17 13:07

Rajeev


People also ask

What is SHA256 used for?

SHA-256 stands for Secure Hash Algorithm 256-bit and it's used for cryptographic security. Cryptographic hash algorithms produce irreversible and unique hashes. The larger the number of possible hashes, the smaller the chance that two values will create the same hash.

How does SHA256 encryption work?

SHA-256 is a patented cryptographic hash function that outputs a value that is 256 bits long. What is hashing? In encryption, data is transformed into a secure format that is unreadable unless the recipient has a key. In its encrypted form, the data may be of unlimited size, often just as long as when unencrypted.

Is it possible to break SHA256?

SHA 256 password cracking. Reaching the original data from the encrypted SHA256 output (hash) is only possible if each combination is tried and failed one by one.


2 Answers

This can be accomplished with a MessageDigest and Sink.fold.

First we need a function to create an empty digest and a function to update a digest with a ByteBuffer:

import java.security.MessageDigest
import java.nio.ByteBuffer

def emptySHA256Digest : MessageDigest = MessageDigest getInstance "SHA-256" 

val updateDigest : (MessageDigest, ByteBuffer) => MessageDigest = 
  (messageDigest, byteBuffer) => {
    messageDigest update byteBuffer
    messageDigest
  }

These two functions can then be used within a fold which is applied to the entity of an HttpResponse to update the digest with all ByteString values in the entity:

import akka.http.scaladsl.model.HttpResponse

val responseBodyToDigest : HttpResponse => Future[MessageDigest] = 
  (_ : HttpResponse)
    .entity
    .dataBytes
    .map(_.asByteBuffer)
    .runFold(emptySHA256Digest)(updateDigest)
like image 128
Ramón J Romero y Vigil Avatar answered Oct 24 '22 12:10

Ramón J Romero y Vigil


You would need Flow which will transform one data to another data. In your case, you want to transform plain text to sha256 text.

def digest(algorithm: String = "SHA-256"): Flow[ByteString, ByteString, NotUsed] = {
    Flow[ByteString].fold(MessageDigest.getInstance(algorithm)) {
        case (digest: MessageDigest, bytes:ByteString) => {digest.update(bytes.asByteBuffer); digest}}
          .map {case md: MessageDigest => ByteString(md.digest())}
}
like image 23
Abdhesh kumar Avatar answered Oct 24 '22 13:10

Abdhesh kumar