folkertdev / elm-sha2 / SHA512

SHA-512 is a cryptographic hash function that gives 256 bits of security.


type alias Digest =
Internal.Digest

Abstract representation of a sha512 digest.

Creating digests

fromString : String -> Digest

Create a digest from a String.

"hello world"
    |> SHA512.fromString
    |> SHA512.toHex
--> "309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f"

fromBytes : Bytes -> Digest

Create a digest from a Bytes

import Bytes.Encode as Encode
import Bytes exposing (Bytes, Endianness(..))

buffer : Bytes
buffer = Encode.encode (Encode.unsignedInt32 BE 42)

SHA512.fromBytes buffer
    |> SHA512.toHex
    --> "08cc3f0991969ae44b05e92bcd8f6ece4dd4e9733a9288dcfff47325906c36ecab9a3c63e59411b3df1f6fed6a232c6a20bff3afff91b36689a41037cbe0b6a0"

fromByteValues : List Basics.Int -> Digest

Create a digest from integer byte values. Values are considered mod 256, which means that larger than 255 overflow.

SHA512.fromByteValues
    [72, 105, 33, 32, 240, 159, 152, 132]
--> SHA512.fromString "Hi! 😄"

[0x00, 0xFF, 0x34, 0xA5]
    |> SHA512.fromByteValues
    |> SHA512.toBase64
--> "El+WnnuwQuhuInw0BkdTlTj/MkFOE/Rx65xiLJxvw5PjAGZ9oow71/el2OGLAULzaFmREAfEy1MWSxNSfsnVgw=="

Formatting digests

toHex : Digest -> String

Represent the digest as a string of hexadecimal digits.

"And our friends are all aboard"
    |> SHA512.fromString
    |> SHA512.toHex
--> "5af050bf4b4f2fbb2f032f42521e2e46a1aff6dcd02176c31425d8777abbe5c818375de27fd8d83cd848621a85507d1bd19eb35c70152c0f8e77b9ba3104e669"

toBase64 : Digest -> String

Represent the digest as its base-64 encoding.

"Many more of them live next door"
    |> SHA512.fromString
    |> SHA512.toBase64
--> "cyr6xhwqW4Fk9Gm5R4h/dqFxkPOf/gPHKiI6t00qQFC8QJAP65IlZkS4YhdGxTvL7VPFzlSPAoXtPTxPAmVJrg=="

To binary data

toBytes : Digest -> Bytes

Turn a digest into Bytes.

The digest is stored as 8 big-endian 64-bit unsigned integers, so the width is 64 bytes or 512 bits.

toByteValues : Digest -> List Basics.Int

Get the individual byte values as integers.

"And the band begins to play"
    |> SHA512.fromString
    |> SHA512.toByteValues
--> [153,140,77,156,68,193,195,117,134,19,24,147,44,86,45,132,106,110,43,98,221,233,100,27,183,45,33,120,139,31,6,103,128,205,65,65,9,252,111,213,5,60,65,56,181,170,166,85,7,48,58,253,54,121,246,230,31,95,205,70,53,219,78,168]