Crypto.sha256
func Crypto.sha256(bytes: Bytes): BytesCrypto.sha256 returns the 32-byte SHA-256 digest of bytes.
Details
- It hashes bytes. Turn text into bytes with
String.toBytes, which gives its UTF-8 encoding. - The digest is
Bytes, not text. Show it withEncoding.toHexorEncoding.toBase64.
Basic examples
Hash the bytes of a string. The digest renders as 32 bytes:
Crypto.sha256(String.toBytes("abc")) // Bytes(ba 78 16 bf 8f 01 cf ea 41 41 40 de 5d ae 22 23 b0 03 61 a3 96 17 7a 9c b4 10 ff 61 f2 00 15 ad)Encode the digest as hex, two lower-case digits per byte:
Crypto.sha256(String.toBytes("abc")) | Encoding.toHex() // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"Scope
Empty input has a digest of its own, 32 bytes like any other:
let empty = Crypto.sha256(String.toBytes(""))
empty.length() // 32
Encoding.toHex(empty) // "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"Text outside ASCII hashes as its UTF-8 bytes:
Crypto.sha256(String.toBytes("héllo 🐜")) | Encoding.toHex() // "1f4f5917fc00eb339334ecb0b46356f237527407a8b874a1ebad07ffe3c8d82a"Binary data needs no string at all:
let png = Bytes.fromArray([0x89, 0x50, 0x4e, 0x47])
Crypto.sha256(png) | Encoding.toHex() // "0f4636c78f65d3639ece5a064b5ae753e3408614a14fb18ab4d7540d2c248543"Encode the digest as base64 at the end of a pipe:
"abc" | String.toBytes() | Crypto.sha256() | Encoding.toBase64() // "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="The digest is Bytes like any other, so it indexes to a byte and compares by contents:
let d = Crypto.sha256(String.toBytes("abc"))
d[0] // 186
d == Crypto.sha256(String.toBytes("abc")) // trueApplications
Check a downloaded file against its published checksum:
func verify(path: string, expected: string): Result[bool, Error] {
let data = try (File.readBytes(path) | Result.wrapErr("verify ${path}"))
let hex = Crypto.sha256(data) | Encoding.toHex()
Result.ok(hex == expected.toLower())
}
let sum = "EDEAAFF3F1774AD2888673770C6D64097E391BC362D7D6FB34982DDF0EFD18CB"
println(try verify("release.tar.gz", sum))trueFind files with the same contents. The digest is Bytes, which compares by contents, so it serves as the key to group by:
type Upload = { name: string, data: Bytes }
let uploads = [
Upload{ name: "a.txt", data: String.toBytes("hello") },
Upload{ name: "b.txt", data: String.toBytes("world") },
Upload{ name: "c.txt", data: String.toBytes("hello") },
]
let duplicates = uploads
| Array.groupBy({ Crypto.sha256(x.data) })
| Map.values()
| Array.filter({ x.length() > 1 })
for group in duplicates {
println(group.map({ x.name }))
}["a.txt", "c.txt"]Name a cache entry after its contents, with a short prefix of the hex digest:
func cacheKey(text: string): string {
let hex = text | String.toBytes() | Crypto.sha256() | Encoding.toHex()
"cache-${hex.slice(0, 12)}"
}
println(cacheKey("SELECT * FROM users"))
println(cacheKey("SELECT * FROM users"))
println(cacheKey("SELECT * FROM orders"))cache-26e7e05427bc
cache-26e7e05427bc
cache-ecf344c50257Properties and relations
The digest is 32 bytes for every input length:
for n in [0, 1, 55, 56, 64, 1000] {
let input = Bytes.fromArray(Array.filled(n, 7))
assert(Crypto.sha256(input).length() == 32)
}The same bytes always give the same digest, however they were built:
let a = Crypto.sha256(String.toBytes("añt"))
let b = Crypto.sha256(Bytes.fromArray([0x61, 0xc3, 0xb1, 0x74]))
let c = Crypto.sha256(Bytes.concat([String.toBytes("añ"), String.toBytes("t")]))
assert(a == b && b == c)Inputs that differ in one byte give different digests:
let one = Crypto.sha256(String.toBytes("transfer 100"))
let two = Crypto.sha256(String.toBytes("transfer 900"))
assert(one != two)Possible issues
A string is not Bytes; convert it first:
let digest = Crypto.sha256("abc") // error: cannot use string where Bytes is expectedsha256 belongs to Crypto, not Bytes, so a dot call on Bytes does not find it. Use a pipe:
let b = String.toBytes("abc")
let digest = b.sha256() // error: Bytes has no field or function sha256
let piped = b | Crypto.sha256()A digest is not UTF-8 text. String.fromBytes returns null for it; encode it instead:
let d = Crypto.sha256(String.toBytes("abc"))
String.fromBytes(d) // null
Encoding.toHex(d).length() // 64Encoding.toHex writes lower-case digits, so a checksum published in upper case does not compare equal until it is lowered:
let hex = Crypto.sha256(String.toBytes("")) | Encoding.toHex()
let published = "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"
hex == published // false
hex == published.toLower() // trueThe digest of two pieces hashed apart is not the digest of the whole. Join the bytes first:
let whole = Crypto.sha256(String.toBytes("hello world"))
let parts = Bytes.concat([
Crypto.sha256(String.toBytes("hello ")),
Crypto.sha256(String.toBytes("world")),
])
let joined = Bytes.concat([String.toBytes("hello "), String.toBytes("world")])
whole == parts // false
whole == Crypto.sha256(joined) // trueA plain digest uses no key, so anyone can compute it. To prove a message came from someone who holds a secret, use Crypto.hmacSha256, and compare the result with a received signature using Crypto.equal:
let key = String.toBytes("secret")
let message = String.toBytes("amount=100")
let signature = Crypto.hmacSha256(key, message)
Crypto.equal(signature, Crypto.hmacSha256(key, message)) // trueSee also
Crypto.sha512 · Crypto.sha1 · Crypto.md5 · Crypto.hmacSha256 · Crypto.equal · Encoding.toHex · Encoding.toBase64 · String.toBytes · File.readBytes
