Crypto.randomBytes
func Crypto.randomBytes(n: int): BytesCrypto.randomBytes returns n bytes from the operating system's secure source of randomness. It panics if n < 0 or n is above 2^31 - 1.
Details
- The bytes come from the operating system's source of randomness, which nothing a program can see seeds, so no seed makes a run repeat them.
- Reading the operating system's source of randomness does not fail, so the result is
Bytes, not aResult.
Basic examples
Make 32 random bytes, enough for a secret key:
let key = Crypto.randomBytes(32)
key.length() // 32The bytes are rarely shown as they are. Encode them as text to print, store, or send them:
Crypto.randomBytes(16) | Encoding.toHex() | String.length() // 32Scope
A count of 0 gives empty Bytes:
Crypto.randomBytes(0) // Bytes()The count comes first, so a pipe passes it, and the parameter is named n:
16 | Crypto.randomBytes() | Bytes.length() // 16
Crypto.randomBytes(n: 8).length() // 8The result is Bytes, so every Bytes function applies to it, such as toArray for the byte values:
Crypto.randomBytes(4).toArray().length() // 4Applications
Make a session token as 64 hex digits:
func newSessionToken(): string {
Crypto.randomBytes(32) | Encoding.toHex()
}
let token = newSessionToken()
println(token.length())
println(token.toLower() == token)64
trueMake a token for a link, in the URL-safe Base64 alphabet, which has no + or /. 24 bytes give 32 characters with no padding:
let code = Crypto.randomBytes(24) | Encoding.toBase64(url: true)
let link = "https://example.com/reset?code=${code}"
println(code.length())
println(["+", "/", "="].every({ !code.contains(x) }))
println(link.length())32
true
63For a code people read aloud or type, map each random byte to a character of an alphabet. This alphabet has 32 characters and leaves out i, l, and o, which people misread as 1 and 0, and u, to keep 32 characters. 32 divides 256, so % 32 picks every character equally often:
let alphabet = "0123456789abcdefghjkmnpqrstvwxyz".chars()
func shortCode(n: int): string {
Crypto.randomBytes(n)
| Bytes.toArray()
| Array.map({ alphabet[int(x) % alphabet.length()] })
| String.join("")
}
let code = shortCode(10)
println(code.length())
println(code.chars().every({ alphabet.contains(x) }))10
trueKeep the alphabet at 2, 4, 8, 16, 32, 64, 128, or 256 characters. With another size, such as 36, % 36 picks the first characters more often than the rest.
Sign a message with a fresh key, then check a received signature against it with Crypto.equal:
let key = Crypto.randomBytes(32)
let message = "amount=100".toBytes()
let signature = Crypto.hmacSha256(key, message)
func verify(key: Bytes, message: Bytes, received: Bytes): bool {
Crypto.equal(Crypto.hmacSha256(key, message), received)
}
println(verify(key, message, signature))
println(verify(key, "amount=900".toBytes(), signature))
println(verify(Crypto.randomBytes(32), message, signature))true
false
falseProperties and relations
The result has n bytes, and its hex form has two digits per byte:
let bytes = Crypto.randomBytes(10)
assert(bytes.length() == 10)
assert(Encoding.toHex(bytes).length() == 20)Two calls of 16 bytes give the same bytes with a chance of 1 in 2^128:
assert(Crypto.randomBytes(16) != Crypto.randomBytes(16))Crypto.uuid reads the same source and formats the result as a version 4 UUID:
let id = Crypto.uuid()
assert(id.length() == 36)
assert(id.split("-")[2].startsWith("4"))Possible issues
A negative count panics:
Crypto.randomBytes(-1) // panic: Crypto.randomBytes needs a count of at least 0, got -1A count above 2^31 − 1 panics too:
Crypto.randomBytes(3000000000) // panic: Crypto.randomBytes needs a count of at most 2147483647, got 3000000000Random bytes are rarely valid UTF-8, so String.fromBytes returns null for most of them, and the type checker rejects using its result as a string. Encode the bytes with Encoding.toHex or Encoding.toBase64 instead:
let token: string = String.fromBytes(Crypto.randomBytes(16))
// error: cannot use string | null where string is expectedA Random generator built with a seed is not a source for keys or tokens: it gives the same values on every run, so anyone who knows the seed knows the values. Random.new() without a seed and Math.random are not fit for keys or tokens either; use Crypto.randomBytes. Two generators with one seed draw the same values:
let a = Random.new(42)
let b = Random.new(42)
assert(a.int(0, 1000000) == b.int(0, 1000000))See also
Crypto.uuid, Crypto.equal, Crypto.hmacSha256, Encoding.toHex, Encoding.toBase64, Bytes.length, Random.new
