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?
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.
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.
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.
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)
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())}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With